JavaWeb 实现简单登录、注册功能
1.首先创建一个简单的动态Javaweb项目
2.然后手动建立文件目录:
项目创建好之后,在src下建几个包:
controller:控制器,负责转发请求,对请求进行处理,主要存放servlet;
dao:数据库管理,主要是写数据库操作方法;
model:存放实体类;
service:业务逻辑的处理;
util:存放工具类,在这里我主要是把数据库加载驱动和创立连接、关闭连接封装成了一个静态类。
ps:别忘了在lib文件夹里放入这个jar包,用以连接数据库。
3.下面直接贴上对应的代码:
src代码:
1 package com.maike.controller; 2 3 import java.io.IOException; 4 import javax.servlet.ServletException; 5 import javax.servlet.annotation.WebServlet; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 import com.maike.service.UserService; 11 import com.maike.service.UserServiceImpl; 12 13 /** 14 * Servlet implementation class RegisterServlet 15 */ 16 @WebServlet("/RegisterServlet") 17 public class RegisterServlet extends HttpServlet { 18 UserService userService = new UserServiceImpl(); 19 private static final long serialVersionUID = 1L; 20 21 /** 22 * @see HttpServlet#HttpServlet() 23 */ 24 public RegisterServlet() { 25 super(); 26 // TODO Auto-generated constructor stub 27 } 28 29 /** 30 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 31 */ 32 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 33 // TODO Auto-generated method stub 34 response.getWriter().append("Served at: ").append(request.getContextPath()); 35 } 36 37 /** 38 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 39 */ 40 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 41 // TODO Auto-generated method stub 42 request.setCharacterEncoding("utf-8"); 43 String userName = request.getParameter("userName"); 44 String userPwd = request.getParameter("userPwd"); 45 String userRePwd = request.getParameter("userRePwd"); 46 47 int k = userService.insertUser(userName,userPwd,userRePwd); 48 49 if(k > 0) { 50 request.getRequestDispatcher("login.jsp").forward(request, response); 51 }else { 52 request.getRequestDispatcher("register.jsp").forward(request, response); 53 } 54 } 55 56 }
1 package com.maike.controller; 2 3 import java.io.IOException; 4 import javax.servlet.ServletException; 5 import javax.servlet.annotation.WebServlet; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 import com.maike.service.UserService; 11 import com.maike.service.UserServiceImpl; 12 13 /** 14 * Servlet implementation class LoginServlet 15 */ 16 @WebServlet("/LoginServlet") 17 public class LoginServlet extends HttpServlet { 18 UserService userService = new UserServiceImpl(); 19 private static final long serialVersionUID = 1L; 20 21 /** 22 * @see HttpServlet#HttpServlet() 23 */ 24 public LoginServlet() { 25 super(); 26 // TODO Auto-generated constructor stub 27 } 28 29 /** 30 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 31 */ 32 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 33 // TODO Auto-generated method stub 34 response.getWriter().append("Served at: ").append(request.getContextPath()); 35 } 36 37 /** 38 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 39 */ 40 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 41 // TODO Auto-generated method stub 42 request.setCharacterEncoding("utf-8"); 43 String userName = request.getParameter("userName"); 44 String uesrPwd = request.getParameter("userPwd"); 45 46 int k = userService.judgeLogin(userName,uesrPwd); 47 if(k > 0) { 48 request.getRequestDispatcher("success.jsp").forward(request, response); 49 }else { 50 request.getRequestDispatcher("login.jsp").forward(request, response); 51 } 52 } 53 54 }
1 package com.maike.dao; 2 3 import com.maike.model.User; 4 5 public interface UserDao { 6 7 int insert(String userName,String userPwd); 8 User selectByName(String userName); 9 10 }
1 package com.maike.dao; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 8 import com.maike.model.User; 9 import com.maike.util.ConnectionUtil; 10 11 public class UserDaoImpl implements UserDao { 12 Connection con = null; 13 PreparedStatement pt = null; 14 ResultSet rs = null; 15 String sql; 16 17 @Override 18 public int insert(String userName, String userPwd) { 19 // TODO Auto-generated method stub 20 int k = 0; 21 sql = "insert into user value(null,?,?)"; 22 try { 23 con = ConnectionUtil.getConnection(); 24 pt = con.prepareStatement(sql); 25 pt.setString(1, userName); 26 pt.setString(2, userPwd); 27 k = pt.executeUpdate(); 28 } catch (SQLException e) { 29 // TODO Auto-generated catch block 30 e.printStackTrace(); 31 }finally { 32 ConnectionUtil.closeRe(con, pt); 33 } 34 return k; 35 } 36 37 @Override 38 public User selectByName(String userName) { 39 // TODO Auto-generated method stub 40 sql = "select * from user where user_name = ?"; 41 User user = new User(); 42 try { 43 con = ConnectionUtil.getConnection(); 44 pt = con.prepareStatement(sql); 45 pt.setString(1, userName); 46 rs = pt.executeQuery(); 47 48 while(rs.next()) { 49 user.setUserId(rs.getInt("user_id")); 50 user.setUserName(rs.getString("user_name")); 51 user.setUserPwd(rs.getString("user_pwd")); 52 } 53 } catch (SQLException e) { 54 // TODO Auto-generated catch block 55 e.printStackTrace(); 56 }finally { 57 ConnectionUtil.closeRe(con, pt, rs); 58 } 59 return user; 60 } 61 62 }
1 package com.maike.model; 2 3 public class User { 4 5 private int userId; 6 7 private String userName; 8 9 private String userPwd; 10 11 public int getUserId() { 12 return userId; 13 } 14 15 public void setUserId(int userId) { 16 this.userId = userId; 17 } 18 19 public String getUserName() { 20 return userName; 21 } 22 23 public void setUserName(String userName) { 24 this.userName = userName; 25 } 26 27 public String getUserPwd() { 28 return userPwd; 29 } 30 31 public void setUserPwd(String userPwd) { 32 this.userPwd = userPwd; 33 } 34 35 @Override 36 public String toString() { 37 return "User [userId=" + userId + ", userName=" + userName + ", userPwd=" + userPwd + "]"; 38 } 39 40 }
1 package com.maike.service; 2 3 public interface UserService { 4 5 int insertUser(String userName,String userPwd,String userRePwd); 6 int judgeLogin(String userName,String userPwd); 7 8 }
1 package com.maike.service; 2 3 import com.maike.dao.UserDao; 4 import com.maike.dao.UserDaoImpl; 5 import com.maike.model.User; 6 7 public class UserServiceImpl implements UserService { 8 UserDao userDao = new UserDaoImpl(); 9 10 /** 11 * insertUser: 实现注册功能.<br/> 12 */ 13 @Override 14 public int insertUser(String userName, String userPwd, String userRePwd) { 15 // TODO Auto-generated method stub 16 int k = 0; 17 if(userName == "" || userName == null || userPwd == "" || userRePwd == null) { 18 return k; 19 } 20 if(!userPwd.equals(userRePwd)) { 21 return k; 22 } 23 24 k = userDao.insert(userName,userPwd); 25 26 return k; 27 } 28 29 /** 30 * judgeLogin:登录判断 .<br/> 31 */ 32 @Override 33 public int judgeLogin(String userName, String userPwd) { 34 // TODO Auto-generated method stub 35 int k = 0; 36 if(userName == "" || userName == null || userPwd == ""|| userPwd == null) { 37 return k; 38 } 39 User user = userDao.selectByName(userName); 40 41 if(!userPwd.equals(user.getUserPwd())) { 42 k = 0; 43 }else { 44 k = 1; 45 } 46 return k; 47 } 48 49 }
1 package com.maike.util; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 9 public class ConnectionUtil { 10 private static String url = "jdbc:mysql://127.0.0.1/nanfeng?characterEncoding=utf8&useSSL=true"; 11 private static String rootName = "root"; 12 private static String rootPwd = "zz201608"; 13 14 private ConnectionUtil() {}; 15 16 static { 17 try { 18 /*加载驱动*/ 19 Class.forName("com.mysql.jdbc.Driver"); 20 } catch (ClassNotFoundException e) { 21 // TODO Auto-generated catch block 22 e.printStackTrace(); 23 } 24 } 25 26 /** 27 * getConnection:创建连接.<br/> 28 * @return 29 * @throws SQLException 30 */ 31 public static Connection getConnection() throws SQLException { 32 return DriverManager.getConnection(url,rootName,rootPwd); 33 } 34 35 /** 36 * closeRe:关闭连接.<br/> 37 * @param con 38 * @param pt 39 * @param rs 40 */ 41 public static void closeRe(Connection con,PreparedStatement pt,ResultSet rs) { 42 if(rs != null) { 43 try { 44 rs.close(); 45 } catch (SQLException e) { 46 // TODO Auto-generated catch block 47 e.printStackTrace(); 48 }finally { 49 if(pt != null) { 50 try { 51 pt.close(); 52 } catch (SQLException e) { 53 // TODO Auto-generated catch block 54 e.printStackTrace(); 55 }finally{ 56 if(con != null) { 57 try { 58 con.close(); 59 } catch (SQLException e) { 60 // TODO Auto-generated catch block 61 e.printStackTrace(); 62 } 63 } 64 } 65 } 66 } 67 } 68 } 69 70 /** 71 * closeRe:关闭连接.<br/> 72 * @param con 73 * @param pt 74 */ 75 public static void closeRe(Connection con,PreparedStatement pt) { 76 if(pt != null) { 77 try { 78 pt.close(); 79 } catch (SQLException e) { 80 // TODO Auto-generated catch block 81 e.printStackTrace(); 82 }finally { 83 if(con != null) { 84 try { 85 con.close(); 86 } catch (SQLException e) { 87 // TODO Auto-generated catch block 88 e.printStackTrace(); 89 } 90 } 91 } 92 } 93 } 94 95 }
jsp页面代码:
1 <%@ page language="java" contentType="text/html; charset=utf-8" 2 pageEncoding="utf-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 7 <title>登录页面</title> 8 </head> 9 <body> 10 <br><br><br> 11 <h3 align = "center">登录页面</h3> 12 <hr> 13 <form align = "center" action="LoginServlet" method="post"> 14 <table align = "center" border="0"> 15 <tr><td>用户名</td><td><input type="text" name="userName" ></td></tr> 16 <tr><td>密码</td><td><input type="password" name="userPwd" ></td></tr> 17 <tr><td align = "center"><input type="submit" value = "登录" style="color:blue" ></td><td align = "right"><button><a href = "register.jsp" style="color:blue" >注册</a></button></td></tr> 18 </table> 19 20 </form> 21 22 </body> 23 </html>
1 <%@ page language="java" contentType="text/html; charset=utf-8" 2 pageEncoding="utf-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 7 <title>注册页面</title> 8 </head> 9 <body> 10 <br><br><br> 11 <h3 align = "center">注册页面</h3> 12 <hr> 13 <form align = "center" action="RegisterServlet" method="post"> 14 <table align = "center" border="0"> 15 <tr><td>用户名</td><td><input type="text" name="userName" ></td></tr> 16 <tr><td>密码</td><td><input type="password" name="userPwd" ></td></tr> 17 <tr><td>确认密码</td><td><input type="password" name="userRePwd" ></td></tr> 18 <tr><td align = "center" colspan="2"><input type="submit" value = "注册" style="color:blue" ></td></tr> 19 </table> 20 21 </form> 22 </body> 23 </html>
创建数据库:
1 CREATE TABLE nanfeng.`user` ( 2 user_id INT NOT NULL AUTO_INCREMENT, 3 user_name varchar(100) NULL, 4 user_pwd varchar(100) NULL, 5 CONSTRAINT user_pk PRIMARY KEY (user_id) 6 ) 7 ENGINE=InnoDB 8 DEFAULT CHARSET=utf8 9 COLLATE=utf8_general_ci;
4.最后,启动服务器,界面效果出来了