一套完整的登陸注冊業(yè)務(wù)邏輯
- 準(zhǔn)備部分
- 基礎(chǔ)工具類
- 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; } }
- 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(); } } }
- 數(shù)據(jù)庫配置db.properties
driver=com.mysql.jdbc.Driver dns=jdbc:mysql://localhost:3306/yjzblog user=root pwd=1
- web.xml
<?xml version="1.0" encoding="UTF-8"?>
- 基礎(chǔ)工具類
<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;
}
}
```
- 業(yè)務(wù)實現(xiàn)
- 主頁(引導(dǎo)頁)
- 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>
- 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); } }
- 注冊
- 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>
- 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); } }
- 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; }
- 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; } }
- 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; }
- 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; } } }
- 登陸
- 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>
- 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); } } }
- 歡迎頁
- 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>
- 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); } } }
- 退出登陸
- 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("退出成功"))); } }
- 主頁(引導(dǎo)頁)