后端servlet步骤:
乱码处理
得到前端数据
前端数据封装
调用服务逻辑
得到后端返回数据
将数据响应给前端
登录示例
servlet层
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//1.乱码处理
req.setCharacterEncoding(StandardCharsets.UTF_8.toString());
resp.setCharacterEncoding(StandardCharsets.UTF_8.toString());
//2.得到前端值
String username = req.getParameter("username");
String password = req.getParameter("password");
//3.将前端值封装
UserVO userVO = UserVO.builder()
.name(username)
.password(password)
.build();
userVO.setName(username);
userVO.setPassword(password);
//4.逻辑处理
UserService userService = new UserServiceImpl();
//5.得到处理结果
ResultDTO resultDTO = userService.login(userVO);
if ("success".equals(resultDTO.getMsg())) {
req.getSession().setAttribute("username", username);
}
//6.响应数据到前端
resp.getWriter().println(JSONObject.toJSONString(resultDTO));
}
}
service层
@Override
public ResultDTO login(UserVO userVO) {
UserDao userDao = new UserDaoImpl();
//复制数据
BeanUtils.copyProperties(userVO, userEntity);
String mingwen = userEntity.getPassword();
//加密
String anwen = Md5.encoderByMd5(mingwen);
userEntity.setPassword(anwen);
userEntity = userDao.findByUsernameAndPassword(userEntity);//查询是否存在
if (userEntity == null) {
return ResultDTO.getResult("error");
} else {
return ResultDTO.getResult("success");
}
}
dao层
@Override
public UserEntity findByUsernameAndPassword(UserEntity userEntity) {
UserDao userDao = MyBatisUtils.getMapper(UserDao.class);
return userDao.findByUsernameAndPassword(userEntity);
}
mapper
<!-- 登录,查找用户名和密码 -->
<select id="findByUsernameAndPassword" resultType="com.zzb.entity.UserEntity">
select * from user where name=#{name} and password=#{password}
</select>
VO、entity和DTO
VO:存放前端的数据
entity:存放与数据库交互的数据
DTO:存放返回前端的数据