【Java】【MVC】一套完整的登陸注冊邏輯

一套完整的登陸注冊業(yè)務(wù)邏輯

  1. 準(zhǔn)備部分
    1. 基礎(chǔ)工具類
      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;
      }
      
      /**
       * 生成成功返回結(jié)果信息
       *
       * @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;
      }
      
      /**
       * 生成成功返回結(jié)果信息
       *
       * @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));
      }
      
      /**
       * 生成失敗返回結(jié)果信息
       *
       * @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;
      }
      
      /**
       * 生成失敗返回結(jié)果信息
       *
       * @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);
      }
      
      /**
       * 顯示請求結(jié)果
       *
       * @param request 請求數(shù)據(jù)
       */
      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();
          }
      }
      
      /**
       * 獲取生成隨機(jī)字符串
       *
       * @param length 生成字符串長度
       * @return String
       */
      public static String getRandomString(int length) {
          String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";//含有字符和數(shù)字的字符串
          Random random;//隨機(jī)類初始化
          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 請求數(shù)據(jù)
       * @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   請求數(shù)據(jù)
       * @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()) {
              // 通過反射機(jī)制創(chuàng)建一個實例
              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的訪問權(quán)限
                  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;
      
      /**
       * 數(shù)據(jù)庫工具類
       */
      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");
      
          // 獲取數(shù)據(jù)庫驅(qū)動
          // 獲取數(shù)據(jù)庫驅(qū)動
          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);
      }
      
      /**
       * 關(guān)閉資源
       *
       * @param conn 鏈接
       * @param stmt 參數(shù)
       * @param rs   結(jié)果集
       * @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. 數(shù)據(jù)庫配置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. 業(yè)務(wù)實現(xiàn)
    1. 主頁(引導(dǎo)頁)
      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>重復(fù)密碼:<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>
          /**
           * 執(zhí)行注冊
           */
          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);
      
          // 獲取表單數(shù)據(jù)
          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()));
      
                  // 保存到數(shù)據(jù)庫
                  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數(shù)據(jù)處理接口
       */
      public interface UserDao {
      /**
       * 創(chuàng)建信息用戶
       *
       * @param user 用戶信息
       * @return int
       * @throws Exception
       */
      public int add(User user) throws Exception;
      
      /**
       * 根據(jù)mobile_no查詢數(shù)據(jù)
       *
       * @param mobile_no 手機(jī)號
       * @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數(shù)據(jù)處理實現(xiàn)類
       */
      public class UserDaoImpl implements UserDao {
      
      /**
       * 創(chuàng)建新用戶
       *
       * @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;
      }
      
      /**
       * 根據(jù)mobile_no 查詢數(shù)據(jù)
       *
       * @param mobile_no 手機(jī)號
       * @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;
          // 獲取用戶數(shù)據(jù)
          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;
      
      /**
       * 用戶服務(wù)接口
       */
      public interface UserService {
      /**
       * 注冊
       *
       * @param user 用戶信息
       * @return boolean
       * @throws Exception
       */
      public boolean register(User user) throws Exception;
      
      /**
       * 登陸
       *
       * @param user 用戶數(shù)據(jù)
       * @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;
      
      /**
       * 用戶服務(wù)實現(xiàn)類
       */
      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 用戶數(shù)據(jù)
       * @return User
       * @throws Exception
       */
      @Override
      public User login(User user) throws Exception {
          // 獲取數(shù)據(jù)庫信息
          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>
          /**
           * 執(zhí)行登陸
           */
          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 {
              // 獲取表單數(shù)據(jù)
              this.user = Base.requestToBean(User.class, request, "id,salt,nickname");
              // 執(zhí)行登陸
              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數(shù)據(jù),判斷是否已經(jīng)登陸
          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("退出成功")));
      }
      }
      
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末骂蓖,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子怔锌,更是在濱河造成了極大的恐慌,老刑警劉巖墩新,帶你破解...
    沈念sama閱讀 206,839評論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件帆赢,死亡現(xiàn)場離奇詭異,居然都是意外死亡玉工,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,543評論 2 382
  • 文/潘曉璐 我一進(jìn)店門淘菩,熙熙樓的掌柜王于貴愁眉苦臉地迎上來遵班,“玉大人,你說我怎么就攤上這事潮改∠林#” “怎么了?”我有些...
    開封第一講書人閱讀 153,116評論 0 344
  • 文/不壞的土叔 我叫張陵汇在,是天一觀的道長翰萨。 經(jīng)常有香客問我,道長糕殉,這世上最難降的妖魔是什么亩鬼? 我笑而不...
    開封第一講書人閱讀 55,371評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮阿蝶,結(jié)果婚禮上雳锋,老公的妹妹穿的比我還像新娘。我一直安慰自己羡洁,他們只是感情好玷过,可當(dāng)我...
    茶點故事閱讀 64,384評論 5 374
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著焚廊,像睡著了一般。 火紅的嫁衣襯著肌膚如雪习劫。 梳的紋絲不亂的頭發(fā)上咆瘟,一...
    開封第一講書人閱讀 49,111評論 1 285
  • 那天,我揣著相機(jī)與錄音诽里,去河邊找鬼袒餐。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的灸眼。 我是一名探鬼主播卧檐,決...
    沈念sama閱讀 38,416評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼焰宣!你這毒婦竟也來了霉囚?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,053評論 0 259
  • 序言:老撾萬榮一對情侶失蹤匕积,失蹤者是張志新(化名)和其女友劉穎盈罐,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體闪唆,經(jīng)...
    沈念sama閱讀 43,558評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡盅粪,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,007評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了悄蕾。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片票顾。...
    茶點故事閱讀 38,117評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖帆调,靈堂內(nèi)的尸體忽然破棺而出奠骄,到底是詐尸還是另有隱情,我是刑警寧澤贷帮,帶...
    沈念sama閱讀 33,756評論 4 324
  • 正文 年R本政府宣布戚揭,位于F島的核電站,受9級特大地震影響撵枢,放射性物質(zhì)發(fā)生泄漏民晒。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,324評論 3 307
  • 文/蒙蒙 一锄禽、第九天 我趴在偏房一處隱蔽的房頂上張望潜必。 院中可真熱鬧,春花似錦沃但、人聲如沸磁滚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,315評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽垂攘。三九已至,卻和暖如春淤刃,著一層夾襖步出監(jiān)牢的瞬間晒他,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,539評論 1 262
  • 我被黑心中介騙來泰國打工逸贾, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留陨仅,地道東北人津滞。 一個月前我還...
    沈念sama閱讀 45,578評論 2 355
  • 正文 我出身青樓,卻偏偏與公主長得像灼伤,于是被迫代替她去往敵國和親触徐。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,877評論 2 345

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理狐赡,服務(wù)發(fā)現(xiàn)撞鹉,斷路器,智...
    卡卡羅2017閱讀 134,600評論 18 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法猾警,類相關(guān)的語法孔祸,內(nèi)部類的語法,繼承相關(guān)的語法发皿,異常的語法崔慧,線程的語...
    子非魚_t_閱讀 31,587評論 18 399
  • 一. Java基礎(chǔ)部分.................................................
    wy_sure閱讀 3,791評論 0 11
  • 本文包括:1、Listener簡介2穴墅、Servlet監(jiān)聽器3惶室、監(jiān)聽三個域?qū)ο髣?chuàng)建和銷毀的事件監(jiān)聽器4、監(jiān)聽三個域?qū)?..
    廖少少閱讀 6,002評論 6 28
  • Genius is an infinite capacity for taking pains. 所謂的天才是不斷...
    貝小魚閱讀 1,133評論 0 24