使用Servlet和jdbc创建用户登录验证
首先创建一个用户表,用来保存用户名 密码,并插入几条数据
mysql> desc user;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(20) | YES | | NULL | |
| password | varchar(50) | YES | | NULL | |
+----------+-------------+------+-----+---------+----------------+
创建语句,注意一定要设置password的长度超过41,因为插入数据时我们使用password函数,生成长度为41的字符串,
例如:
mysql> select password('aasas');
+-------------------------------------------+
| password('aasas') |
+-------------------------------------------+
| *462034BF6D04324F93F1F6CA352B23079A165972 |
+-------------------------------------------+
1 row in set (0.00 sec)
mysql> select length( password('aasas'));
+----------------------------+
| length( password('aasas')) |
+----------------------------+
| 41 |
+----------------------------+
1 row in set (1.76 sec)
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(20) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
插入数据:
mysql> insert into user(username,password) values('root',password('root'));
查看一下插入结果:此时密码已经变成一串字符串.
mysql> select * from user where username='root';
+----+----------+-------------------------------------------+
| id | username | password |
+----+----------+-------------------------------------------+
| 4 | root | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B |
+----+----------+-------------------------------------------+
1 row in set (0.00 sec)
2.创建一个java web project,新建一个名为user的类,使用jdbc链接数据库,把user表的数据拿出来和输入的用户名密码对比,并添加validate方法
如果用户名密码正确,返回true。之后注意将Mysql JDBC的driver copy到lib目录下,否则无法运行
package com.data; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class user { private static String userName; private static String password; 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 static boolean validate() { String url = "jdbc:mysql://localhost:3306/study"; String user= "root"; String dbpassword = "3edc4rfv"; boolean result = false; try { String driver ="com.mysql.jdbc.Driver"; Class.forName(driver); Connection con = DriverManager.getConnection(url,user, dbpassword); if(con==null){ System.out.println("can't open DBConnection"); } String sql = "select * from user where username=? and password=password(?)"; PreparedStatement pstmt=con.prepareStatement(sql); pstmt.setString(1, userName); pstmt.setString(2, password); System.out.println(sql); ResultSet rs=pstmt.executeQuery(); if(rs.next()) { System.out.println("PASS"); result=true; } else { System.out.println("FAIl"); result=false; } pstmt.close(); rs.close(); con.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } }
并新建一个Servlet,包名com.web,class name login.java,这里主要使用post方法,所以在dopost方法添加代码
将login.java 修改为这样:
package com.web; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.data.book; import com.data.user; public class login extends HttpServlet { /** * Constructor of the object. */ public login() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Add some codes doPost(request,response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getParameter("username"); request.getParameter("password"); request.getSession().setAttribute("user", request.getParameter("username")); //将user放在Attribute中 user user1=new user(); user1.setUserName(request.getParameter("username")); user1.setPassword(request.getParameter("password")); System.out.println(request.getParameter("username")+request.getParameter("password")); if(user1.validate()) { request.getRequestDispatcher("welcome.jsp").forward(request, response); //校验用户名密码正确,跳转到welcome.jsp } else { request.getRequestDispatcher("index.jsp").forward(request, response); //校验用户名密码不正确,跳转到index.jsp } } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
此时web.xml代码如下。可以使用login.do访问这个Servlet
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description>login Page</description> <display-name>login Page</display-name> <servlet-name>login</servlet-name> <servlet-class>com.web.login</servlet-class> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>/login.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
3.在jsp页面添加相应的action,在index.jsp的body标签之间添加,会生出登录界面,用户名 密码
<form action="login.do" method="post" > username<input type="text" name="username"> <br>password <input type="password" name="password"> <br> <input type="submit" value="login"> <input type="reset" value="cancel"/> </form>
4.添加welcome.jsp
在welcome.jsp body标签添加
Welcome <%=session.getAttribute("user") %><br>
5.加载工程
![](https://images2015.cnblogs.com/blog/418763/201610/418763-20161014225758390-402578379.gif)