用户注册案例--浅谈servlet
本案例为用户注册案例,同时介绍一部分之前经常用得到servlet的知识.servlet是javaEE的技术规范之一.
基于MCV架构的分析
1.dao层在mapper代理文件中写入insert的操作,对于成功注册的用户直接写入数据库,以及查询操作判断用户名是否已经存在
User getUserByUsername(@Param("username") String username ,@Param("password") String password);@Select("select * from tb_user where username=#{username}")User findUsername(@Param("username") String username);@Insert("insert into tb_user values(#{username},#{password},#{type})")void insertUser(User user);
2.service层,在本层中封装对于数据库的操作,同时记得执行操作之后将数据提交
public void InsertUser(User user) throws IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);userMapper.insertUser(user);sqlSession.commit();sqlSession.close();}public boolean findUser(String username) throws IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(com.stdu.mapper.UserMapper.class);User user=userMapper.findUsername(username);sqlSession.close();if(user==null){return false;}return true;}
3.在web层分为两部分,第一部分是在jsp中设计表单将表单中的信息提交到servlet中,然后进行逻辑判断,对于用户名已经存在的情况和成功注册的情况进行重定向和dao层操作
jsp的代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head><title>register</title>
</head>
<body><h2>注册账号</h2><form method="POST" action="/LogIn/registerServlet" accept-charset="UTF-8"><p>${wr_message} </p><p>用户名 <input type="text" name="username"> </p><p>密码 <input type="password" name="password"></p><p>验证码 <input type="text" name="code"> <img src="/LogIn/insureServlet" id="insure"></p><input type="submit" value="注册">
</form>
<script>document.getElementById("insure").onclick = function () {document.getElementById("insure").src = "/LogIn/insureServlet?"+ new Date().getMilliseconds();}
</script>
</body>
</html>
sevlet的代码
package com.stdu.servlet;import com.mysql.cj.Session;
import com.stdu.pojo.User;
import com.stdu.service.UserService;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 javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {UserService userService = new UserService();String username = req.getParameter("username");String password = req.getParameter("password");String code = req.getParameter("code");HttpSession session=req.getSession();String insure=session.getAttribute("insure").toString();if(code==null||!code.equals(insure)){req.setAttribute("wr_message","验证码错误");req.getRequestDispatcher("register.jsp").forward(req, resp);return ;}boolean st=userService.findUser(username);if(st){req.setAttribute("wr_message","用户名已经存在");req.getRequestDispatcher("register.jsp").forward(req, resp);}else{User user = new User();user.setUsername(username);user.setPassword(password);userService.InsertUser(user);req.setAttribute("wr_message","注册成功");req.getRequestDispatcher("index.jsp").forward(req, resp);}}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
}package com.stdu.servlet;import com.stdu.util.CheckCodeUtil;import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
@WebServlet("/insureServlet")
public class InsureServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {ServletOutputStream outputStream= resp.getOutputStream();String insure=CheckCodeUtil.outputVerifyImage(140,50,outputStream,4);req.getSession().setAttribute("insure",insure);}
}
技术学习
在本案例中,加入了注册需要验证码的功能来防止机器人暴力注册来冲掉数据库.功能实现包括以下几个步骤:
1.生成验证码图片,这里使用了一个工具类,然后将图片输出到servlet的输出流,并且将src放到输出流就可以得到图片
2.同时将得到的验证码放到session上使得数据的验证可以实现
3.将图片使用js的语法绑定事件使得点击图片可以实现图片的替换