用户注销时 处理session<原>

本文探讨了用户注销过程中Session管理的最佳实践。指出简单清除Session值可能导致的安全隐患,并建议使用HttpSession的invalidate()方法来彻底销毁Session,以避免潜在的用户权限误用问题。
当一个用户注销时,最好的办法是将这个session 失效,即调用 HttpSession的invalidate()方法。因为如果仅仅清除Session中的值,会存在潜在的问题,一般的操作可能没有问题,有时就会存在问题,比如A用户登录后,使用IE6浏览器新建一个窗口,然后在新的窗口中注销用户,再用B用户登录,则此时,A用户就有了B用户的操作权限,因为系统会将A用户当作B用户。
# 题目重述 根据《第三次实验-使用会话技术记录用户登录状态.docx》的要求,构建一个完整的 Web 应用系统,实现基于 **Session** 的用户登录状态管理。要求从零开始搭建项目结构、创建必要文件(HTML、JSP、Servlet、JavaBean 等),并通过会话技术控制资源访问权限:未登录用户无法访问 `index.jsp`,登录后可访问并能注销。 --- # 详解 ## ✅ 第一步:创建 Maven Web 项目 ### 1. 打开 IntelliJ IDEA → New Project → Maven Archetype 选择:`maven-archetype-webapp` 填写项目信息: - GroupId: `com.example` - ArtifactId: `session-demo` - Version: `1.0-SNAPSHOT` 点击“Finish”,生成基础 Web 项目。 ### 2. 补全目录结构(手动创建) Maven 默认不生成某些目录,需手动补全: ``` src └── main ├── java ← 新建此目录(标记为 Sources Root) ├── resources ← 新建此目录(标记为 Resources Root) └── webapp ├── WEB-INF │ └── web.xml ├── login.html ← 创建 └── index.jsp ← 创建 ``` 右键 `java` 目录 → Mark Directory as → **Sources Root** --- ## ✅ 第二步:配置 `pom.xml` 添加依赖 编辑 `pom.xml`,添加 Servlet、JSP、JSTL 支持(注意 Tomcat 10+ 使用 Jakarta 命名空间): ```xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>session-demo</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> <failOnMissingWebXml>false</failOnMissingWebXml> </properties> <dependencies> <!-- Jakarta Servlet API --> <dependency> <groupId>jakarta.servlet</groupId> <artifactId>jakarta.servlet-api</artifactId> <version>6.0.0</version> <scope>provided</scope> </dependency> <!-- Jakarta JSP API --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <version>10.1.0</version> <scope>provided</scope> </dependency> <!-- Jakarta JSTL --> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>jakarta.servlet.jsp.jstl</artifactId> <version>3.0.0</version> </dependency> </dependencies> <build> <finalName>session-demo</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <source>17</source> <target>17</target> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>8080</port> <path>/</path> </configuration> </plugin> </plugins> </build> </project> ``` > 💡 提示:若使用本地 Tomcat,可忽略插件部分,直接部署到外部服务器。 --- ## ✅ 第三步:创建前端登录页面 `login.html` 路径:`src/main/webapp/login.html` ```html <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>用户登录</title> </head> <body style="font-family: Arial;"> <h3>请登录</h3> <form action="login" method="post"> 用户名:<input type="text" name="username" required><br><br> 密码:<input type="password" name="password" required><br><br> <input type="submit" value="登录"> </form> </body> </html> ``` --- ## ✅ 第四步:创建主资源页面 `index.jsp` 路径:`src/main/webapp/index.jsp` ```jsp <%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" isELIgnored="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>欢迎页</title> </head> <body style="font-family: Arial;"> <!-- 判断用户是否已登录 --> <c:if test="${user == null}"> <c:redirect url="login.html"/> </c:if> <h3>登录成功!欢迎您,${user.name}!</h3> <p><a href="logout">【注销】</a></p> </body> </html> ``` > 🔍 理:利用 EL 表达式 `${user}` 检查 Session 中是否存在用户对象,不存在则跳转。 --- ## ✅ 第五步:创建 JavaBean 类 `User.java` 路径:`src/main/java/com/example/entity/User.java` ```java package com.example.entity; public class User { private String username; private String name; public User(String username, String name) { this.username = username; this.name = name; } // Getters and Setters public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` > ⚠️ 包名建议规范:`com.example.entity` 或 `bean` --- ## ✅ 第六步:创建三个核心 Servlet ### ① LoginServlet.java —— 处理登录请求 路径:`src/main/java/com/example/servlet/LoginServlet.java` ```java package com.example.servlet; import com.example.entity.User; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.*; import java.io.IOException; @WebServlet("/login") public class LoginServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); // 模拟认证(生产环境应查数据库) if ("admin".equals(username) && "123456".equals(password)) { User user = new User(username, "管理员"); HttpSession session = request.getSession(); session.setAttribute("user", user); session.setMaxInactiveInterval(30 * 60); // 30分钟 // 将 JSESSIONID 写入 Cookie Cookie cookie = new Cookie("JSESSIONID", session.getId()); cookie.setPath("/"); cookie.setMaxAge(30 * 60); // 与 session 一致 response.addCookie(cookie); response.sendRedirect("index.jsp"); } else { response.setContentType("text/html;charset=utf-8"); response.getWriter().println("登录失败,请重新登录!<br><a href='login.html'>返回登录页</a>"); } } } ``` --- ### ② LogoutServlet.java —— 处理注销请求 路径:`src/main/java/com/example/servlet/LogoutServlet.java` ```java package com.example.servlet; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.*; import java.io.IOException; @WebServlet("/logout") public class LogoutServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); if (session != null) { session.removeAttribute("user"); // 清除用户 // 可选:session.invalidate(); 销毁整个会话 } response.sendRedirect("login.html"); } } ``` --- ### ③ (可选)ResourceServlet —— 统一资源入口控制(替代JSP判断) 本实验中由 `index.jsp` 自行判断,故非必需。但可用于更复杂场景。 --- ## ✅ 第七步:配置 `web.xml`(可选,现代Servlet可省略) 路径:`src/main/webapp/WEB-INF/web.xml` ```xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd" version="5.0"> <!-- 设置会话间为30分钟 --> <session-config> <session-timeout>30</session-timeout> </session-config> </web-app> ``` > 📝 注解方式已取代大部分XML配置,但 `session-timeout` 在 `web.xml` 中设置更直观。 --- ## ✅ 第八步:部署与运行 ### 方式一:使用内置插件运行(推荐学习阶段) 在命令行执行: ```bash mvn tomcat7:run ``` 访问地址:`http://localhost:8080/session-demo/login.html` ### 方式二:部署到本地 Tomcat 1. 编译打包:`mvn clean package` 2. 将生成的 `target/session-demo.war` 放入 `$TOMCAT_HOME/webapps/` 3. 启动 Tomcat:`startup.bat` 或 `startup.sh` 4. 访问:`http://localhost:8080/session-demo/login.html` --- ## ✅ 第九步:测试功能 | 测试项 | 操作 | 预期结果 | |-------|------|---------| | 未登录访问 index.jsp | 直接输入 URL | 自动跳转到 `login.html` | | 正确登录 | 用户名=admin, 密码=123456 | 跳转至 `index.jsp` 显示欢迎语 | | 点击“注销” | 点击链接 | Session 清除,跳回登录页 | | 重新访问 index.jsp | 不登录直接访问 | 再次跳转登录页 | | 30分钟内关闭浏览器再打开 | 保留 Cookie | 若 Session 未失效仍可访问 | --- # 知识点 ## 1. **HttpSession 会话管理** 服务器通过 HttpSession 存储用户状态,实现跨请求的身份识别,是保障安全访问的核心机制。 ## 2. **Cookie 与 Session 协同机制** Cookie 存储 JSESSIONID,使得客户端能持续持有会话凭证,从而维持登录状态。 ## 3. **JSP + JSTL + EL 表达式联合控制流程** 使用 `${user}` 获取 Session 属性,结合 `<c:if>` 和 `<c:redirect>` 实现页面级权限控制,增强安全性与可维护性。请再实现一下注册的功能
最新发布
11-24
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ page import="javax.servlet.*,java.text.*" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="renderer" content="webkit"> <title>收入综合分析平台</title> <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/bootstrap-3.3.7-dist/css/bootstrap.min.css"> <%-- 右击菜单样式 --%> <link href="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/css/jquery.contextMenu.min.css" rel="stylesheet"/> <%-- <link href="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/css/animate.min.css" rel="stylesheet"/>--%> <link href="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/css/style.min.css" rel="stylesheet"/> <link href="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/css/skins.css" rel="stylesheet"/> <link href="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/css/ry-ui.css?v=4.6.1" rel="stylesheet"/> <%-- 图标库 --%> <link href="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/css/font-awesome.min.css" rel="stylesheet"/> <script src="${pageContext.request.contextPath}/resources/js/jquery-1.11.3.min.js?v=<%=System.currentTimeMillis()%>"></script> <script src="${pageContext.request.contextPath}/resources/bootstrap-3.3.7-dist/js/bootstrap.min.js?v=<%=System.currentTimeMillis()%>"></script> <script src="${pageContext.request.contextPath}/resources/global/global.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript"> $(function(){ $.ajax({ type: 'get', url: "dic/getUrlByUser", async: false, dataType: 'json', success: function (data) {//返回list数据并循环获取 var ht = ""; var arr = ['desktop','calculator','leanpub','map','send','bar-chart','line-chart','train','american-sign-language-interpreting','gears','user-circle-o','paper-plane','firefox']; for(var i=0;i<data.length;i++){ //循环一级菜单 ht = ht +'<li>'+ '<a href="#">' + '<i class="fa fa-'+arr[i]+'"></i> ' + '<span class="nav-label">'+data[i].mkName+'</span>' + '<span class="fa arrow"></span>' + '</a>'+ '<ul class="nav nav-second-level collapse">'; var obj = data[i].obj; if(obj[0].cdlb == ""){//该模块不存在二级菜单 for(var j=0;j<obj.length;j++){ ht = ht + '<li>\n' + '<a class="menuItem" href="'+obj[j].cdUrl+'">'+ obj[j].cdName +'</a>' + '</li>'; } ht = ht + '</ul></li>'; }else{ var cdlbArr = new Array(); for(var j=0;j<obj.length;j++){ cdlbArr.push(obj[j].cdlb); } cdlbArr = uniqueArr(cdlbArr); for(var k=0;k<cdlbArr.length;k++){ ht = ht + '<li>\n' + '<a href="#"><i class="fa fa-pied-piper"></i> '+cdlbArr[k]+'<span class="fa arrow"></span></a>\n' + '<ul class="nav nav-third-level collapse">'; for(var m=0;m<obj.length;m++){ if(cdlbArr[k] == obj[m].cdlb){ ht = ht + '<li>\n' + '<a class="menuItem" href="'+obj[m].cdUrl+'">'+ obj[m].cdName +'</a>' + '</li>'; } } ht = ht + '</ul></li>'; } } ht = ht + '</ul></li>'; } $("#side-menu").append(ht); } }); }) /* * 用于解决浏览器关闭后Cookie未失效,攻击者可在用户关闭浏览器后,通过同一cookie直接访问网站(无需重新登录),窃取用户会话; * 由于ajax是异步 使用会造成发送不过去的现象 需要使用同步请求 * 另外 如果只是使用 window.addEventListener('beforeunload'来判断 会出现 刷野也会消除session 所以只能通过一下方法来实现 * */ window.addEventListener('beforeunload', function(e) { // 获取导航类型(替代废弃的performance.navigation.type) console.log(JSON.stringify(performance.getEntriesByType("navigation")[0].toJSON().type)) const navType = performance.getEntriesByType("navigation")[0].toJSON().type; sendLogoutRequest(navType) // 排除刷新行为,仅在离开/关闭触发逻辑 if (navType !== 'reload') { console.log('离开页面,执行逻辑') //sendLogoutRequest() return '111'; } }); /*class PageLeaveHandler { constructor() { this.isRefreshing = false; this.pendingUnload = false; this.pendingUnloadnum = 0;//默认值 this.init(); } init() { // 监听刷新快捷键 window.addEventListener('keydown', (e) => { if (e.key === 'F5' || (e.ctrlKey && e.key === 'F5')) { this.isRefreshing = true; } }); // 监听beforeunload事件 window.addEventListener('beforeunload', this.handleBeforeUnload.bind(this)); } handleBeforeUnload(e) { if (this.isRefreshing) { this.pendingUnload = false; return; } //sendLogoutRequest(this.isRefreshing) this.pendingUnload = true; return 1; } } new PageLeaveHandler();*/ function sendLogoutRequest(navType) { const logoutUrl = '${pageContext.request.contextPath}/sys/loginoutall?navType='+navType; if (navigator.sendBeacon) { navigator.sendBeacon(logoutUrl, 'loginoutall'); } else { const xhr = new XMLHttpRequest(); xhr.open('GET', logoutUrl, false); // 同步请求 xhr.timeout = 2000; try { xhr.send(); } catch (e) { // 忽略错误 } } } /*window.addEventListener('beforeunload', function(e) { // 取消事件的默认行为(部分浏览器需要) e.preventDefault(); if(!e.isTrusted){ // 2. 拼接正确的上下文路径(关键:避免404) const logoutUrl = '${pageContext.request.contextPath}/sys/loginoutall'; // 3. 用sendBeacon发送请求,浏览器会优先保证发送完成 if (navigator.sendBeacon) { navigator.sendBeacon(logoutUrl, 'loginoutall'); } else { const xhr = new XMLHttpRequest(); xhr.open('GET', logoutUrl, false); // 同步请求 xhr.timeout = 2000; try { xhr.send(); } catch (e) { } } } });*/ </script> </head> <body class="fixed-sidebar full-height-layout gray-bg skin-blue theme-light" style="overflow: hidden"> <div id="wrapper"> <!--左侧导航开始--> <nav class="navbar-default navbar-static-side" role="navigation"> <div class="nav-close"> <i class="fa fa-times-circle"></i> </div> <a href=""> <li class="logo hidden-xs"> <span class="logo-lg">欢迎${user.username}</span> </li> </a> <div class="sidebar-collapse"> <ul class="nav" id="side-menu"> <li> <div class="user-panel"> <%-- 该位置换谁个人中心地址 --%> <a class="menuItem noactive" title="个人中心" href=""> <div class="hide" text="个人中心"></div> <div class="pull-left image"> <%--<img src="resources/ruoyi/favicon.ico" class="img-circle" alt="User Image">--%> <img src="resources/image/eee.png" class="img-circle" alt="User Image"> </div> </a> <div class="pull-left info"> <%-- 该位置可以加上el表达式 然后读取成登录名即可 --%> <p></p> <a href="#"><i class="fa fa-circle text-success"></i> 在线</a> <%-- 该位置发起退出请求 换上即可 --%> <a href="sys/loginout" style="padding-left:5px;"><i class="fa fa-sign-out text-danger"></i> 注销</a> </div> </div> </li> <li> <a class="menuItem" href="web/main/sy.jsp"><i class="fa fa-home"></i> <span class="nav-label">首页</span></a> </li> </ul> </div> </nav> <!--左侧导航结束--> <!--右侧部分开始--> <div id="page-wrapper" class="gray-bg dashbard-1"> <div class="row border-bottom"> <nav class="navbar navbar-static-top" role="navigation" style="margin-bottom: 0"> <div class="navbar-header"> <a class="navbar-minimalize minimalize-styl-2" style="color:#FFF;" href="#" title="收起菜单"> <i class="fa fa-bars"></i> </a> </div> <ul class="nav navbar-top-links navbar-right welcome-message"> <%--<li><a data-toggle="tooltip" data-trigger="hover" data-placement="bottom" title="开发文档" href="http://doc.ruoyi.vip/ruoyi" target="_blank"><i class="fa fa-question-circle"></i> 文档</a></li> <li><a data-toggle="tooltip" data-trigger="hover" data-placement="bottom" title="锁定屏幕" href="#" id="lockScreen"><i class="fa fa-lock"></i> 锁屏</a></li>--%> <li><a data-toggle="tooltip" data-trigger="hover" data-placement="bottom" title="全屏显示" href="#" id="fullScreen"><i class="fa fa-arrows-alt"></i> 全屏</a></li> <%--<li class="dropdown user-menu"> <a href="javascript:void(0)" class="dropdown-toggle" data-hover="dropdown"> <img src="resources/image/eee.png" class="user-image"> <%– 该位置用el表达式读取登录名 –%> <span class="hidden-xs">海来怡天</span> </a> <ul class="dropdown-menu"> <li class="mt5"> <%– 该位置是个人中心超链接 –%> <a href="" class="menuItem noactive"> <i class="fa fa-user"></i> 个人中心</a> </li> <li> <a onclick="resetPwd()"> <i class="fa fa-key"></i> 修改密码</a> </li> <li> <a onclick="switchSkin()"> <%–<a id="btn" >–%> <i class="fa fa-dashboard"></i> 切换主题 </a> </li> <li class="divider"></li> <li> <%– 该位置是推出登录请求 –%> <a href=""> <i class="fa fa-sign-out"></i> 退出登录</a> </li> </ul> </li>--%> </ul> </nav> </div> <div class="row content-tabs"> <button class="roll-nav roll-left tabLeft"> <i class="fa fa-backward"></i> </button> <nav class="page-tabs menuTabs"> <div class="page-tabs-content"> <a href="javascript:" class="active menuTab" data-id="web/main/sy.jsp">首页</a> </div> </nav> <button class="roll-nav roll-right tabRight"> <i class="fa fa-forward"></i> </button> <a href="javascript:void(0);" class="roll-nav roll-right tabReload"><i class="fa fa-refresh"></i> 刷新</a> </div> <a id="ax_close_max" class="ax_close_max" href="#" title="关闭全屏"> <i class="fa fa-times-circle-o"></i> </a> <div class="row mainContent" id="content-main" > <iframe class="RuoYi_iframe" name="iframe0" width="100%" height="100%" data-id="web/main/sy.jsp" src="web/main/sy.jsp" frameborder="0" seamless></iframe> </div> </div> <!--右侧部分结束--> </div> <!-- 全局js --> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/js/plugins/metisMenu/jquery.metisMenu.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/js/plugins/slimscroll/jquery.slimscroll.min.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/js/jquery.contextMenu.min.js?v=<%=System.currentTimeMillis()%>"></script> <%--<script src="${pageContext.request.contextPath}/resources/ruoyi/ajax/libs/layui/layui.js?v=<%=System.currentTimeMillis()%>"></script>--%> <%-- 该方法用于将页面加载到本页面 --%> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/ajax/libs/blockUI/jquery.blockUI.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/ajax/libs/layer/layer.min.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/js/ry-ui.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/js/common.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/index.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/ajax/libs/fullscreen/jquery.fullscreen.js?v=<%=System.currentTimeMillis()%>"></script> <script> /*window.history.forward(1); var ctx = "/zhfx"; // 皮肤缓存 var skin = storage.get("skin");*/ // history(表示去掉地址的#)否则地址以"#"形式展示 var mode = "history"; // 历史访问路径缓存 var historyPath = storage.get("historyPath"); // 是否页签与菜单联动 var isLinkage = true; /* * 这个js如果删了 按下F12编辑 页面会不起作用 * */ $(function() { var lockPath = storage.get('lockPath'); if($.common.equals("history", mode) && window.performance.navigation.type == 1) { var url = storage.get('publicPath'); if ($.common.isNotEmpty(url)) { applyPath(url); } } else if($.common.isNotEmpty(lockPath)) { applyPath(lockPath); storage.remove('lockPath'); } else { var hash = location.hash; if ($.common.isNotEmpty(hash)) { var url = hash.substring(1, hash.length); applyPath(url); } else { if($.common.equals("history", mode)) { storage.set('publicPath', ""); } } } $("[data-toggle='tooltip']").tooltip(); }); </script> </body> </html> 为什么 一个刷新 一个跳转 这俩 点刷新是reload 再点跳转还是reload 必须第二下才是navigate 但是这样点了navigate之后 再点刷新还是navigate 必须再点刷新才是reload 这可不能这样
11-12
现在要进行一个实验:实验二 Servlet进阶和JSP基础 一、实验目的 (1)掌握Servlet处理session以及Cookie的方法。 (2)掌握JSP的编写方法。 (3)掌握JSP中变量、表达式的使用。 二、 实验环境和要求 (1)使用Eclipse、Tomcat以及浏览器等作为实验环境。 (2)实验前应做好设计规划,充分准备,对各个问题预先编制程序。 (3)在实验中遇到困难运用多种手段解决问题。 三、 实验内容 (1) 使用表单提交的方式交给Servlet处理,完成用户登录以及退出操作,并利用会话和Cookie实现自动登录功能。我创建了一个login.jsp,代码为:<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% String username = ""; String password = ""; Cookie[] cookies = request.getCookies(); if(cookies!= null){ String userinfo = null; for(int i=0;i<cookies.length;i++){ if(cookies[i].getName( ).equals("userinfo")){ userinfo= cookies[i].getValue(); break; } } if(userinfo!=null){ String[ ] information = userinfo. split("\\|" ); username=information[0]; password= information[1]; } } %> <form action = "LoginServlet" method="post"> 用户名:<input type = "text" name = "username" value = <%= username %>> <br> 密   码: <input type = "password" name = "password" value = <%= password %>><br> <input type = "submit" value = "登录"><input type = "reset" value = "重置"> </form> </body> </html>,又创建了一个LoginServlet,代码为:package com.test.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class LoginServlet */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LoginServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-type","text/plain;charset = UTF -8" ); String username = request.getParameter("username"); String password= request.getParameter("password" ); if(username!=null&&password!= null) { if(username.equals(password)) { HttpSession session = request.getSession(); session.setAttribute("username", username); Cookie userinfocookie = new Cookie("userinfo" ,username + "|"+ password); userinfocookie.setMaxAge(60*5); response.addCookie(userinfocookie); response.sendRedirect("welcome. jsp" ); }else { //跳转到欢迎页面 response.getWriter().append("用户名密码错误,请重新登录5 秒后回到登录页面……"); response.setHeader("Refresh","5;URL= login.jsp"); } }else { response.getWriter().append("禁止直接访问,5秒后回到登录页面……"); response.setHeader("Refresh","5;URL = login.jsp"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } ,接着创建了一个welcome.jsp,代码为:<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% response.setHeader("Pragma" ,"No - Cache" ); response.setHeader( "Cache - Control" , "No - Cache" ); response.setDateHeader("Expires",0); if(session!= null){ String username =(String)session.getAttribute("username"); if(username!=null) {out.print("欢迎您,"+ username + "<a href ='LogoutServlet'>安全退出</a>"); } else { out.print("你还没有登录,5秒后跳转到登录页面……"); response.setHeader("Refresh","5;URL=login.jsp"); } }else{ out.print("禁止直接访问,5秒后跳转到登录页面……"); response.setHeader("Refresh","5;URL=login.jsp"); } %> </body> </html>,最后创建了一个LogoutServlet,代码为:package com.test.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class LogoutServlet */ @WebServlet("/LogoutServlet") public class LogoutServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LogoutServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setCharacterEncoding("UTF-8"); response.setHeader("Content- type" ,"text/plain;charset = UTF - 8" );//判断当前请求是否存在对象 HttpSession session =request.getSession(false); if(session!= null) { session.invalidate(); Cookie usernameinfo = new Cookie("userinfo" , "" ); usernameinfo.setMaxAge(0); response.addCookie(usernameinfo); response.getWriter().append("注销成功,5秒后跳转到登录页面……"); response. setHeader("Refresh", "5;URL, = login. jsp" ); }else{ response.getWriter().append("你还未登录,无须注销5秒后跳转到登录页面……"); response. setHeader(" Refresh", "5 ;URL = login. jsp" ); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } ,请问能完成这个实验的要求吗,如果不能请在我的代码上改动
11-10
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值