中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java中怎么利用servlet實現自動登錄退出功能

發布時間:2021-08-06 16:38:14 來源:億速云 閱讀:248 作者:Leah 欄目:編程語言

本篇文章給大家分享的是有關Java中怎么利用servlet實現自動登錄退出功能,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

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.javapublic User login(User user){try {return ud.login(user);} catch (SQLException e) {// TODO Auto-generated catch blocke.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(6060);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{br/>@Overridepublic 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")){//找到感興趣的cookieusername = cookie.getValue();}if (cookie.getName().equals("password")){//找到感興趣的cookieuserpass = 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);br/>}@Overridepublic void init(FilterConfig filterConfig) throws ServletException {// TODO Auto-generated method stubbr/>}@Overridepublic void destroy() {// TODO Auto-generated method stub}}

前臺:login.jsp此單選框被選中下次訪問即為自動登錄

<p class="checkbox"><label> <input type="checkbox" name="autoLogin" > 自動登錄</label>   <label> <inputtype="checkbox" > 記住用戶名</label></p><%@ 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><p id="nav"><p id="logo"><img src="csdn-logo.png" width="180" height="88"></p><p id="userinfo"><%-- 不推薦使用<%String loginUser = (String) request.getAttribute("loginUser");if (loginUser != null){out.println(loginUser);}else {%><a href="login.jsp" rel="external nofollow" rel="external nofollow" rel="external nofollow" >登錄</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" rel="external nofollow" rel="external nofollow" rel="external nofollow" >登錄</a><a>/注冊</a><%}%></p></p><p id="container">

主頁內容

<a href="info.jsp" rel="external nofollow" >Python——畫一棵漂亮的櫻花樹(不同種櫻花+玫瑰+圣誕樹喔)</a></p></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"><h2 align="center">登錄</h2><table width="500" border="1" cellspacing="0" cellpadding="0" align="center"><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><p id="nav"><p id="logo"><img src="csdn-logo.png" width="180" height="88"></p><p 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" rel="external nofollow" rel="external nofollow" rel="external nofollow" >登錄</a><a>/注冊</a><%}%></p></p><p id="container">主頁內容</p></body></html>

Servlet02.java

import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.io.IOException;br/>@WebServlet("/myServlet02")public class Servlet02 extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//修改編碼request.setCharacterEncoding("utf-8");//請求過來的編碼是亨達返傭www.kaifx.cn/broker/hantecglobal.htmlutf-8response.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步驟//獲取sessionHttpSession 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;br/>@WebServlet("/logoutServlet")public class LogoutServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//退出系統//獲取sessionHttpSession session = request.getSession();//刪除sessionsession.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>

以上就是Java中怎么利用servlet實現自動登錄退出功能,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

疏附县| 清涧县| 汝阳县| 大足县| 比如县| 南投市| 光山县| 肃宁县| 富源县| 铅山县| 宁夏| 保德县| 祥云县| 蒙城县| 安西县| 明光市| 蒲城县| 健康| 平罗县| 额济纳旗| 凤凰县| 西昌市| 屯门区| 嵩明县| 年辖:市辖区| 柞水县| 仁布县| 五莲县| 崇明县| 福建省| 隆子县| 黄冈市| 枞阳县| 庆阳市| 安达市| 康乐县| 彭泽县| 阿克陶县| 株洲县| 青龙| 进贤县|