Java Session 介绍

一、添加、获取session

1、项目结构

2、jar包

3、web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>spring</display-name> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-context.xml,/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- log4j配置文件路径 -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param> <context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>6000</param-value>
</context-param> <!-- 加载log4j配置文件 -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener> <!-- springmvc配置 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

4、spring-config.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd"> <!-- 通知spring容器通过注解的方式装配bean -->
<context:annotation-config />
<!-- 通知spring容器采用自动扫描机制查找注解的bean -->
<context:component-scan base-package="com.*" /> <task:annotation-driven /> <!-- 定时器开关--> <bean id="agentExcelTask" class="com.timer.TimerController1"/>
<task:scheduled-tasks>
<task:scheduled ref="agentExcelTask" method="printstr" cron="* * 0/1000 * * ?"/>
</task:scheduled-tasks> <!-- 配置返回页面过滤 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

5、TestSession.java

package com.session;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes; import com.demo.User;
@Controller
@SessionAttributes("user")
public class TestSession { /**
* 用servlet的HttpServletRequest添加信息到session
*/
@RequestMapping("addSession")
public String addSession(User user, HttpServletRequest request, Model model){
request.getSession().setAttribute("user", user);
//request.getSession().removeAttribute("user");//删除 session 指定属性健
//request.getSession().invalidate();//清除所有的session,使当前 session 完全失效
User u = (User) request.getSession().getAttribute("user");
model.addAttribute("name", u.getName());
model.addAttribute("password", u.getPassword());
return "success";
} /**
* 用servlet的HttpSession添加信息到session
*/
@RequestMapping("addSession1")
public String addSession1(User user, HttpSession request, Model model){
request.setAttribute("user", user);
//request.removeAttribute("user");//移除session
//request.invalidate();//清除所有的session,使当前 session 完全失效
User u = (User) request.getAttribute("user");
model.addAttribute("name", u.getName());
model.addAttribute("password", u.getPassword());
return "success";
} }

6、index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>index</title>
</head> <body>
<form action="addSession1" method="post">
用户:<input type="text" name="name"><br><br>
密码:<input type="text" name="password"><br><br>
<input type="submit" value="确定">
</form> <!-- 使用message 标签配置需要显示的国际化文本,
code 对应国际化文件中对应的键的名称 -->
<span style="color: #2D2D2D;">
<spring:message code="main.title"/>
</span>
<br>
<input type="text" value="<spring:message code="main.target"/>">
</body>
</html>

7、success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>success</title>
</head> <body>
${name},success. <br>
用户名:${name},密码:${password}
</body>
</html>

二、设置session超时的3中方式

1.      在web容器中设置(此处以tomcat为例)

在tomcat-5.0.28\conf\web.xml中设置,以下是tomcat 5.0中的默认配置:

<session-config>   

  <session-timeout>30</session-timeout>  

</session-config>

Tomcat默认session超时时间为30分钟,可以根据需要修改,负数或0为不限制session失效时间。

2.      在工程的web.xml中设置

<!-- 时间单位为分钟   -->  

<session-config>

      <session-timeout>15</session-timeout>

</session-config>

3.      通过java代码设置

session.setMaxInactiveInterval(30*60);//以秒为单位

三种方式优先级:1 < 2 <3

servlet之session添加和移除的两种方式的更多相关文章

  1. 添加登录装饰器的两种方式:FBV和CBV

    1.FBV方式:添加验证装饰器 def auth(func): def deco(request, *args, **kwargs): u = request.get_signed_cookie('u ...

  2. spring boot集成 servlet自动注册的两种方式

    有两种方式:(两种方式同时存在时,@Bean优先@ServletComponentScan实例化,生成两个对象) 1)通过@ServletComponentScan类注解 扫描 带有@WebServl ...

  3. SpringBoot整合Servlet的两种方式

    SpringBoot整合Servlet有两种方式: 1.通过注解扫描完成Servlet组件的注册: 2.通过方法完成Servlet组件的注册: 现在简单记录一下两种方式的实现 1.通过注解扫描完成Se ...

  4. 【SpringBoot】03.SpringBoot整合Servlet的两种方式

    SpringBoot整合Servlet的两种方式: 1. 通过注解扫描完成Servlet组件注册 新建Servlet类继承HttpServlet 重写超类doGet方法 在该类使用注解@WebServ ...

  5. Servlet实现重定向的两种方式

    使用Servlet实现请求重定向:两种方式 1. response.setStatus(302); response.setHeader("location", "/Re ...

  6. springmvc和servlet在上传和下载文件(保持文件夹和存储数据库Blob两种方式)

    参与该项目的文件上传和下载.一旦struts2下完成,今天springmvc再来一遍.发现springmvc特别好包,基本上不具备的几行代码即可完成,下面的代码贴: FileUpAndDown.jsp ...

  7. linux中添加一个用户到指定用户组的两种方式,修改一个用户到指定用户组的一种方式

    添加一个用户到指定用户组: gpasswd –a 用户名 组名usermod –G 组名 用户名 //第一种:gpasswd –a 用户名 组名 [root@localhost ~]# id user ...

  8. Servlet访问路径的两种方式、Servlet生命周期特点、计算服务启动后的访问次数、Get请求、Post请求

    Servlet访问路径的两种方式: 1:注解 即在Servlet里写一个@WebServlet @WebServlet("/myServlet") 2:配置web.xml < ...

  9. js如何实现动态的在表格中添加和删除行?(两种方法)

    js如何实现动态的在表格中添加和删除行?(两种方法) 一.总结 1.table元素有属性和一些方法(js使用) 方法一:添加可通过在table的innerHTML属性中添加tr和td来实现 tab.i ...

随机推荐

  1. BZOJ4653: [Noi2016]区间

    传送门 UOJ上卡掉一个点,COGS上卡掉两个点..弃疗,不改了,反正BZOJ上过啦hhh 先把区间按长度递增排序.然后每次用线段树维护区间最大覆盖次数,用一个指针随便扫扫就行了. //NOI 201 ...

  2. JavaScript事件类型

    JavaScript事件类型 Web浏览器中可能发生的事件有很多类型.这里我将主要将下面几种常用的事件类型: UI事件 焦点事件 鼠标与滚轮事件 键盘与文本事件 复合事件 变动事件 HTML5事件 设 ...

  3. logo上传

  4. ecshop JSON,ajax.call 异步传输

    1.res = Ajax.call('user.php?act=depot_id', 'id='+v,null,"GET", "JSON",false); 2. ...

  5. [Unity] UGUI研究院之游戏摇杆

    最近在做Unity基于UGUI的摇杆,发现了一种非常简单并且巧妙的方法,原文在这里, 不过要FQ!!http://godstamps.blogspot.tw/2015/07/unity-ugui-sc ...

  6. HBase中的压缩算法比较 GZIP、LZO、Zippy、Snappy [转]

    网址: http://www.cnblogs.com/panfeng412/archive/2012/12/24/applications-scenario-summary-of-compressio ...

  7. singleton和prototype

    public class testScope { @Test public void test() { //默任singleton ApplicationContext ctx= new ClassP ...

  8. mysql存储过程对900w数据进行操作测试

    新增索引:LTER TABLE `tablename` ADD INDEX `sdhid` (`createTime`) USING BTREE ;[SQL]ALTER TABLE `tablenam ...

  9. [Json.net]忽略不需要的字段

    摘要 在序列化对象,总会遇到一些敏感的信息,这些信息,并不想对调用接口的用户暴露出来,又或者移动端调用接口的时候,为了不返回没用的信息占用流量,这个时候也需要把一些信息给过滤掉. 系列文章 [Json ...

  10. 使程序在Linux下后台运行

    一.为什么要使程序在后台执行 我们计算的程序都是周期很长的,通常要几个小时甚至一个星期.我们用的环境是用putty远程连接到日本Linux服务器.所以使程序在后台跑有以下三个好处: 1:我们这边是否关 ...