之前做完了登录,那么就该做一个注册页面,让别人来注册了。

1、首先创建一个表单页和一个结果页。

/web/WEB-INF/views/register

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册</title>
</head>
<body>
    <form action="/register" method="post">
        用户名:<input type="text" name="username"><br/>
        密码:<input type="password" name="password"><br/>
        <input type="submit" value="注册">
    </form>
    <p>
        <a href="/"> 登录</a>
    </p>
</body>
</html>

 

result.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册结果</title>
</head>
<body>
    <p>
        ${result_msg}
    </p>
    <a href="/">返回首页</a>
</body>
</html>

 

当然登录页面我们也得改改,加个注册链接。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>登录</title>
</head>
<body>
  <form action="/login" method="post">
    用户名:<input type="text" name="username"><br/>
    密码:<input type="password" name="password"><br/>
    <input type="submit" value="登陆">
  </form>
  <p>
    <a href="/register"> 注册</a>
  </p>
</body>
</html>

 

2、然后就该来写控制器了。

RegisterController.java

package Controllers;

import Helpers.DbConnection;
import Models.UsersEntity;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class RegisterController {

    static String to_reg_page_url = "/register";
    static String to_home_page_url = "/";

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String index() {
        return "register/index";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@RequestParam("username") String username, @RequestParam("password") String password,
                           Model model, HttpSession session) {
        //输入参数为空
        if(username.equals("") || password.equals("")) {
            model.addAttribute("to_url", to_reg_page_url);
            model.addAttribute("result_msg", "信息不完整,请重新填写。");
            return "register/result";
        }

        //创建数据库操作线程
        Session db_session = DbConnection.getSession();

        try{
            //创建初始创建条件
            Criteria criteria = db_session.createCriteria(UsersEntity.class);
            //往条件里加东西,等同于 where `username` = username
            criteria.add(Restrictions.eq("username", username));
            //列出所有查询结果
            List<UsersEntity> list = criteria.list();

            if(!list.isEmpty()) {
                model.addAttribute("to_url", to_reg_page_url);
                model.addAttribute("result_msg", "用户名已存在,请重新输入。");
                return "register/result";
            }

            //开启事务
            Transaction db_trans = db_session.beginTransaction();
            //创建一个新用户
            UsersEntity new_user = new UsersEntity();
            new_user.setUsername(username);
            new_user.setPassword(password);
            new_user.setUserRoleType(Byte.parseByte("2"));
            //保存用户到数据库线程
            db_session.save(new_user);
            //提交事务
            db_trans.commit();

            model.addAttribute("to_url", to_home_page_url);
            model.addAttribute("result_msg", "注册成功。");

            //把用户信息加到 Session 里,自动登录
            session.setAttribute("user", new_user);

            return "register/result";
        }catch(Exception e) {
            //添加错误信息
            model.addAttribute("to_url", to_reg_page_url);
            model.addAttribute("result_msg", " 系统发生了错误!");
            return "register/fail";
        }finally {
            //用完这个 数据库的 Session  记得关了
            db_session.close();
        }
    }
}

 

3、然后我们还得改改拦截器,放行我们这个注册界面。

LoginInterceptor.java

package Interceptors;

import Models.UsersEntity;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        Boolean is_in_guest_page = (httpServletRequest.getRequestURI().indexOf("/login") == 0 || httpServletRequest.getRequestURI().indexOf("/register") == 0);
        //从 Session  里获取当前登录的用户
        UsersEntity user = (UsersEntity) httpServletRequest.getSession().getAttribute("user");
        if(user == null && !is_in_guest_page) {
            //未登录
            httpServletResponse.sendRedirect("/login");
            return false;
        }

        //已登录的还访问登录界面就是搞事儿了
        if(user != null && is_in_guest_page) {
            //未登录
            httpServletResponse.sendRedirect("/");
            return false;
        }

        //已登录
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

 

4、可以运行来试试了。