Java Servlet session實現登入退出
UserDao.java 從資料庫中查詢使用者名稱與密碼
// 登入
public User login(User user) throws SQLException {
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from user where username = ? and password = ?";
return qr.query(sql, new BeanHandler<User>(User.class),user.getUsername(),user.getPassword());
}
UserService.java
public User login(User user){
try {
return ud.login(user);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
UserServlet.java 實現登入功能
// 登入
public void login(HttpServletRequest request,
HttpServletResponse response) throws IOException, IllegalAccessException, InvocationTargetException, ServletException{
Map<String,String[]> map = request.getParameterMap();
User user = new User();
BeanUtils.populate(user,map);
if (map.get("autoLogin")!=null){
Cookie username = new Cookie("username", map.get("username")[0]);
username.setMaxAge(60*60);
Cookie password = new Cookie("password", map.get("password")[0]);
password.setMaxAge(60*60);
response.addCookie(username);
response.addCookie(password);
}
user = us.login(user);
if (user != null){
request.getSession().setAttribute("user", user);
response.sendRedirect("/ShopStore/default.jsp");
}
else{
request.setAttribute("message", " 使用者或密碼錯誤! ");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
工具類:AutoLoginFilter.java 用來實現自動登入
package com.yinhe.web.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.yinhe.bean.User;
import com.yinhe.service.UserService;
public class AutoLoginFilter implements Filter{
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
// 是否已登入
if (req.getSession().getAttribute("user") == null){// 如果已登入,則啥都不幹
// 判斷 cookie 中有沒有賬戶密碼
Cookie[] cookies = req.getCookies();
if (cookies != null){
String username = "";
String userpass = "";
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")){// 找到感興趣的 cookie
username = cookie.getValue();
}
if (cookie.getName().equals("password")){// 找到感興趣的 cookie
userpass = cookie.getValue();
}
}
UserService us = new UserService();
User user = new User();
user.setUsername(username);
user.setPassword(userpass);
if (us.login(user) != null){
req.getSession().setAttribute("user", user);
}
}
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
前臺:login.jsp 此單選框被選中下次訪問即為自動登入
<div>
<label> <input type="checkbox" name="autoLogin" > 自動登入
</label> <label> <input
type="checkbox" > 記住使用者名稱
</label>
</div>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> 系統首頁 </title>
<style>
#nav{
height: 88px;
padding: 5px 200px;
background-color: aquamarine;
}
#logo{
float: left;
}
#userinfo{
float: right;
height: 50px;
line-height: 80px;
}
#container{
background-color: aqua;
height: 800px;
margin: 2px 200px;
font-size: xx-large;
text-align: center;
}
</style>
</head>
<body>
<div id="nav">
<div id="logo">
<img src="csdn-logo_.png" width="180" height="88">
</div>
<div id="userinfo">
<%-- 不推薦使用
<%
String loginUser = (String) request.getAttribute("loginUser");
if (loginUser != null){
out.println(loginUser);
}else {
%>
<a href="login.jsp"> 登入 </a><a>/ 註冊 </a>
<%
}
%>
--%>
<%
String loginUser = (String) session.getAttribute("loginUser");
if (loginUser != null){
out.println(loginUser);
out.println("<a href='logoutServlet'> 退出 </a>");
}else {
%>
<a href="login.jsp"> 登入 </a><a>/ 註冊 </a>
<%
}
%>
</div>
</div>
<div id="container">
主頁內容
<a href="info.jsp">Python ——畫一棵漂亮的櫻花樹(不同種櫻花 + 玫瑰 + 聖誕樹喔) </a>
</div>
</body>
</html>
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> 登入 </title>
<style>
tr{
height:50px;
}
td{
text-align: center;
}
</style>
</head>
<body>
<%
String msg = (String)request.getAttribute("msg");
%>
<%
if(msg != null){
out.print(msg);
}
%>
<form action="myServlet02" method="get">
<h1> 登入 </h1>
<table width="500" border="1" cellspacing="0" cellpadding="0">
<tr>
<td> 賬號: </td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td> 密碼: </td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value=" 登入 " /></td>
</tr>
</table>
</form>
</body>
</html>
info.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<style>
#nav{
height: 88px;
padding: 5px 200px;
background-color: aquamarine;
}
#logo{
float: left;
}
#userinfo{
float: right;
height: 50px;
line-height: 80px;
}
#container{
background-color: aqua;
height: 800px;
margin: 2px 200px;
font-size: xx-large;
text-align: center;
}
</style>
</head>
<body>
<div id="nav">
<div id="logo">
<img src="csdn-logo_.png" width="180" height="88">
</div>
<div id="userinfo">
<%
String loginUser = (String) session.getAttribute("loginUser");
if (loginUser != null){
out.println(loginUser);
out.println("<a href='logoutServlet'> 退出 </a>");
}else {
%>
<a href="login.jsp"> 登入 </a><a>/ 註冊 </a>
<%
}
%>
</div>
</div>
<div id="container">
主頁內容
</div>
</body>
</html>
Servlet02.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/myServlet02")
public class Servlet02 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 修改編碼
request.setCharacterEncoding("utf-8");// 請求過來的編碼是外匯IBhttp://www.kaifx.cn/ utf-8
response.setContentType("text/html;charset=utf-8");// 響應出去的內容,為網頁編碼 utf-8
// 獲取表單資料
String username = request.getParameter("username");
String password = request.getParameter("password");
// 驗證
if("aaa".equals(username) && "123".equals(password)){
// 跳轉 ( 請求轉發 請求重定向 )
// 重定向:兩次請求,不能在 request 作用域享資料。
// 如果要在兩次請求或多次請求之間,進行資料共享,需要用 session
// 使用 session 步驟
// 獲取 session
HttpSession session = request.getSession();// 如果存在已有的 session ,則直接返回,否則會建立一個新的,返回。
//HttpSession session = request.getSession(true);// 同上
//HttpSession session = request.getSession(false);// 如果存在已有的 session ,則直接返回,否則返回 null 。
// 在 session 的作用域儲存資料,供後續請求使用
session.setAttribute("loginUser",username);
response.sendRedirect("index.jsp");
/* 多個頁面不推薦使用請求轉發
request.setAttribute("loginUser",username);
request.getRequestDispatcher("index.jsp").forward(request,response);
*/
}else {
// 轉發:一次請求,可以在 request 作用域中,共享資料
request.setAttribute("msg","<script>alert(' 登入失敗! ');</script>");
// response.sendRedirect("login.jsp");
request.getRequestDispatcher("login.jsp").forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
LogoutServlet.java
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/logoutServlet")
public class LogoutServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 退出系統
// 獲取 session
HttpSession session = request.getSession();
// 刪除 session
session.removeAttribute("loginUser");
// 跳轉到登入頁面 / 首頁
response.sendRedirect("index.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946279/viewspace-2662508/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- Servlet+Session+Cookie登入、校驗、退出的邏輯程式碼ServletSessionCookie
- Auth Session 退出他人正登入的賬號、passport 退出登入SessionPassport
- Java 中使用 Session 物件(以登入、退出功能為例)JavaSession物件
- 基於 Session 實現簡訊登入Session
- 基於session的登入與退出思維導圖Session
- JSP(ajax)+Servlet實現簡單的登入功能JSServlet
- Spring Security 實戰乾貨:實現自定義退出登入Spring
- express+vue+mongodb+session 實現註冊登入ExpressVueMongoDBSession
- layui使用html+servlet+ajax實現登入驗證UIHTMLServlet
- Flask——登入、退出Flask
- java實現微信登入Java
- 【Java】——模擬登入實現Java
- 短影片商城系統,session和cookie實現登入SessionCookie
- Laravel 通過 cookie 實現基於 session 的單點登入LaravelCookieSession
- Spring Boot退出登入注意點Spring Boot
- session與登入機制Session
- Java Web實現使用者登入功能JavaWeb
- Flutter 登入退出功能注意事項Flutter
- Java實現QQ第三方登入Java
- Cookie和Session的區別,Koa2+Mysql+Redis實現登入邏輯CookieSessionMySqlRedis
- win10怎麼退出登入賬戶_win10電腦退出賬戶登入的方法Win10
- jsp+servlet登入註冊頁面JSServlet
- Servlet的實現Servlet
- Java 語言實現簡易版掃碼登入Java
- jwt與session的登入鑑權JWTSession
- Flask Session 登入認證模組FlaskSession
- java視窗登入介面實現隨機驗證碼Java隨機
- PHP 會話(Session)如何實現使用者登陸功能PHP會話Session
- session屬性的清除和非法登入Session
- python爬蟲如何用session保持登入?Python爬蟲Session
- 基於servlet+原生dbc的登入案例(含servlet知識點梳理)Servlet
- 怎麼實現谷歌登入?谷歌
- Django2 Web 實戰02-使用者註冊登入退出DjangoWeb
- 簡單登入註冊實現(Java物件導向複習)Java物件
- Next.js-Cookie鑑權+續期+退出登入JSCookie
- 2.登入/退出功能(路由導航守衛)路由
- Cookie&Session,登入的那些小事兒~CookieSession
- servlet實現下載功能Servlet