1.修改UserService.java
package com.imooc.oa.service; import com.imooc.oa.entity.User; import com.imooc.oa.mapper.UserMapper; import com.imooc.oa.service.exception.LoginException; import com.imooc.oa.utils.Md5Utils; public class UserService { private UserMapper userMapper = new UserMapper(); /** * 根据前台输入进行登录校验 * @param username 前台输入的用户名 * @param password 前台输入的密码 * @return 校验通过后,包含对应用户数据的User实体类 * @throws LoginException 用户登录异常 */ public User checkLogin(String username , String password){ User user = userMapper.selectByUsername(username); if(user == null){ throw new LoginException("用户名不存在"); } String md5 = Md5Utils.md5Digest(password, user.getSalt()); if(!md5.equals(user.getPassword())){ throw new LoginException("密码错误"); } return user; } }
2.LoginServlet.java的处理
如果不处理返回的使用户的全部信息,对用户的密码和盐值进行处理
user.setPassword(null); user.setSalt(null);
package com.imooc.oa.controller; import com.imooc.oa.entity.User; import com.imooc.oa.service.UserService; import com.imooc.oa.utils.ResponseUtils; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/api/login") public class LoginServlet extends HttpServlet { private UserService userService = new UserService(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=utf-8"); //接收用户输入 String username = request.getParameter("username"); String password = request.getParameter("password"); //调用业务逻辑 ResponseUtils resp = null; try { User user = userService.checkLogin(username, password); user.setPassword(null); user.setSalt(null); //处理结果编码,0代表处理成功,非0代表处理失败 resp = new ResponseUtils().put("user", user); }catch (Exception e){ e.printStackTrace(); resp = new ResponseUtils(e.getClass().getSimpleName(), e.getMessage()); } //返回JSON结果 response.getWriter().println(resp.toJsonString()); } }
标签:登录,resp,oa,完整,user,import,009,com,imooc From: https://www.cnblogs.com/LLL0617/p/16964719.html