Servlet案例1:用户登录
2018-06-18 03:31:23来源:未知 阅读 ()
数据库准备:
CREATE DATABASE web; USE web; CREATE TABLE users( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(64), PASSWORD VARCHAR(64), email VARCHAR(64) ); INSERT INTO users (username,PASSWORD,email) VALUES("tom","123","tom@qq.com"),("lucy","123","lucy@qq.com");
对应User类:
package domain; public class User { private int id; private String username; private String password; private String email; @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + "]"; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
前端页面:
login.html:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="/WEB2/login" method="post"> 用户名:<input type="text" name="username"><br/> 密码:<input type="password" name="password"><br/> <input type="submit" value="登录" > </form> </body> </html>
Servlet:
用到c3p0连接池,dbutils工具类,mysql驱动,注意导入相关包
utils包:
自定义连接池工具类:
package utils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DataSourceUtils { private static DataSource dataSource = new ComboPooledDataSource(); private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); // 直接可以获取一个连接池 public static DataSource getDataSource() { return dataSource; } // 获取连接对象 public static Connection getConnection() throws SQLException { Connection con = tl.get(); if (con == null) { con = dataSource.getConnection(); tl.set(con); } return con; } // 开启事务 public static void startTransaction() throws SQLException { Connection con = getConnection(); if (con != null) { con.setAutoCommit(false); } } // 事务回滚 public static void rollback() throws SQLException { Connection con = getConnection(); if (con != null) { con.rollback(); } } // 提交并且 关闭资源及从ThreadLocall中释放 public static void commitAndRelease() throws SQLException { Connection con = getConnection(); if (con != null) { con.commit(); // 事务提交 con.close();// 关闭资源 tl.remove();// 从线程绑定中移除 } } // 关闭资源方法 public static void closeConnection() throws SQLException { Connection con = getConnection(); if (con != null) { con.close(); } } public static void closeStatement(Statement st) throws SQLException { if (st != null) { st.close(); } } public static void closeResultSet(ResultSet rs) throws SQLException { if (rs != null) { rs.close(); } } }
c3p0-config.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="user">root</property> <property name="password">xuyiqing</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql:///web</property> </default-config> </c3p0-config>
核心类:
package login; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import domain.User; import utils.DataSourceUtils; public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.获取用户名密码 String username = request.getParameter("username"); String password = request.getParameter("password"); //2.数据库中验证 QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "select * from users where username=? and password=?"; User user = null; try { user = runner.query(sql,new BeanHandler<User>(User.class) ,username,password); } catch (SQLException e) { e.printStackTrace(); } if(user!=null){ //登录成功 response.getWriter().write(user.toString()); }else { //登录失败 response.getWriter().write("Sorry!Your username or password is wrong."); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
web.xml配置:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>WEB2</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>LoginServlet</display-name> <servlet-name>LoginServlet</servlet-name> <servlet-class>login.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> </web-app>
完成!
访问http://localhost:8080/WEB2/login.html
输入正确的用户名和密码点击登录
结果如下:
完成!
成功!
接下来,提升功能:
统计成功登录的人数:
package login; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import domain.User; import utils.DataSourceUtils; public class LoginServlet extends HttpServlet { @Override public void init() throws ServletException { int count = 0; // 域对象 this.getServletContext().setAttribute("count", count); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.获取用户名密码 String username = request.getParameter("username"); String password = request.getParameter("password"); // 2.数据库中验证 QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "select * from users where username=? and password=?"; User user = null; try { user = runner.query(sql, new BeanHandler<User>(User.class), username, password); } catch (SQLException e) { e.printStackTrace(); } if (user != null) { // 登录成功 // 利用域对象的方法 ServletContext context = this.getServletContext(); Integer count = (Integer) context.getAttribute("count"); count++; response.getWriter().write(user.toString() + "You are the " + count + " person to log in successfully"); context.setAttribute("count", count); } else { // 登录失败 response.getWriter().write("Sorry!Your username or password is wrong."); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:Java基础(三)选择和循环结构
下一篇:JavaSE笔记-集合
- Java--反射(框架设计的灵魂)案例 2020-06-11
- Dubbo+Zookeeper集群案例 2020-06-09
- Invalid [xxx] in servlet mapping 、 <url-pattern& 2020-06-07
- SpringBoot定时任务如何正确运用?案例详解 2020-06-05
- Java Spring注入一个接口的多个实现类在map里如何实现?案 2020-06-04
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash