×

【Java】【MVC】一套完整的登陆注册逻辑

96
JerichoPH
2017.04.18 12:19* 字数 2853

一套完整的登陆注册业务逻辑

  1. 准备部分
    1. 基础工具类
      1. Base
      package com.jericho.tools;
      
      import com.google.gson.Gson;
      
      import javax.servlet.http.HttpServletRequest;
      import java.lang.reflect.Field;
      import java.math.BigInteger;
      import java.security.MessageDigest;
      import java.security.NoSuchAlgorithmException;
      import java.sql.ResultSet;
      import java.sql.ResultSetMetaData;
      import java.util.HashMap;
      import java.util.Map;
      import java.util.Random;
      
      public class Base {
      
      static Gson gson = new Gson();
      
      private static Map<Object, Object> _makeReturnMap(boolean isSuccess) {
          Map<Object, Object> map = new HashMap<>();
          if (isSuccess) {
              map.put("err", 0);
          } else {
              map.put("err", 1);
          }
          return map;
      }
      
      /**
       * 生成成功返回结果信息
       *
       * @param message 描述
       * @return Map
       */
      public static Map<Object, Object> returnSuccess(String message) {
          Map<Object, Object> map = Base._makeReturnMap(true);
          map.put("msg", message);
          return map;
      }
      
      /**
       * 生成成功返回结果信息
       *
       * @param map 描述
       * @return Map
       */
      public static Map<Object, Object> returnSuccess(Map<Object, Object> map) {
          Map<Object, Object> res = Base._makeReturnMap(true);
          res.putAll(map);
          return res;
      }
      
      /**
       * 返回json格式成功信息
       *
       * @param message 描述
       * @return String
       */
      public static String jsonSuccess(String message) {
          return Base.gson.toJson(Base.returnSuccess(message));
      }
      
      /**
       * 返回json格式成功信息
       *
       * @param map 描述
       * @return String
       */
      public static String jsonSuccess(Map<Object, Object> map) {
          return Base.gson.toJson(Base.returnSuccess(map));
      }
      
      /**
       * 生成失败返回结果信息
       *
       * @param message 描述
       * @return Map
       */
      public static Map<Object, Object> returnFail(String message) {
          Map<Object, Object> map = Base._makeReturnMap(false);
          map.put("msg", message);
          return map;
      }
      
      /**
       * 生成失败返回结果信息
       *
       * @param map 描述
       * @return Map
       */
      public static Map<Object, Object> returnFail(Map<Object, Object> map) {
          Map<Object, Object> res = Base._makeReturnMap(false);
          res.putAll(map);
          return res;
      }
      
      /**
       * 生成json格式失败信息
       *
       * @param message 描述
       * @return String
       */
      public static String jsonFail(String message) {
          return Base.gson.toJson(Base.returnFail(message));
      }
      
      /**
       * 生成json格式失败信息
       *
       * @param map 描述
       * @return String
       */
      public static String jsonFail(Map<Object, Object> map) {
          return Base.gson.toJson(Base.returnFail(map));
      }
      
      /**
       * 生成md5
       *
       * @param str 待加密字符串
       * @return String
       * @throws NoSuchAlgorithmException
       */
      public static String md5(Object str) throws NoSuchAlgorithmException {
          MessageDigest md5 = MessageDigest.getInstance("MD5");
          md5.update(str.toString().getBytes());
          return new BigInteger(1, md5.digest()).toString(16);
      }
      
      /**
       * 显示请求结果
       *
       * @param request 请求数据
       */
      public static void showRequest(HttpServletRequest request) {
          Map<String, String[]> map = request.getParameterMap();
          for (Map.Entry<String, String[]> m :
                  map.entrySet()) {
              String key = m.getKey();
              String[] values = m.getValue();
              System.out.print(key + ":");
              for (String value :
                      values) {
                  System.out.print(value + " ");
              }
              System.out.println();
          }
      }
      
      /**
       * 获取生成随机字符串
       *
       * @param length 生成字符串长度
       * @return String
       */
      public static String getRandomString(int length) {
          String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";//含有字符和数字的字符串
          Random random;//随机类初始化
          random = new Random();
          StringBuffer sb = new StringBuffer();//StringBuffer类生成,为了拼接字符串
      
          for (int i = 0; i < length; ++i) {
              int number = random.nextInt(62);// [0,62)
      
              sb.append(str.charAt(number));
          }
          return sb.toString();
      }
      
      /**
       * 将请求表单保存到实体类
       *
       * @param entity  实体类
       * @param request 请求数据
       * @param <T>     T
       * @return T
       * @throws Exception
       */
      public static <T> T requestToBean(Class<T> entity, HttpServletRequest request) throws Exception {
          Map<String, String[]> map = request.getParameterMap();
          T cls = entity.newInstance();
          Class<?> clsClass = cls.getClass();
      
          for (Map.Entry<String, String[]> m :
                  map.entrySet()) {
              String key = m.getKey();
              String[] value = m.getValue();
      
              Field field = clsClass.getDeclaredField(key);
              field.setAccessible(true);
              if (value.length == 1) {
                  field.set(cls, value[0]);
              } else {
                  field.set(cls, (Object) value);
              }
          }
          return cls;
      }
      
      /**
       * 将请求表单保存到实体类
       *
       * @param entity    实体类
       * @param request   请求数据
       * @param exception 排除在外的字段
       * @param <T>       T
       * @return T
       * @throws Exception
       */
      public static <T> T requestToBean(Class<T> entity, HttpServletRequest request, String exception) throws Exception {
          Map<String, String[]> map = request.getParameterMap();
          T cls = entity.newInstance();
          Class<?> clsClass = cls.getClass();
      
          for (Map.Entry<String, String[]> m :
                  map.entrySet()) {
              String key = m.getKey();
              String[] value = m.getValue();
      
              if (exception.indexOf(key) != -1) {
                  continue;
              } else {
                  Field field = clsClass.getDeclaredField(key);
                  field.setAccessible(true);
                  if (value.length == 1) {
                      field.set(cls, value[0]);
                  } else {
                      field.set(cls, (Object) value);
                  }
              }
          }
          return cls;
      }
      
      public static <T> T resultSetToBean(ResultSet rs, Class<T> cls)
              throws Exception {
          T resultObject = null;
          int index = 1;
      
          ResultSetMetaData metaData = rs.getMetaData();
          int cols_len = metaData.getColumnCount();
          while (rs.next()) {
              // 通过反射机制创建一个实例
              resultObject = cls.newInstance();
              for (int i = 0; i < cols_len; i++) {
                  String cols_name = metaData.getColumnName(i + 1);
                  Object cols_value = rs.getObject(cols_name);
      
                  if (cols_value == null) {
                      cols_value = "";
                  }
                  Field field = cls.getDeclaredField(cols_name);
                  field.setAccessible(true); // 打开javabean的访问权限
                  field.set(resultObject, cols_value);
              }
          }
      
          return resultObject;
      }
      }
      
      1. DbUtils
      package com.yjzblog.web.utils;
      
      import java.sql.Connection;
      import java.sql.DriverManager;
      import java.sql.ResultSet;
      import java.sql.Statement;
      import java.util.ResourceBundle;
      
      /**
       * 数据库工具类
       */
      public class DbUtils {
      
      private static String driver = null;
      private static String dns = null;
      private static String user = null;
      private static String pwd = null;
      
      static {
          // 读取配置文件
          ResourceBundle rb = ResourceBundle.getBundle("db");
          DbUtils.driver = rb.getString("driver");
          DbUtils.dns = rb.getString("dns");
          DbUtils.user = rb.getString("user");
          DbUtils.pwd = rb.getString("pwd");
      
          // 获取数据库驱动
          // 获取数据库驱动
          try {
              Class.forName(DbUtils.driver);
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
      
      /**
       * 获取链接
       *
       * @return Connection
       * @throws Exception
       */
      public static Connection getConn() throws Exception {
          return DriverManager.getConnection(dns, user, pwd);
      }
      
      /**
       * 关闭资源
       *
       * @param conn 链接
       * @param stmt 参数
       * @param rs   结果集
       * @throws Exception
       */
      public static void kill(Connection conn, Statement stmt, ResultSet rs) throws Exception {
          if (conn != null) {
              conn.close();
          }
          if (stmt != null) {
              stmt.close();
          }
          if (rs != null) {
              rs.close();
          }
      }
      }
      
      1. 数据库配置db.properties
      driver=com.mysql.jdbc.Driver
      dns=jdbc:mysql://localhost:3306/yjzblog
      user=root
      pwd=1
      
      1. web.xml
      <?xml version="1.0" encoding="UTF-8"?>
      

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<session-config>
<session-timeout>15</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>demo</welcome-file>
</welcome-file-list>

        <!--servlet-->
        <servlet>
            <servlet-name>Index</servlet-name>
            <servlet-class>com.yjzblog.web.servlet.IndexServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>Index</servlet-name>
            <url-pattern>/index</url-pattern>
        </servlet-mapping>
    
        <servlet>
            <servlet-name>Register</servlet-name>
            <servlet-class>com.yjzblog.web.servlet.RegisterServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>Register</servlet-name>
            <url-pattern>/register</url-pattern>
        </servlet-mapping>
    
        <servlet>
            <servlet-name>Login</servlet-name>
            <servlet-class>com.yjzblog.web.servlet.LoginServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>Login</servlet-name>
            <url-pattern>/login</url-pattern>
        </servlet-mapping>
    
        <servlet>
            <servlet-name>Welcome</servlet-name>
            <servlet-class>com.yjzblog.web.servlet.WelcomeServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>Welcome</servlet-name>
            <url-pattern>/welcome</url-pattern>
        </servlet-mapping>
    
        <servlet>
            <servlet-name>Demo</servlet-name>
            <servlet-class>com.yjzblog.web.servlet.DemoServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>Demo</servlet-name>
            <url-pattern>/demo</url-pattern>
        </servlet-mapping>
    
        <servlet>
            <servlet-name>Exit</servlet-name>
            <servlet-class>com.yjzblog.web.servlet.ExitServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>Exit</servlet-name>
            <url-pattern>/exit</url-pattern>
        </servlet-mapping>
    </web-app>
    ```
2. 实体类
    1. User
    ```js
    package com.yjzblog.web.domain;

    /**
     * user实体类
     */
    public class User {
    private long id;
    private String mobile_no;
    private String pwd;
    private String salt;
    private String nickname;
    
    @Override
    public String toString() {
        return "User{" +
                       "id=" + id +
                       ", mobile_no='" + mobile_no + '\'' +
                       ", pwd='" + pwd + '\'' +
                       ", salt='" + salt + '\'' +
                       ", nickname='" + nickname + '\'' +
                       '}';
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
    
        User user = (User) o;
    
        if (id != user.id) return false;
        if (mobile_no != null ? !mobile_no.equals(user.mobile_no) : user.mobile_no != null) return false;
        if (pwd != null ? !pwd.equals(user.pwd) : user.pwd != null) return false;
        if (salt != null ? !salt.equals(user.salt) : user.salt != null) return false;
        return nickname != null ? nickname.equals(user.nickname) : user.nickname == null;
    
    }
    
    @Override
    public int hashCode() {
        int result = (int) (id ^ (id >>> 32));
        result = 31 * result + (mobile_no != null ? mobile_no.hashCode() : 0);
        result = 31 * result + (pwd != null ? pwd.hashCode() : 0);
        result = 31 * result + (salt != null ? salt.hashCode() : 0);
        result = 31 * result + (nickname != null ? nickname.hashCode() : 0);
        return result;
    }
    
    public long getId() {
    
        return id;
    }
    
    public void setId(long id) {
        this.id = id;
    }
    
    public String getMobile_no() {
        return mobile_no;
    }
    
    public void setMobile_no(String mobile_no) {
        this.mobile_no = mobile_no;
    }
    
    public String getPwd() {
        return pwd;
    }
    
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    
    public String getSalt() {
        return salt;
    }
    
    public void setSalt(String salt) {
        this.salt = salt;
    }
    
    public String getNickname() {
        return nickname;
    }
    
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
    }
    ```
  1. 业务实现
    1. 主页(引导页)
      1. index.jsp
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
          <title>webStu</title>
          <script src="resource/ui/js/jquery-1.11.0.min.js"></script>
      </head>
      <body>
      <h1>Hello Java</h1>
      <a href="<%=request.getContextPath()%>/register">注册</a>
      <a href="<%=request.getContextPath()%>/login">登陆</a>
      </body>
      </html>
      
      1. IndexServlet
      package com.yjzblog.web.servlet;
      
      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;
      import java.io.PrintWriter;
      
      @WebServlet(name = "IndexServlet")
      public class IndexServlet extends HttpServlet {
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          this.doGet(request, response);
      }
      
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          request.setCharacterEncoding("utf-8");
          response.setCharacterEncoding("utf-8");
          PrintWriter out = response.getWriter();
      
          request.getRequestDispatcher("/index.jsp").forward(request, response);
      }
      }
      
    2. 注册
      1. register.jsp
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
          <title>注册</title>
          <script src="resource/ui/js/jquery-1.11.0.min.js"></script>
      </head>
      <body>
      <h2>注册</h2>
      <form id="frmRegister">
          <label>账号:<input type="text" placeholder="账号" name="mobile_no" value="13522178057"></label>
          <label>密码:<input type="password" placeholder="密码" name="pwd" value="123123"></label>
          <label>重复密码:<input type="password" placeholder="再次输入密码" name="repeat" value="123123"></label>
          <label>昵称:<input type="text" placeholder="昵称" name="nickname" value="JerichoPH"></label>
          <a href="javascript:" onclick="fnRegister()">注册</a>
      </form>
      </body>
      <script>
          /**
           * 执行注册
           */
          fnRegister = function () {
              $.ajax({
                  url: "<%=request.getContextPath()%>/register",
                  type: "post",
                  data: $("#frmRegister").serialize(),
                  success: function (res) {
                      console.log(res);
                      res = $.parseJSON(res);
                      console.log(res);
                      if (res.err == 0) {
                          alert(res.msg);
                      } else {
                          alert(res.msg);
                      }
                  }
              })
          };
      </script>
      </html>
      
      1. RegisterServlet
      package com.yjzblog.web.servlet;
      
      import com.google.gson.Gson;
      import com.jericho.tools.Base;
      import com.yjzblog.web.domain.User;
      import com.yjzblog.web.service.UserService;
      import com.yjzblog.web.service.impl.UserServiceImpl;
      
      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;
      import java.io.PrintWriter;
      
      @WebServlet(name = "RegisterServlet")
      public class RegisterServlet extends HttpServlet {
      
      UserService userService = new UserServiceImpl();
      Gson gson = new Gson();
      
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          request.setCharacterEncoding("utf-8");
          response.setCharacterEncoding("utf-8");
          PrintWriter out = response.getWriter();
      
          Base.showRequest(request);
      
          // 获取表单数据
          try {
              User user = Base.requestToBean(User.class, request, "repeat");
              String repeat = request.getParameter("repeat");
      
              // 判断两次密码是否一致
              if (user.getPwd().equals(repeat)) {
                  // 两次密码一致,生成MD5密码
                  user.setPwd(Base.md5(user.getPwd()));
                  // 密码加盐
                  user.setSalt(Base.getRandomString(4));
                  user.setPwd(Base.md5(user.getPwd() + user.getSalt()));
      
                  // 保存到数据库
                  boolean register = this.userService.register(user);
                  System.out.println(register);
                  out.print(Base.jsonSuccess(register ? "注册成功" : "注册失败"));
              }
      
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
      
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          request.setCharacterEncoding("utf-8");
          response.setCharacterEncoding("utf-8");
          PrintWriter out = response.getWriter();
      
          request.getRequestDispatcher("/register.jsp").forward(request, response);
      }
      }
      
      1. UserDao
      package com.yjzblog.web.dao;
      
      import com.yjzblog.web.domain.User;
      
      /**
       * user数据处理接口
       */
      public interface UserDao {
      /**
       * 创建信息用户
       *
       * @param user 用户信息
       * @return int
       * @throws Exception
       */
      public int add(User user) throws Exception;
      
      /**
       * 根据mobile_no查询数据
       *
       * @param mobile_no 手机号
       * @return User
       * @throws Exception
       */
      public User readOneBymobile_no(String mobile_no) throws Exception;
      }
      
      1. UserDaoImpl
      package com.yjzblog.web.dao.impl;
      
      import com.jericho.tools.Base;
      import com.yjzblog.web.dao.UserDao;
      import com.yjzblog.web.domain.User;
      import com.yjzblog.web.utils.DbUtils;
      
      import java.sql.Connection;
      import java.sql.PreparedStatement;
      import java.sql.ResultSet;
      
      /**
       * user数据处理实现类
       */
      public class UserDaoImpl implements UserDao {
      
      /**
       * 创建新用户
       *
       * @param user 用户信息
       * @return int
       * @throws Exception
       */
      @Override
      public int add(User user) throws Exception {
          Connection conn = DbUtils.getConn();
          PreparedStatement ps = conn.prepareStatement("INSERT INTO `user` (mobile_no,pwd,salt,nickname) VALUES (?,?,?,?)");
          try {
              ps.setString(1, user.getMobile_no());
              ps.setString(2, user.getPwd());
              ps.setString(3, user.getSalt());
              ps.setString(4, user.getNickname());
              int i = ps.executeUpdate();
              return i;
          } catch (Exception e) {
              e.printStackTrace();
          } finally {
              DbUtils.kill(conn, ps, null);
          }
          return 0;
      }
      
      /**
       * 根据mobile_no 查询数据
       *
       * @param mobile_no 手机号
       * @return User
       * @throws Exception
       */
      @Override
      public User readOneBymobile_no(String mobile_no) throws Exception {
          Connection conn = DbUtils.getConn();
          PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM user WHERE mobile_no = ?");
          ResultSet rs = null;
          // 获取用户数据
          try {
              preparedStatement.setString(1, mobile_no);
              rs = preparedStatement.executeQuery();
              return Base.resultSetToBean(rs, User.class);
          } catch (Exception e) {
              e.printStackTrace();
          } finally {
              DbUtils.kill(conn, preparedStatement, rs);
          }
          return null;
      }
      }
      
      1. UserService
      package com.yjzblog.web.service;
      
      import com.yjzblog.web.domain.User;
      
      /**
       * 用户服务接口
       */
      public interface UserService {
      /**
       * 注册
       *
       * @param user 用户信息
       * @return boolean
       * @throws Exception
       */
      public boolean register(User user) throws Exception;
      
      /**
       * 登陆
       *
       * @param user 用户数据
       * @return User
       * @throws Exception
       */
      public User login(User user) throws Exception;
      }
      
      1. UserServiceImpl
      package com.yjzblog.web.service.impl;
      
      import com.jericho.tools.Base;
      import com.yjzblog.web.dao.UserDao;
      import com.yjzblog.web.dao.impl.UserDaoImpl;
      import com.yjzblog.web.domain.User;
      import com.yjzblog.web.service.UserService;
      
      /**
       * 用户服务实现类
       */
      public class UserServiceImpl implements UserService {
      
      UserDao userDao = new UserDaoImpl();
      
      /**
       * 注册
       *
       * @param user 用户信息
       * @return boolean
       * @throws Exception
       */
      @Override
      public boolean register(User user) throws Exception {
          int add = this.userDao.add(user);
          return add > 0;
      }
      
      /**
       * 登陆
       *
       * @param user 用户数据
       * @return User
       * @throws Exception
       */
      @Override
      public User login(User user) throws Exception {
          // 获取数据库信息
          User userData = this.userDao.readOneBymobile_no(user.getMobile_no());
      
          // 密码加盐运算
          String pwd = Base.md5(Base.md5(user.getPwd()) + userData.getSalt());
          if (pwd.equals(userData.getPwd())) {
              // 密码正确
              userData.setSalt("");// 去掉多余字段
              return userData;
          } else {
              // 密码错误
              return null;
          }
      }
      }
      
    3. 登陆
      1. login.jsp
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
          <title>登陆</title>
          <script src="resource/ui/js/jquery-1.11.0.min.js"></script>
      </head>
      <body>
      <h2>登陆</h2>
      <form id="frmLogin">
          <label>账号:<input type="text" placeholder="账号" name="mobile_no"></label>
          <label>密码:<input type="password" placeholder="密码" name="pwd"></label>
          <a href="javascript:" onclick="fnLogin()">登陆</a>
      </form>
      </body>
      <script>
          /**
           * 执行登陆
           */
          fnLogin = function () {
              $.ajax({
                  url: "<%=request.getContextPath()%>/login",
                  type: "post",
                  data: $("#frmLogin").serialize(),
                  success: function (res) {
                      res = $.parseJSON(res);
                      if (res.err == 0) {
                          alert(res.msg);
                          location.href = "/welcome";
                      } else {
                          alert(res.msg);
                          location.reload();
                      }
                  }
              })
          };
      </script>
      </html>
      
      1. LoginServlet
      package com.yjzblog.web.servlet;
      
      import com.google.gson.Gson;
      import com.jericho.tools.Base;
      import com.yjzblog.web.domain.User;
      import com.yjzblog.web.service.UserService;
      import com.yjzblog.web.service.impl.UserServiceImpl;
      
      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;
      import java.io.PrintWriter;
      
      @WebServlet(name = "LoginServlet")
      public class LoginServlet extends HttpServlet {
      
      Gson gson = new Gson();
      User user = null;
      UserService userService = new UserServiceImpl();
      
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          request.setCharacterEncoding("utf-8");
          response.setCharacterEncoding("utf-8");
          PrintWriter out = response.getWriter();
      
          try {
              // 获取表单数据
              this.user = Base.requestToBean(User.class, request, "id,salt,nickname");
              // 执行登陆
              User user = this.userService.login(this.user);
              if (user != null) {
                  // 登陆成功,保存到session
                  request.getSession().setAttribute("user", user);
      
                  out.print(Base.jsonSuccess("登陆成功"));
              } else {
                  out.print(Base.jsonFail("账号或密码错误"));
              }
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
      
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          request.setCharacterEncoding("utf-8");
          response.setCharacterEncoding("utf-8");
          PrintWriter out = response.getWriter();
      
          // 读取session数据,判断是否已经登陆
          User user = (User) request.getSession().getAttribute("user");
          if (user != null) {
              // 已登陆
              request.getRequestDispatcher("/welcome.jsp").forward(request, response);
          } else {
              // 未登陆
              request.getRequestDispatcher("/login.jsp").forward(request, response);
          }
      }
      }
      
    4. 欢迎页
      1. welcome.jsp
      <%@ page import="com.yjzblog.web.domain.User" %>
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
          <title>登陆成功</title>
          <script src="resource/ui/js/jquery-1.11.0.min.js"></script>
      </head>
      <body>
      <h2>登陆成功</h2>
      <%
          User user = (User) request.getSession().getAttribute("user");
      %>
      欢迎登陆:<%=user.getNickname()%>
      <br>
      <a href="javascript:" onclick="fnExit()">退出登陆</a>
      </body>
      <script>
          /**
           * 退出登录
           */
          fnExit = function () {
              $.ajax({
                  url: "<%=request.getContextPath()%>/exit",
                  success: function (res) {
                      res = $.parseJSON(res);
                      if (res.err == 0) {
                          alert(res.msg);
                          location.reload();
                      } else {
                          alert(res.msg);
                          location.reload();
                      }
                  }
              })
          };
      </script>
      </html>
      
      1. WelcomeServlet
      package com.yjzblog.web.servlet;
      
      import com.google.gson.Gson;
      
      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;
      import java.io.PrintWriter;
      
      @WebServlet(name = "WelcomeServlet")
      public class WelcomeServlet extends HttpServlet {
      
      Gson gson = new Gson();
      
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          request.setCharacterEncoding("utf-8");
          response.setCharacterEncoding("utf-8");
          PrintWriter out = response.getWriter();
      
          this.doGet(request, response);
      }
      
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          request.setCharacterEncoding("utf-8");
          response.setCharacterEncoding("utf-8");
          PrintWriter out = response.getWriter();
      
          Object user = request.getSession().getAttribute("user");
          if (user == null) {
              request.getRequestDispatcher("/login.jsp").forward(request, response);
          } else {
              request.getRequestDispatcher("/welcome.jsp").forward(request, response);
          }
      }
      }
      
    5. 退出登陆
      1. ExitServlet
      package com.yjzblog.web.servlet;
      
      import com.google.gson.Gson;
      import com.jericho.tools.Base;
      
      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;
      import java.io.PrintWriter;
      
      @WebServlet(name = "ExitServlet")
      public class ExitServlet extends HttpServlet {
      
      Gson gson = new Gson();
      
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          this.doGet(request, response);
      }
      
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          request.setCharacterEncoding("utf-8");
          response.setCharacterEncoding("utf-8");
          PrintWriter out = response.getWriter();
      
          // 清除session
          request.getSession().invalidate();
          out.print(this.gson.toJson(Base.returnSuccess("退出成功")));
      }
      }
      
Java学习笔记
Web note ad 1