13. SMBMS
准备工作:数据库搭建
项目如何搭建?
13.1 项目搭建准备工作
-
搭建一个maven web项目
-
配置tomcat
-
测试项目是否能跑起来
-
导入项目中需要的jar包
jsp,Servlet,mysql驱动,jstl,stand。。。
-
创建项目包结构
-
编写实体类
ORM映射:表–类对应
-
编写基础公共类
-
数据库配置文件
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306?useSSL=true&useUnicode=true&characterEncoding=UTF-8 username=root password=020113
-
编写字符编码过滤器
<!-- 字符编码过滤器--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.Yurrize.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
-
-
导入静态资源
13.2 登录功能实现
-
编写前端页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>系统登录 - 超市订单管理系统</title> <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/css/style.css" /> <script type="text/javascript"> /* if(top.location!=self.location){ top.location=self.location; } */ </script> </head> <body class="login_bg"> <section class="loginBox"> <header class="loginHeader"> <h1>超市订单管理系统</h1> </header> <section class="loginCont"> <form class="loginForm" action="${pageContext.request.contextPath }/login.do" name="actionForm" id="actionForm" method="post" > <div class="info">${error }</div> <div class="inputbox"> <label for="userCode">用户名:</label> <input type="text" class="input-text" id="userCode" name="userCode" placeholder="请输入用户名" required/> </div> <div class="inputbox"> <label for="userPassword">密码:</label> <input type="password" id="userPassword" name="userPassword" placeholder="请输入密码" required/> </div> <div class="subBtn"> <input type="submit" value="登录"/> <input type="reset" value="重置"/> </div> </form> </section> </section> </body> </html>
-
设置首页
<!-- 设置欢迎页面--> <welcome-file-list> <welcome-file>./WEB-INF/login.jsp</welcome-file> </welcome-file-list>
-
mybatis实现查询账号密码功能
<select id="getLoginUser" resultType="User"> select * from smbms.smbms_user where userCode=#{userCode} and userPassword=#{userPassword} </select> </mapper>
-
Servlet实现
public class LoginServlet extends HttpServlet { @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"); //和数据库种密码进行对比 SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getLoginUser(userCode,userPassword); if(user!=null){ //查询到这个人,将用户信息放在session中 req.getSession().setAttribute(Constants.USER_SESSION,user); //登录成功后跳转内部主页 resp.sendRedirect("jsp/frame.jsp"); }else { //查无此人,转发回登陆页面 req.setAttribute("error","用户名或者密码不正确"); req.getRequestDispatcher("/WEB-INF/login.jsp").forward(req,resp); } sqlSession.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
13.3 登录功能优化
13.3.1 实现注销功能
思路:移除Session,返回主页
public class CancellationServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//移除用户的Session
req.getSession().removeAttribute(Constants.USER_SESSION);
resp.sendRedirect(req.getContextPath()+"/login.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
登录拦截优化(未登录不能继续访问)
public class SysFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//过滤器,从Session中获取用户
User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
if(user==null){
//已经被移除或注销了,或者未登录
response.sendRedirect("/smbms/error.jsp");
}else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
public void destroy() {
}
}
注册xml
<!-- 用户登录过滤器-->
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.Yurrize.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>
13.4 密码修改功能实现
-
导入前端代码
<li><a href="${pageContext.request.contextPath }/jsp/pwdmodify">密码修改</a></li>
-
编写数据库代码
<update id="updatePwd" parameterType="com.Yurrize.pojo.User"> update smbms.smbms_user set userPassword=#{userPassword} where id=#{id} </update>
-
编写service类
public boolean updatePwd(int id, String password) { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int flagNum = mapper.updatePwd(id, password); if(flagNum>0){ System.out.println("密码修改成功"); sqlSession.close(); return true; }else { System.out.println("密码修改失败"); sqlSession.close(); return false; } }
-
编写servlet类
public class UserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //从Session中拿id Object attribute = req.getSession().getAttribute(Constants.USER_SESSION); String newpassword = req.getParameter("newpassword"); boolean flag; if(attribute!=null&& StringUtils.isNullOrEmpty(newpassword)){ UserServiceImpl userService = new UserServiceImpl(); flag=userService.updatePwd(((User)attribute).getId(),newpassword); if(flag){ req.setAttribute("message","修改密码成功,请推出,使用新密码登录"); //移除当前session req.getSession().removeAttribute(Constants.USER_SESSION); }else { req.setAttribute("message","修改密码失败"); } req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
13.5 优化密码修改使用Ajax
-
导入依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.80</version> </dependency>
-
编写实体类
//验证旧密码 public void pwdModify(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{ Object o = req.getSession().getAttribute(Constants.USER_SESSION); String oldpassword = req.getParameter("oldpassword"); //万能的Map HashMap<String, String> resultMap = new HashMap<String, String>(); if (o==null){//Session过期,失效 resultMap.put("result","SessionError"); }else if(StringUtils.isNullOrEmpty(oldpassword)){ resultMap.put("result","error"); }else { String userPassword = ((User) o).getUserPassword(); if (oldpassword.equals(userPassword)){ resultMap.put("result","true"); }else { resultMap.put("result","false"); } } resp.setContentType("application/json"); PrintWriter writer = resp.getWriter(); //阿里巴巴的工具类,转换格式的 writer.write(JSONArray.toJSONString(resultMap)); writer.flush(); writer.close(); }
-
编写Ajax
oldpassword.on("blur",function(){ $.ajax({ type:"GET", url:path+"/jsp/user.do", data:{method:"pwdmodify",oldpassword:oldpassword.val()}, dataType:"json", success:function(data){ if(data.result == "true"){//旧密码正确 validateTip(oldpassword.next(),{"color":"green"},imgYes,true); }else if(data.result == "false"){//旧密码输入不正确 validateTip(oldpassword.next(),{"color":"red"},imgNo + "原密码输入不正确",false); }else if(data.result == "sessionerror"){//当前用户session过期,请重新登录 validateTip(oldpassword.next(),{"color":"red"},imgNo + "当前用户session过期,请重新登录",false); }else if(data.result == "error"){//旧密码输入为空 validateTip(oldpassword.next(),{"color":"red"},imgNo + " 请输入旧密码",false); } }, error:function(data){ //请求出错 validateTip(oldpassword.next(),{"color":"red"},imgNo + " 请求错误",false); } });
13.6 用户管理实现
思路:
-
导入分页工具类
-
导入用户列表
UserList.jsp
为了符合三层架构:
private SqlSession sqlSession;
private UserMapper mapper;
public UserServiceImpl() {
sqlSession= MybatisUtils.getSqlSession();
mapper= sqlSession.getMapper(UserMapper.class);
}
public class RoleServiceImpl implements RoleService{
private SqlSession sqlSession;
private RoleMapper mapper;
public RoleServiceImpl() {
sqlSession= MybatisUtils.getSqlSession();
mapper= sqlSession.getMapper(RoleMapper.class);
}
13.6.1 获取用户数量
-
userDao
//查询用户名字或角色id查询用户总数 public int getUserCount(@Param("username") String username,@Param("userRole")int userRole);
-
UserDaoImpl
<select id="getUserCount" resultType="int"> select COUNT(*) from smbms.smbms_user u ,smbms.smbms_role r <where> u.userRole=r.id <if test="username!=null"> and u.userName like "%"#{username}"%" </if> <if test="userRole>0"> and u.userRole=#{userRole} </if> </where> </select>
-
UserService
//查询记录数 public int getUserCount(String username,int userRole);
-
UserServiceImpl
public int getUserCount(String username, int userRole) { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int count = mapper.getUserCount(username, userRole); sqlSession.close(); return count; }
13.6.2 获取用户列表
-
userdao
//通过条件查询userList public List<User> getUserList(@Param("userName") String userName,@Param("userRole") int userRole,@Param("currentPageNo") int currentPageNo,@Param("pageSize") int pageSize );
-
userdaoimpl
<select id="getUserList" resultType="User"> select COUNT(*) from smbms.smbms_user u ,smbms.smbms_role r limit #{currentPageNo},#{pageSize} <where> u.userRole=r.id <if test="username!=null"> and u.userName like "%"#{username}"%" </if> <if test="userRole>0"> and u.userRole=#{userRole} </if> </where> </select>
-
UserService
//根据条件查询用户列表 public List<User> getUserList(String queryUserName,int queryUserRole,int currentPageNo,int pageSize);
-
UserServiceImpl
public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); System.out.println("queryUserName------>"+queryUserName); System.out.println("queryUserRole------>"+queryUserRole); System.out.println("currentPageNo------>"+currentPageNo); System.out.println("pageSize------>"+pageSize); List<User> userList = mapper.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize); sqlSession.close(); return userList; }
13.6.3 获取角色列表
-
RoleDao
public interface RoleMapper { //获取角色列表 public List<Role> getRoleList(); }
-
RoleDaoImpl
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.Yurrize.dao.user.UserMapper"> <select id="getRoleList" resultType="Role"> select * from smbms.smbms_role </select> </mapper>
-
RoleService
public interface RoleService { public List<Role> getRoleList(); }
-
RoleServiceImpl
public List<Role> getRoleList() { RoleServiceImpl roleService = new RoleServiceImpl(); List<Role> roleList = roleService.mapper.getRoleList(); roleService.sqlSession.close(); return roleList; }
13.7 添加用户功能实现
创建一个用户,包含了插入用户所有的个人信息,以及规定创造角色的类型(管理人员或普通。。),由于用户类型就三种,因此设置表单让用户前端选择。
-
数据库设计,插入用户所有需要的信息和查询用户角色类型和判断用户是否已经存在,设计dao层
<insert id="addUser"> insert into smbms.smbms_user(userCode, userName, userPassword, gender, birthday, phone, address, userRole) values (#{userCode}, #{userName}, #{userPassword}, #{gender}, #{birthday},#{phone},#{address},#{userRole}) </insert>
<select id="getRoleList" resultType="Role"> select * from smbms.smbms_role </select>
<select id="IsExitUser" parameterType="String" resultType="com.Yurrize.pojo.User"> select * from smbms.smbms_user where userCode=#{userCode} </select>
-
Service层调用dao层
-
Servlet层实现
//判断用户是否存在 private void userCodeExist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //判断用户账号是否可用 String userCode = request.getParameter("userCode"); HashMap<String, String> resultMap = new HashMap<String, String>(); if(StringUtils.isNullOrEmpty(userCode)){ //userCode == null || userCode.equals("") resultMap.put("userCode", "exist"); }else{ UserService userService = new UserServiceImpl(); User user = userService.selectUserCodeExist(userCode); if(null != user){ resultMap.put("userCode","exist"); }else{ resultMap.put("userCode", "notexist"); } } //把resultMap转为json字符串以json的形式输出 //配置上下文的输出类型 response.setContentType("application/json"); //从response对象中获取往外输出的writer对象 PrintWriter outPrintWriter = response.getWriter(); //把resultMap转为json字符串 输出 outPrintWriter.write(JSONArray.toJSONString(resultMap)); outPrintWriter.flush();//刷新 outPrintWriter.close();//关闭流 } //查询角色列表 public void getRoleList(HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("getRoleList"); List<Role> roleList = null; RoleService roleService = new RoleServiceImpl(); roleList = roleService.getRoleList(); //把roleList转换成json对象输出 response.setContentType("application/json"); PrintWriter outPrintWriter = response.getWriter(); outPrintWriter.write(JSONArray.toJSONString(roleList)); outPrintWriter.flush(); outPrintWriter.close(); } //新建用户 public void add(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { System.out.println("进入了add方法"); String userCode = request.getParameter("userCode"); String userName = request.getParameter("userName"); String userPassword = request.getParameter("userPassword"); String gender = request.getParameter("gender"); String birthday = request.getParameter("birthday"); String phone = request.getParameter("phone"); String address = request.getParameter("address"); String userRole = request.getParameter("userRole"); User user = new User(); user.setUserCode(userCode); user.setUserName(userName); user.setUserPassword(userPassword); user.setAddress(address); try { user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } user.setGender(Integer.valueOf(gender)); user.setPhone(phone); user.setUserRole(Integer.valueOf(userRole)); user.setCreationDate(new Date()); user.setCreatedBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId()); UserServiceImpl userService = new UserServiceImpl(); boolean flag = userService.add(user); System.out.println(flag); if(flag){ response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query"); }else{ request.getRequestDispatcher("useradd.jsp").forward(request, response); } }