Smbms-01超市管理系统分析总结
一,开发分析
1,搭建一个maven项目
2,配置Tomcat
3,测试tomcat 能否正确启动
4,导入项目中会遇到的jar包 (jsp,.servlet,mysql驱动 ,jstl,standard)
5,创建项目包结构
6,编写实体类:
ORM 映射:表-类映射

User类
1 package com.pao.pojo; 2 3 import java.util.Date; 4 5 public class User { 6 private Integer id; //id 7 private String userCode; //用户编码 8 private String userName; //用户名称 9 private String userPassword; //用户密码 10 private Integer gender; //性别 11 private Date birthday; //出生日期 12 private String phone; //电话 13 private String address; //地址 14 private Integer userRole; //用户角色 15 private Integer createdBy; //创建者 16 private Date creationDate; //创建时间 17 private Integer modifyBy; //更新者 18 private Date modifyDate; //更新时间 19 20 private Integer age;//年龄 21 22 private String userRoleName; //用户角色名称 23 24 25 public String getUserRoleName() { 26 return userRoleName; 27 } 28 public void setUserRoleName(String userRoleName) { 29 this.userRoleName = userRoleName; 30 } 31 public Integer getAge() { 32 /*long time = System.currentTimeMillis()-birthday.getTime(); 33 Integer age = Long.valueOf(time/365/24/60/60/1000).IntegerValue();*/ 34 Date date = new Date(); 35 Integer age = date.getYear()-birthday.getYear(); 36 return age; 37 } 38 public Integer getId() { 39 return id; 40 } 41 public void setId(Integer id) { 42 this.id = id; 43 } 44 public String getUserCode() { 45 return userCode; 46 } 47 public void setUserCode(String userCode) { 48 this.userCode = userCode; 49 } 50 public String getUserName() { 51 return userName; 52 } 53 public void setUserName(String userName) { 54 this.userName = userName; 55 } 56 public String getUserPassword() { 57 return userPassword; 58 } 59 public void setUserPassword(String userPassword) { 60 this.userPassword = userPassword; 61 } 62 public Integer getGender() { 63 return gender; 64 } 65 public void setGender(Integer gender) { 66 this.gender = gender; 67 } 68 public Date getBirthday() { 69 return birthday; 70 } 71 public void setBirthday(Date birthday) { 72 this.birthday = birthday; 73 } 74 public String getPhone() { 75 return phone; 76 } 77 public void setPhone(String phone) { 78 this.phone = phone; 79 } 80 public String getAddress() { 81 return address; 82 } 83 public void setAddress(String address) { 84 this.address = address; 85 } 86 public Integer getUserRole() { 87 return userRole; 88 } 89 public void setUserRole(Integer userRole) { 90 this.userRole = userRole; 91 } 92 public Integer getCreatedBy() { 93 return createdBy; 94 } 95 public void setCreatedBy(Integer createdBy) { 96 this.createdBy = createdBy; 97 } 98 public Date getCreationDate() { 99 return creationDate; 100 } 101 public void setCreationDate(Date creationDate) { 102 this.creationDate = creationDate; 103 } 104 public Integer getModifyBy() { 105 return modifyBy; 106 } 107 public void setModifyBy(Integer modifyBy) { 108 this.modifyBy = modifyBy; 109 } 110 public Date getModifyDate() { 111 return modifyDate; 112 } 113 public void setModifyDate(Date modifyDate) { 114 this.modifyDate = modifyDate; 115 } 116 }
Role类
1 package com.pao.pojo; 2 3 import java.util.Date; 4 5 public class Role { 6 7 private Integer id; //id 8 private String roleCode; //角色编码 9 private String roleName; //角色名称 10 private Integer createdBy; //创建者 11 private Date creationDate; //创建时间 12 private Integer modifyBy; //更新者 13 private Date modifyDate;//更新时间 14 15 public Integer getId() { 16 return id; 17 } 18 public void setId(Integer id) { 19 this.id = id; 20 } 21 public String getRoleCode() { 22 return roleCode; 23 } 24 public void setRoleCode(String roleCode) { 25 this.roleCode = roleCode; 26 } 27 public String getRoleName() { 28 return roleName; 29 } 30 public void setRoleName(String roleName) { 31 this.roleName = roleName; 32 } 33 public Integer getCreatedBy() { 34 return createdBy; 35 } 36 public void setCreatedBy(Integer createdBy) { 37 this.createdBy = createdBy; 38 } 39 public Date getCreationDate() { 40 return creationDate; 41 } 42 public void setCreationDate(Date creationDate) { 43 this.creationDate = creationDate; 44 } 45 public Integer getModifyBy() { 46 return modifyBy; 47 } 48 public void setModifyBy(Integer modifyBy) { 49 this.modifyBy = modifyBy; 50 } 51 public Date getModifyDate() { 52 return modifyDate; 53 } 54 public void setModifyDate(Date modifyDate) { 55 this.modifyDate = modifyDate; 56 } 57 58 }
Provider类
1 package com.pao.pojo; 2 3 import java.util.Date; 4 5 public class Provider { 6 7 private Integer id; //id 8 private String proCode; //供应商编码 9 private String proName; //供应商名称 10 private String proDesc; //供应商描述 11 private String proContact; //供应商联系人 12 private String proPhone; //供应商电话 13 private String proAddress; //供应商地址 14 private String proFax; //供应商传真 15 private Integer createdBy; //创建者 16 private Date creationDate; //创建时间 17 private Integer modifyBy; //更新者 18 private Date modifyDate;//更新时间 19 public Integer getId() { 20 return id; 21 } 22 public void setId(Integer id) { 23 this.id = id; 24 } 25 public String getProCode() { 26 return proCode; 27 } 28 public void setProCode(String proCode) { 29 this.proCode = proCode; 30 } 31 public String getProName() { 32 return proName; 33 } 34 public void setProName(String proName) { 35 this.proName = proName; 36 } 37 public String getProDesc() { 38 return proDesc; 39 } 40 public void setProDesc(String proDesc) { 41 this.proDesc = proDesc; 42 } 43 public String getProContact() { 44 return proContact; 45 } 46 public void setProContact(String proContact) { 47 this.proContact = proContact; 48 } 49 public String getProPhone() { 50 return proPhone; 51 } 52 public void setProPhone(String proPhone) { 53 this.proPhone = proPhone; 54 } 55 public String getProAddress() { 56 return proAddress; 57 } 58 public void setProAddress(String proAddress) { 59 this.proAddress = proAddress; 60 } 61 public String getProFax() { 62 return proFax; 63 } 64 public void setProFax(String proFax) { 65 this.proFax = proFax; 66 } 67 public Integer getCreatedBy() { 68 return createdBy; 69 } 70 public void setCreatedBy(Integer createdBy) { 71 this.createdBy = createdBy; 72 } 73 public Date getCreationDate() { 74 return creationDate; 75 } 76 public void setCreationDate(Date creationDate) { 77 this.creationDate = creationDate; 78 } 79 public Integer getModifyBy() { 80 return modifyBy; 81 } 82 public void setModifyBy(Integer modifyBy) { 83 this.modifyBy = modifyBy; 84 } 85 public Date getModifyDate() { 86 return modifyDate; 87 } 88 public void setModifyDate(Date modifyDate) { 89 this.modifyDate = modifyDate; 90 } 91 92 93 }
Bill类
1 package com.pao.pojo; 2 3 import java.math.BigDecimal; 4 import java.util.Date; 5 6 public class Bill { 7 private Integer id; //id 8 private String billCode; //账单编码 9 private String productName; //商品名称 10 private String productDesc; //商品描述 11 private String productUnit; //商品单位 12 private BigDecimal productCount; //商品数量 13 private BigDecimal totalPrice; //总金额 14 private Integer isPayment; //是否支付 15 private Integer providerId; //供应商ID 16 private Integer createdBy; //创建者 17 private Date creationDate; //创建时间 18 private Integer modifyBy; //更新者 19 private Date modifyDate;//更新时间 20 21 private String providerName;//供应商名称 22 23 24 public String getProviderName() { 25 return providerName; 26 } 27 public void setProviderName(String providerName) { 28 this.providerName = providerName; 29 } 30 public Integer getId() { 31 return id; 32 } 33 public void setId(Integer id) { 34 this.id = id; 35 } 36 public String getBillCode() { 37 return billCode; 38 } 39 public void setBillCode(String billCode) { 40 this.billCode = billCode; 41 } 42 public String getProductName() { 43 return productName; 44 } 45 public void setProductName(String productName) { 46 this.productName = productName; 47 } 48 public String getProductDesc() { 49 return productDesc; 50 } 51 public void setProductDesc(String productDesc) { 52 this.productDesc = productDesc; 53 } 54 public String getProductUnit() { 55 return productUnit; 56 } 57 public void setProductUnit(String productUnit) { 58 this.productUnit = productUnit; 59 } 60 public BigDecimal getProductCount() { 61 return productCount; 62 } 63 public void setProductCount(BigDecimal productCount) { 64 this.productCount = productCount; 65 } 66 public BigDecimal getTotalPrice() { 67 return totalPrice; 68 } 69 public void setTotalPrice(BigDecimal totalPrice) { 70 this.totalPrice = totalPrice; 71 } 72 public Integer getIsPayment() { 73 return isPayment; 74 } 75 public void setIsPayment(Integer isPayment) { 76 this.isPayment = isPayment; 77 } 78 79 public Integer getProviderId() { 80 return providerId; 81 } 82 public void setProviderId(Integer providerId) { 83 this.providerId = providerId; 84 } 85 public Integer getCreatedBy() { 86 return createdBy; 87 } 88 public void setCreatedBy(Integer createdBy) { 89 this.createdBy = createdBy; 90 } 91 public Date getCreationDate() { 92 return creationDate; 93 } 94 public void setCreationDate(Date creationDate) { 95 this.creationDate = creationDate; 96 } 97 public Integer getModifyBy() { 98 return modifyBy; 99 } 100 public void setModifyBy(Integer modifyBy) { 101 this.modifyBy = modifyBy; 102 } 103 public Date getModifyDate() { 104 return modifyDate; 105 } 106 public void setModifyDate(Date modifyDate) { 107 this.modifyDate = modifyDate; 108 } 109 110 111 }
7,编写基础工具类
db.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/smbms?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf-8&autoReconnect=true&allowPublicKeyRetrieval=true username=root password=123456
BaseDao类 操作数据库的基类
1 package com.pao.dao; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.sql.*; 6 import java.util.Properties; 7 8 //操作数据库的公共类 9 public class BaseDao { 10 private static String driver; 11 private static String url; 12 private static String username; 13 private static String password; 14 15 //静态代码块,类启动的时候就会加载,进行初始化 16 static { 17 18 Properties properties = new Properties(); 19 //通过类加载器进行数据的读取 把资源变成一个流 20 InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties"); 21 22 try { 23 properties.load(is); //加载流 24 } catch (IOException e) { 25 e.printStackTrace(); 26 } 27 //获取信息 28 driver = properties.getProperty("driver"); 29 url = properties.getProperty("url"); 30 username = properties.getProperty("username"); 31 password = properties.getProperty("password"); 32 33 } 34 35 //获取数库的连接 36 public static Connection getConnection (){ 37 Connection connection = null; 38 try { 39 Class.forName(driver); 40 connection = DriverManager.getConnection(url, username, password); 41 } catch (Exception e) { 42 e.printStackTrace(); 43 } 44 return connection; //提升作用域,之后再进行return 45 } 46 47 //编写查询工具类 查询的结果集:ResultSet 48 public static ResultSet execute(Connection connection,PreparedStatement preparedStatement, ResultSet resultSet, String sql,Object[] params) throws SQLException { 49 //进行预编译的sql 在后面直接执行就可以了不用加 resultSet = preparedStatement.executeQuery(sql); 50 preparedStatement = connection.prepareStatement(sql); 51 52 for (int i = 0; i <params.length; i++) { 53 //setObject,占位符从1开始,但是我们的数组是从0开始的 54 preparedStatement.setObject(i+1,params[i]); //这里是给预编译设定值 55 } 56 resultSet = preparedStatement.executeQuery(); //执行SQL 57 return resultSet; 58 } 59 60 //编写增删改的公共方法 61 public static int execute(Connection connection,PreparedStatement preparedStatement,String sql,Object[] params) throws SQLException { 62 //进行预编译 63 preparedStatement = connection.prepareStatement(sql); 64 65 for (int i = 0; i <params.length; i++) { 66 //setObject,占位符从1开始,但是我们的数组是从1开始的 67 preparedStatement.setObject(i+1,params[i]); 68 } 69 70 int updateRows = preparedStatement.executeUpdate(); 71 return updateRows; 72 } 73 74 //关闭连接,释放资源 75 public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){ 76 boolean flag = true; 77 if (resultSet!=null){ 78 try { 79 resultSet.close(); 80 //Gc回收 81 resultSet = null; 82 } catch (SQLException e) { 83 e.printStackTrace(); 84 flag=false; 85 } 86 } 87 if (connection!=null){ 88 try { 89 connection.close(); 90 //Gc回收 91 connection = null; 92 } catch (SQLException e) { 93 e.printStackTrace(); 94 flag=false; 95 } 96 } 97 if (preparedStatement!=null){ 98 try { 99 preparedStatement.close(); 100 //Gc回收 101 preparedStatement = null; 102 } catch (SQLException e) { 103 e.printStackTrace(); 104 flag=false; 105 } 106 } 107 return false; 108 } 109 110 111 }
字符编码过滤器 就是一个Filter过滤器 别忘记进行注册
1 package com.pao.filter; 2 3 import javax.servlet.*; 4 import java.io.IOException; 5 6 public class CharacterEncodingFilter implements Filter { 7 @Override 8 public void init(FilterConfig filterConfig) throws ServletException { 9 10 } 11 12 @Override 13 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 14 request.setCharacterEncoding("utf-8"); 15 response.setCharacterEncoding("utf-8"); 16 17 chain.doFilter(request,response); 18 } 19 20 @Override 21 public void destroy() { 22 23 } 24 }
8,导入静态资源
二,登陆功能的实现
实现流程

1,编写前端页面
2,设置首页
<!--设置欢迎界面 默认访问login界面-->
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
开发顺序从底层向上层开发:从操作数据库开始
3,编写dao层登陆用户的接口,和dao接口的实现类
UserDao类 (一个接口,一个实现类)
1 package com.pao.dao.user; 2 3 import com.mysql.jdbc.StringUtils; 4 import com.pao.pojo.Role; 5 import com.pao.pojo.User; 6 7 import java.sql.Connection; 8 import java.sql.SQLException; 9 import java.util.List; 10 11 public interface UserDao { 12 //得到登录的用户 13 public User getLoginUser(Connection connection, String userCode,String Password) throws SQLException; 14 15 // //修改当前用户的密码 16 public int updatePwd(Connection connection,int id,String password)throws SQLException; 17 18 //根据用户名或者角色查询用户总数 19 public int getUserCount(Connection connection, String username, int userRole)throws SQLException;; 20 21 //获取用户列表通过条件查询-userList 22 public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize)throws Exception; 23 24 25 }
1 package com.pao.dao.user; 2 3 import com.mysql.jdbc.StringUtils; 4 import com.pao.dao.BaseDao; 5 import com.pao.pojo.Role; 6 import com.pao.pojo.User; 7 8 import java.sql.Connection; 9 import java.sql.PreparedStatement; 10 import java.sql.ResultSet; 11 import java.sql.SQLException; 12 import java.util.ArrayList; 13 import java.util.List; 14 15 public class UserDaoImpl implements UserDao { 16 // 得到要登陆的用户 17 @Override 18 public User getLoginUser(Connection connection, String userCode,String Password) throws SQLException { 19 20 PreparedStatement pstm = null; 21 ResultSet rs = null; 22 User user = null; 23 24 if (connection != null){ 25 String sql = "select * from smbms_user where userCode=? and userPassword=?"; 26 //封装参数 27 Object[] params = {userCode,Password}; 28 rs = BaseDao.execute(connection,pstm,rs,sql,params); 29 30 if (rs.next()){ 31 user = new User(); 32 user.setId(rs.getInt("id")); 33 user.setUserCode(rs.getString("userCode")); 34 user.setUserName(rs.getString("userName")); 35 user.setUserPassword(rs.getString("userPassword")); 36 user.setGender(rs.getInt("gender")); 37 user.setBirthday(rs.getDate("birthday")); 38 user.setPhone(rs.getString("phone")); 39 user.setAddress(rs.getString("address")); 40 user.setUserRole(rs.getInt("userRole")); 41 user.setCreatedBy(rs.getInt("createdBy")); 42 user.setModifyDate(rs.getTimestamp("creationDate")); 43 user.setModifyBy(rs.getInt("modifyBy")); 44 user.setModifyDate(rs.getTimestamp("modifyDate")); 45 46 } 47 BaseDao.closeResource(null, pstm,rs); 48 49 } 50 return user; 51 } 52 53 //修改当前用户密码 54 @Override 55 public int updatePwd(Connection connection, int id, String password) throws SQLException { 56 57 PreparedStatement pstm = null; 58 59 int execute = 0; 60 if (connection != null){ 61 62 String sql = "update smbms_user set userPassword= ? where id = ?"; 63 64 Object[] params = {password,id}; 65 66 execute = BaseDao.execute(connection, pstm, sql, params); 67 BaseDao.closeResource(null,pstm,null); 68 } 69 70 return execute; 71 72 73 } 74 //根据用户名或者角色查询用户总数 75 @Override 76 public int getUserCount(Connection connection, String username, int userRole) throws SQLException { 77 PreparedStatement pstm = null; 78 ResultSet rs = null; 79 int count = 0; 80 if(connection != null){ 81 StringBuffer sql = new StringBuffer(); 82 sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id"); 83 84 List<Object> list = new ArrayList<Object>(); 85 86 if(!StringUtils.isNullOrEmpty(username)){ 87 sql.append(" and u.userName like ?"); 88 list.add("%"+username+"%"); 89 } 90 if(userRole > 0){ 91 sql.append(" and u.userRole = ?"); 92 list.add(userRole); 93 } 94 95 Object[] params = list.toArray(); 96 System.out.println("sql ----> " + sql.toString()); 97 rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params); 98 if(rs.next()){ 99 count = rs.getInt("count"); 100 } 101 BaseDao.closeResource(null, pstm, rs); 102 } 103 return count; 104 } 105 //获取用户列表通过条件查询-userList 106 107 @Override 108 public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception { 109 PreparedStatement pstm = null; 110 ResultSet rs = null; 111 List<User> userList = new ArrayList<User>(); 112 if(connection != null){ 113 StringBuffer sql = new StringBuffer(); 114 sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id"); 115 List<Object> list = new ArrayList<Object>(); 116 if(!StringUtils.isNullOrEmpty(userName)){ 117 sql.append(" and u.userName like ?"); 118 list.add("%"+userName+"%"); 119 } 120 //在数据库中分页使用 limit startIndex,pagesize; 总数 121 //当前页 (当前页-1)*页面大小 从 页开始 122 //0,5 1 0 01234 123 //5,5 2 5 56789 124 //10,5 3 10 10-14 125 if(userRole > 0){ 126 sql.append(" and u.userRole = ?"); 127 list.add(userRole); 128 } 129 sql.append(" order by creationDate DESC limit ?,?"); 130 currentPageNo = (currentPageNo-1)*pageSize; 131 list.add(currentPageNo); 132 list.add(pageSize); 133 134 Object[] params = list.toArray(); 135 System.out.println("sql ----> " + sql.toString()); 136 rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params); 137 while(rs.next()){ 138 User _user = new User(); 139 _user.setId(rs.getInt("id")); 140 _user.setUserCode(rs.getString("userCode")); 141 _user.setUserName(rs.getString("userName")); 142 _user.setGender(rs.getInt("gender")); 143 _user.setBirthday(rs.getDate("birthday")); 144 _user.setPhone(rs.getString("phone")); 145 _user.setUserRole(rs.getInt("userRole")); 146 _user.setUserRoleName(rs.getString("userRoleName")); 147 userList.add(_user); 148 } 149 BaseDao.closeResource(null, pstm, rs); 150 } 151 return userList; 152 } 153 154 155 }
4,编写业务层接口,和业务层实现类
package com.pao.service.user; import com.pao.pojo.User; import java.util.List; public interface UserService { //用户登录 public User login(String userCode,String password); // // //根据用户id, 修改当前用户的密码 public boolean updatePwd( int id, String pwd); // 查询记录数 public int getUserCount(String username,int userRole); // 根据条件查询用户列表 public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize); }
package com.pao.service.user; import com.pao.dao.BaseDao; import com.pao.dao.user.UserDao; import com.pao.dao.user.UserDaoImpl; import com.pao.pojo.User; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.List; public class UserServiceImpl implements UserService { //业务层都会调用dao层,所以我们要引入dao层 private UserDao userDao; public UserServiceImpl(){ userDao = new UserDaoImpl(); } @Override public User login(String userCode, String password) { Connection connection = null; User user = null; try { connection = BaseDao.getConnection(); //通过业务层调用对应的具体的数据库操作 user = userDao.getLoginUser(connection, userCode,password); } catch (SQLException e) { e.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return user; } // //修改密码 @Override public boolean updatePwd(int id, String pwd) { Connection connection = null; boolean flag =false; //修改密码 try { connection = BaseDao.getConnection(); if (userDao.updatePwd(connection,id,pwd)>0){ flag = true; } } catch (SQLException e) { e.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return flag; } //查询记录数 @Override public int getUserCount(String username, int userRole) { Connection connection = null; int count = 0; try { connection = BaseDao.getConnection(); count = userDao.getUserCount(connection, username,userRole); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ BaseDao.closeResource(connection, null, null); } return count; } //用户列表 @Override public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) { Connection connection = null; List<User> userList = null; System.out.println("queryUserName ---- > " + queryUserName); System.out.println("queryUserRole ---- > " + queryUserRole); System.out.println("currentPageNo ---- > " + currentPageNo); System.out.println("pageSize ---- > " + pageSize); try { connection = BaseDao.getConnection(); userList = userDao.getUserList(connection, queryUserName,queryUserRole,currentPageNo,pageSize); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ BaseDao.closeResource(connection, null, null); } return userList; } } // 这是一个测试类 // @Test // public void test(){ // // UserServiceImpl userService = new UserServiceImpl(); // User user = userService.login("admin", "1234567"); // System.out.println(user.getUserName()); // } // @Test // public void test(){ // // UserServiceImpl userService = new UserServiceImpl(); // int userCount = userService.getUserCount(null, 2); // System.out.println(userCount); // // }
5,编写servlet处理请求
package com.pao.servlet.user; import com.pao.pojo.User; import com.pao.service.user.UserService; import com.pao.service.user.UserServiceImpl; import com.pao.util.Constants; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; //这里用来处理登录的请求 public class LoginServlet extends HttpServlet { //servlet:控制层 调用业务层代码 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("LoginServlet...start"); //获取用用户的密码 从前端获取 String userCode = req.getParameter("userCode"); String userPassword = req.getParameter("userPassword"); //调用业务层和数据库中的密码进行对比 UserService userService = new UserServiceImpl(); User user = userService.login(userCode, userPassword);//这里已经把登录的人给查出来了 if (user!=null){//查有此人可以登录 //将用户的信息放到Session中, req.getSession().setAttribute(Constants.USER_SESSION,user); //登录成功跳转到后台首页 resp.sendRedirect("jsp/frame.jsp"); }else{//查无此人,无法登录成功 //转发回登录页面,随便提示用户名或密码错误 req.setAttribute("error","用户名或密码错误!"); req.getRequestDispatcher("login.jsp").forward(req,resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
设置一个常量来放置 Session
package com.pao.util; public class Constants { public final static String USER_SESSION = "userSession"; }
测试程序是否能正常访问
注销功能的实现
1 package com.pao.servlet.user; 2 3 import com.pao.util.Constants; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import java.io.IOException; 10 11 public class LogoutServlet extends HttpServlet { 12 @Override 13 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 14 //移除用户的session.USER_SESSION 15 req.getSession().removeAttribute(Constants.USER_SESSION); 16 resp.sendRedirect(req.getContextPath()+"/login.jsp");//返回登录页面 17 } 18 19 @Override 20 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 21 doGet(req, resp); 22 } 23 }
配置注销注册
1 <!--注销的注册--> 2 <servlet> 3 <servlet-name>LogoutServlet</servlet-name> 4 <servlet-class>com.pao.servlet.user.LogoutServlet</servlet-class> 5 </servlet> 6 <servlet-mapping> 7 <servlet-name>LogoutServlet</servlet-name> 8 <url-pattern>/jsp/logout.do</url-pattern> 9 </servlet-mapping>
登陆拦截优化
1 package com.pao.filter; 2 3 import com.pao.pojo.User; 4 import com.pao.util.Constants; 5 6 import javax.servlet.*; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import java.io.IOException; 10 11 public class SysFilter implements Filter { 12 @Override 13 public void init(FilterConfig filterConfig) throws ServletException { 14 15 } 16 17 @Override 18 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { 19 HttpServletRequest request = (HttpServletRequest) req; //这个request是为了获取Session 20 HttpServletResponse response = (HttpServletResponse) resp;//这个response是为了用于 重定向 21 //过滤器,从Session中获取用户信息 22 User user = (User) request.getSession().getAttribute(Constants.USER_SESSION); 23 if (user==null){//已经移除或注销或未登录 24 25 response.sendRedirect("/smbms/error.jsp"); 26 27 }else { 28 29 chain.doFilter(req,resp); 30 31 } 32 } 33 34 @Override 35 public void destroy() { 36 37 } 38 }
注册filter
1 <!--注册用户登录过滤器--> 2 <filter> 3 <filter-name>SysFilter</filter-name> 4 <filter-class>com.pao.filter.SysFilter</filter-class> 5 </filter> 6 <filter-mapping> 7 <filter-name>SysFilter</filter-name> 8 <url-pattern>/jsp/*</url-pattern> 9 </filter-mapping>
浙公网安备 33010602011771号