Servlet(二)
ServletConfig对象
9.1 作用
ServletConfig对象: 主要是用于加载servlet的初始化参数。在一个web应用可以存在多个ServletConfig对象(一个Servlet对应一个ServletConfig对象)
9.2 对象创建和得到
创建时机: 在创建完servlet对象之后,在调用init方法之前创建。
得到对象: 直接从有参数的init方法中得到!!!
9.3 servlet的初始化参数配置
<servlet>
<servlet-name>ConfigDemo</servlet-name>
<servlet-class>gz.itcast.f_config.ConfigDemo</servlet-class>
<!-- 初始参数: 这些参数会在加载web应用的时候,封装到ServletConfig对象中 -->
<init-param>
<param-name>path</param-name>
<param-value>e:/b.txt</param-value>
</init-param>
</servlet>
注意: servlet的参数只能由当前的这个sevlet获取!!!!
ServletConfig的API:
java.lang.String getInitParameter(java.lang.String name) 根据参数名获取参数值
java.util.Enumeration getInitParameterNames() 获取所有参数
ServletContext getServletContext() 得到servlet上下文对象
java.lang.String getServletName() 得到servlet的名称
1 package com.uplooking.controller;
2
3 import java.io.IOException;
4 import javax.servlet.ServletException;
5 import javax.servlet.http.HttpServlet;
6 import javax.servlet.http.HttpServletRequest;
7 import javax.servlet.http.HttpServletResponse;
8
9 //@WebServlet("/DemoAction")
10 public class DemoAction extends HttpServlet{
11
12 private static final long serialVersionUID = 1L;
13
14 @Override
15 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
16 String str=this.getInitParameter("abc");
17 System.out.println(str);
18 }
19
20
21 }
注意:注解@Web("/DemoAction")和web.xml中的信息配置不能同时存在,不然会报空指针异常
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> 3 4 <servlet> 5 <servlet-name>DemoAction</servlet-name> 6 <servlet-class>com.uplooking.controller.DemoAction</servlet-class> 7 <init-param> 8 <param-name>abc</param-name> 9 <param-value>123</param-value> 10 </init-param> 11 <load-on-startup>1</load-on-startup> 12 </servlet> 13 14 <servlet-mapping> 15 <servlet-name>DemoAction</servlet-name> 16 <url-pattern>/DemoAction</url-pattern> 17 </servlet-mapping> 18 19 <display-name>180911</display-name> 20 <welcome-file-list> 21 <welcome-file>index.html</welcome-file> 22 <welcome-file>index.htm</welcome-file> 23 <welcome-file>index.jsp</welcome-file> 24 <welcome-file>default.html</welcome-file> 25 <welcome-file>default.htm</welcome-file> 26 <welcome-file>default.jsp</welcome-file> 27 </welcome-file-list> 28 </web-app>
从浏览器键入URL:http://localhost:8081/180911/DemoAction
执行结果:会从web.xml中去读取param-value的值

1 package com.uplooking.controller;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletConfig;
6 import javax.servlet.ServletException;
7 import javax.servlet.http.HttpServlet;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpServletResponse;
10
11 //@WebServlet("/DemoAction")
12 public class DemoAction extends HttpServlet{
13
14 ServletConfig config;
15 private static final long serialVersionUID = 1L;
16
17 @Override
18 public void init(ServletConfig config) throws ServletException { //调用init的含参的函数
19 this.config=config;
20 }
21
22 @Override
23 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
24 //this是指ServletConfig的对象config
25 //String str=this.getInitParameter("abc");
26 //此处this必须改成config,调用全局变量config,this不再指上述的ServletConfig的对象config,否则会报空指针异常
27 String str=config.getInitParameter("abc");
28 System.out.println(str);
29 }
30 }
或者将init()带参函数,使用默认内容,不改变this,也可以执行
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
执行结果和上述一样。(结果:123)
带有无参init方法,自带封装好内容
1 package com.uplooking.controller;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletConfig;
6
7 import javax.servlet.ServletException;
8 import javax.servlet.http.HttpServlet;
9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11
12 //@WebServlet("/DemoAction")
13 public class DemoAction extends HttpServlet{
14
15 ServletConfig config;
16 private static final long serialVersionUID = 1L;
17
18 @Override
19 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
20 //this是指ServletConfig的对象config
21 String str=this.getInitParameter("abc");
22 System.out.println(str);
23 }
24
25 @Override
26 public void init() throws ServletException {
27 // TODO Auto-generated method stub
28 super.init();
29 }
30 }
执行结果一样
1 package com.uplooking.controller;
2
3 import java.io.IOException;
4
5 import java.util.Enumeration;
6
7 import javax.servlet.ServletException;
8 import javax.servlet.http.HttpServlet;
9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11
12 //@WebServlet("/DemoAction")
13 public class DemoAction extends HttpServlet{
14
15 ServletConfig config;
16 private static final long serialVersionUID = 1L;
17
18 @Override
19 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
20 //this是指ServletConfig的对象config
21 String str=this.getInitParameter("abc");
22 System.out.println(str);
23 Enumeration<String> strs=this.getInitParameterNames();
24 while(strs.hasMoreElements()) {
25 str=strs.nextElement();
26 System.out.println(str+" "+this.getInitParameter(str));
27 }
28 }
29
30 @Override
31 public void init() throws ServletException {
32 // TODO Auto-generated method stub
33 super.init();
34 }
35 }
从浏览器键入URL:http://localhost:8081/180911/DemoAction
执行结果:
1 package com.uplooking.controller;
2
3 import java.io.IOException;
4 import java.util.Properties;
5 import javax.servlet.ServletException;
6 import javax.servlet.http.HttpServlet;
7 import javax.servlet.http.HttpServletRequest;
8 import javax.servlet.http.HttpServletResponse;
9
10 public class DemoAction extends HttpServlet{
11 private static final long serialVersionUID = 1L;
12
13 @Override
14 public void init() throws ServletException {
15 super.init();
16 }
17
18 @Override
19 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
20 String str=this.getInitParameter("path");
21 Properties p=new Properties();
22 p.load(this.getClass().getClassLoader().getResourceAsStream(str));
23 String user=p.getProperty("DBUSER");
24 System.out.println(user);
25 }
dbconfig.properties中数据
1 DBDRIVER=com.mysql.jdbc.Driver 2 DBUSER=root 3 DBPWD=12345 4 InitialPoolSize=30
读取DBUSER中的值
从浏览器键入URL:http://localhost:8081/180911/DemoAction
执行结果:

ServletContext对象
10.1 引入
ServletContext对象 ,叫做Servlet的上下文对象。表示一个当前的web应用环境。一个web应用中只有一个ServletContext对象。
10.2 对象创建和得到
创建时机:加载web应用时创建ServletContext对象。
得到对象: 从ServletConfig对象的getServletContext方法得到
我们设计:
创建ServletConfig对象
public void init( ServletConfig config,ServletContext context ){ 多了一个参数
得到ServletConfig对象
得到ServletContext对象;
}
Sun公司设计
1)创建ServletContext对象 ServletContext context = new ServletContext()
2)创建ServletConfig对象 ServetConfig config = new ServletConfig();
config.setServletContxt(context);
class ServletConfig{
ServletContext context;
public ServletContext getServletContxt(){
return contxt;
}
}
public void init( ServletConfig config ){
得到ServletConfig对象
从ServletConfig对象中得到ServletContext对象
SerlvetContext context = config.getServletContext();
}
10.1 ServletContext对象的核心API(作用)
java.lang.String getContextPath() --得到当前web应用的路径
java.lang.String getInitParameter(java.lang.String name) --得到web应用的初始化参数
java.util.Enumeration getInitParameterNames()
void setAttribute(java.lang.String name, java.lang.Object object) --域对象有关的方法
java.lang.Object getAttribute(java.lang.String name)
void removeAttribute(java.lang.String name)
RequestDispatcher getRequestDispatcher(java.lang.String path) --转发(类似于重定向)
java.lang.String getRealPath(java.lang.String path) --得到web应用的资源文件
java.io.InputStream getResourceAsStream(java.lang.String path)
10.3 得到web应用路径
java.lang.String getContextPath() 用在请求重定向的资源名称中
10.4得到web应用的初始化参数(全局)
java.lang.String getInitParameter(java.lang.String name) --得到web应用的初始化参数
java.util.Enumeration getInitParameterNames()
web应用参数可以让当前web应用的所有servlet获取!!!
10.5域对象有关的方法
域对象:作用是用于保存数据,获取数据。可以在不同的动态资源之间共享数据。
案例:
Servlet1 Servlet2
name=eric
response.sendRedirect("/Servlet2?name=eric") String request.getParameter("name");
保存到域对象中 从域对象获取
Student
方案1: 可以通过传递参数的形式,共享数据。局限:只能传递字符串类型。
方案2: 可以使用域对象共享数据,好处:可以共享任何类型的数据!!!!!
ServletContext就是一个域对象!!!!
保存数据:void setAttribute(java.lang.String name, java.lang.Object object)
获取数据: java.lang.Object getAttribute(java.lang.String name)
删除数据: void removeAttribute(java.lang.String name)
ServletContext域对象:作用范围在整个web应用中有效!!!
所有域对象:
HttpServletRequet 域对象
ServletContext域对象
HttpSession 域对象
PageContext域对象
读取web.xml中context中的param-value的值:
1 package com.uplooking.controller;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.util.Properties;
6
7 import javax.servlet.ServletContext;
8 import javax.servlet.ServletException;
9 import javax.servlet.annotation.WebServlet;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13
14 @WebServlet("/DemoAction1")
15 public class DemoAction1 extends HttpServlet{
16
17 private static final long serialVersionUID = 1L;
18
19
20 @Override
21 public void init() throws ServletException {
22 super.init();
23 }
24
25
26 @Override
27 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
28 //this.getSreletConfig().getServletContext();
29 ServletContext context=this.getServletContext();
30 String root=context.getInitParameter("root");
31 System.out.println("root="+root);
32
33 //项目路径
34 String contextPath=context.getContextPath();
35 System.out.println(contextPath);
36
37 //真实路径(绝对路径)
38 String realPath=context.getRealPath("");
39 System.out.println(realPath);
40
41 InputStream in=context.getResourceAsStream("/WEB-INF/classes/dbconfig.properties");
42 Properties p=new Properties();
43 // p.load(this.getClass().getClassLoader().getResourceAsStream(str));
44 p.load(in);
45 String user=p.getProperty("DBUSER");
46 System.out.println(user);
47 }
48 }
web.xml中context的信息配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> 3 4 <context-param> 5 <param-name>root</param-name> 6 <param-value>123</param-value> 7 </context-param> 8 9 <display-name>180911</display-name> 10 <welcome-file-list> 11 <welcome-file>index.html</welcome-file> 12 <welcome-file>index.htm</welcome-file> 13 <welcome-file>index.jsp</welcome-file> 14 <welcome-file>default.html</welcome-file> 15 <welcome-file>default.htm</welcome-file> 16 <welcome-file>default.jsp</welcome-file> 17 </welcome-file-list> 18 </web-app>
从浏览器键入URL:http://localhost:8081/180911/DemoAction1
执行结果:

10.6 转发
RequestDispatcher getRequestDispatcher(java.lang.String path)
1)转发
a)地址栏不会改变
b)转发只能转发到当前web应用内的资源
c)可以在转发过程中,可以把数据保存到request域对象中
2)重定向
a)地址栏会改变,变成重定向到地址。
b)重定向可以跳转到当前web应用,或其他web应用,甚至是外部域名网站。
c)不能再重定向的过程,把数据保存到request中。
结论: 如果要使用request域对象进行数据共享,只能用转发技术!!!
总结:
Servlet编程:
Servlet生命周期(重点)
其他都是应用的东西(敲代码练习)
1、转发
示意图:

1 package com.uplooking.controller;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletException;
6 import javax.servlet.annotation.WebServlet;
7 import javax.servlet.http.HttpServlet;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpServletResponse;
10
11 @WebServlet("/DemoAction2")
12 public class DemoAction2 extends HttpServlet{
13
14 private static final long serialVersionUID = 1L;
15
16 @Override
17 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
18 // this.getServletContext().getRequestDispatcher(path); 等同于下面的语句,直接封装好,简洁
19 // req.getServletContext().getRequestDispatcher(path);
20 //转到另一个资源
21 //转发一次资源 状态200 foward携带的是request和response的数据
22 //携带的必须是本地工程内的资源,若是外地资源,则会报错404
23 req.getRequestDispatcher("index.jsp").forward(req,resp);
24 //req.getRequestDispatcher("www.baidu.com").forward(req,resp);-->外部资源,报错404
25 }
26
27
28 }
index.jsp中
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 天王盖地虎,宝塔镇河妖 11 </body> 12 </html>
从浏览器键入URL:http://localhost:8081/180911/
执行结果:

从浏览器键入URL:http://localhost:8081/180911/DemoAction2
执行结果:

重定向
示意图:

1 package com.uplooking.controller;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletException;
6 import javax.servlet.annotation.WebServlet;
7 import javax.servlet.http.HttpServlet;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpServletResponse;
10
11 @WebServlet("/DemoAction2")
12 public class DemoAction2 extends HttpServlet{
13
14 private static final long serialVersionUID = 1L;
15
16 @Override
17 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
18 //重定向URL(内部资源)
19 //发送状态码
20 //第一种方式:
21 resp.setStatus(302);
22 resp.setHeader("location", "index.jsp");
23 //第二种方式:
24 //resp.sendRedirect("index.jsp");
25 }
26 //可以访问外部资源
27 //resp.sendRedirect("www.baidu.com");
28 }
从浏览器键入URL:http://localhost:8081/180911/DemoAction2
执行结果:
注意form表单提交问题
1、转发的form表单提交问题:
1 package com.uplooking.controller;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletException;
6 import javax.servlet.annotation.WebServlet;
7 import javax.servlet.http.HttpServlet;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpServletResponse;
10
11 @WebServlet("/DemoAction2")
12 public class DemoAction2 extends HttpServlet{
13
14 private static final long serialVersionUID = 1L;
15
16 @Override
17 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
18 //转发 form表单提交问题 此处index.jsp还是/index.jsp都一样
19 req.getRequestDispatcher("index.jsp").forward(req,resp);
20
21 }
22 }
index.jsp中:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 天王盖地虎,宝塔镇河妖 11 <form action="DemoAction2"> //注意:当有多个文件,比如还有user文件时,要调用user中的DemoAction,需要写成“user/DemoAction2”!!! 12 <input type="submit" value="提交1(不带斜杠)"> 13 </form> 14 <br> 15 <form action="/DemoAction2"> //带斜杠会改变文件的路径 16 <input type="submit" value="提交2(带斜杠)"> 17 </form> 18 </body> 19 </html>
从浏览器键入URL:http://localhost:8081/180911/
提交1执行结果:

提交2执行结果:

2、重定向的form表单提交问题:
1 package com.uplooking.controller;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletException;
6 import javax.servlet.annotation.WebServlet;
7 import javax.servlet.http.HttpServlet;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpServletResponse;
10
11 @WebServlet("/DemoAction2")
12 public class DemoAction2 extends HttpServlet{
13
14 private static final long serialVersionUID = 1L;
15 @Override
16 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
17 //重定向 form提交问题 将index.jsp变成/index.jsp
18 resp.sendRedirect("/index.jsp");
19
20 }
21 }
从浏览器键入URL:http://localhost:8081/180911/DemoAction2
执行结果:

四、四大通讯作用域
1.page 只适合当前页面
2.request 一次通讯 重定向时会丢失数据 适合一次通讯 清亮 例如:查询数据
3.session 包时通讯 数据有生命周期 可以自己设定 默认是15分钟 适合重复使用的数据 例如 登陆
4.application 服务器运行 就一直存在 适合一些常量数据
1 package com.uplooking.controller;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletException;
6 import javax.servlet.annotation.WebServlet;
7 import javax.servlet.http.HttpServlet;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpServletResponse;
10
11 @WebServlet("/RequestAction")
12 public class RequestAction extends HttpServlet{
13 private static final long serialVersionUID = 1L;
14 public RequestAction() {
15 super();
16 }
17 @Override
18 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19 //request作用域 一次有效
20 //设置数据
21 request.setAttribute("msg","我是RequestAction作用域");
22
23 //转发 只能通过转发传递出去
24 request.getRequestDispatcher("msg.jsp").forward(request,response);
25
26 }
27 }
msg.jsp文件
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8" isELIgnored="false" %>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>Insert title here</title>
8 </head>
9 <body>
10 <!-- EL表达式 -->
11 <!-- jsp java表达式 -->
12 ${requestScope.msg}
13 </body>
14 </html>
从浏览器键入URL:http://localhost:8081/180911/RequestAction
执行结果:

1 package com.uplooking.controller;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletException;
6 import javax.servlet.annotation.WebServlet;
7 import javax.servlet.http.HttpServlet;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpServletResponse;
10
11 @WebServlet("/RequestAction")
12 public class RequestAction extends HttpServlet{
13 private static final long serialVersionUID = 1L;
14 public RequestAction() {
15 super();
16 }
17 @Override
18 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19 //request作用域 一次有效
20 //设置数据
21 request.setAttribute("msg","我是RequestAction作用域");
22
23 //重定向 会丢失Request作用域的数据
24 response.sendRedirect("msg.jsp");
25 }
26 }
从浏览器键入URL:http://localhost:8081/180911/RequestAction
执行结果:

Session
1、转发
1 package com.uplooking.controller;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletException;
6 import javax.servlet.annotation.WebServlet;
7 import javax.servlet.http.HttpServlet;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpServletResponse;
10 import javax.servlet.http.HttpSession;
11
12 @WebServlet("/SessionAction")
13 public class SessionAction extends HttpServlet {
14 private static final long serialVersionUID = 1L;
15 public SessionAction() {
16 super();
17 }
18 @Override
19 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
20 //session 作用域
21 //包时 在制定时间内有效 消耗比较大 生成在同一个浏览器内有效
22 //获取session
23 HttpSession session=request.getSession();
24 session.setAttribute("msg","我是session作用域");
25
26 //转发
27 request.getRequestDispatcher("msg.jsp").forward(request,response);
28 }
29 }
在web.xml中写入
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8" isELIgnored="false" %>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>Insert title here</title>
8 </head>
9 <body>
10 <!-- EL表达式 -->
11 <!-- jsp java表达式 -->
12 ${sessionScope.msg}、
13 <!-- 前端接收Session的内容 -->
14 </body>
15 </html>
从浏览器键入URL:http://localhost:8081/180911/SessiontAction(信息存在)
执行结果:
从浏览器键入URL:http://localhost:8081/180911/msg.jsp(信息存在)
执行结果:
更换浏览器键入URL:http://localhost:8081/180911/msg.jsp(信息不存在)
执行结果:
更换浏览器键入URL:http://localhost:8081/180911/SessionAction(信息存在)
执行结果:
2、重定向
1 package com.uplooking.controller;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletException;
6 import javax.servlet.annotation.WebServlet;
7 import javax.servlet.http.HttpServlet;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpServletResponse;
10 import javax.servlet.http.HttpSession;
11
12 @WebServlet("/SessionAction")
13 public class SessionAction extends HttpServlet {
14 private static final long serialVersionUID = 1L;
15 public SessionAction() {
16 super();
17 }
18 @Override
19 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
20 //session 作用域
21 //包时 在制定时间内有效 消耗比较大 生成在同一个浏览器内有效
22 //获取session
23 HttpSession session=request.getSession();
24 session.setAttribute("msg","我是session作用域");
25
26 //重定向 不会丢失 可是设置时效
27 response.sendRedirect("msg.jsp");
28 }
29 }
从浏览器键入URL:http://localhost:8081/180911/SessiontAction(信息存在,不会失效)
执行结果:
设置Seeeion时效,应用在登陆7天后,登录信息后失效。
两种方法:
1、在程序中设置时效,优先级最高,单位为秒
1 //设置session时效 优先级最高 以秒为单位 2 session.setMaxInactiveInterval(5);
例如:
1 package com.uplooking.controller;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletException;
6 import javax.servlet.annotation.WebServlet;
7 import javax.servlet.http.HttpServlet;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpServletResponse;
10 import javax.servlet.http.HttpSession;
11
12 @WebServlet("/SessionAction")
13 public class SessionAction extends HttpServlet {
14 private static final long serialVersionUID = 1L;
15 public SessionAction() {
16 super();
17 }
18 @Override
19 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
20 //session 作用域
21 //包时 在制定时间内有效 消耗比较大 生成在同一个浏览器内有效
22 //获取session
23 HttpSession session=request.getSession();
24 session.setAttribute("msg","我是session作用域");
25
26 //设置session时效 优先级最高 以秒为单位
27 session.setMaxInactiveInterval(5);
28
29 //重定向 不会丢失 可是设置时效
30 response.sendRedirect("msg.jsp");
31 }
32
33 }
执行结果:我是session作用域5秒后消失
2、在web.xml中设置时效,优先级第二,单位为分
1 <!-- 设置session时效 单位是分 优先级排第二 程序中设置时效为第一 --> 2 <session-config> 3 <session-timeout>5</session-timeout> 4 </session-config>
注销Session
1 package com.uplooking.controller;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletException;
6 import javax.servlet.annotation.WebServlet;
7 import javax.servlet.http.HttpServlet;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpServletResponse;
10 import javax.servlet.http.HttpSession;
11
12 @WebServlet("/RemoveAction")
13 public class RemoveAction extends HttpServlet {
14 private static final long serialVersionUID = 1L;
15 public RemoveAction() {
16 super();
17 }
18 @Override
19 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
20 //session 作用域
21 //包时 在制定时间内有效 消耗比较大 生成在同一个浏览器内有效
22 //获取session
23 HttpSession session=request.getSession();
24 //第一种移除
25 //session.removeAttribute("msg");
26 //第二种移除 使无效
27 session.invalidate();
28 request.getRequestDispatcher("msg.jsp").forward(request,response);
29 }
30 }
msg.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8" isELIgnored="false" %>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>Insert title here</title>
8 </head>
9 <body>
10 <!-- EL表达式 -->
11 <!-- jsp java表达式 -->
12 ${sessionScope.msg}<a href="RemoveAction" >退出</a>
13 </body>
14 </html>
从浏览器键入URL:http://localhost:8081/180911/SessiontAction
执行结果:
点击退出:
从浏览器键入URL:http://localhost:8081/180911/msg.jsp(信息不存在)
执行结果:
Application
1 package com.uplooking.controller;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletContext;
6 import javax.servlet.ServletException;
7 import javax.servlet.annotation.WebServlet;
8 import javax.servlet.http.HttpServlet;
9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11
12
13 @WebServlet("/ApplicationAction")
14 public class ApplicationAction extends HttpServlet {
15 private static final long serialVersionUID = 1L;
16 public ApplicationAction() {
17 super();
18 }
19 @Override
20 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
21 //application 作用域 消耗特别大 与服务器共生死
22 //获取application 作用域
23 ServletContext context=request.getServletContext();
24 context.setAttribute("user","老王");
25 request.getRequestDispatcher("msg.jsp").forward(request,response);
26 }
27 }
web.xml中
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8" isELIgnored="false" %>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>Insert title here</title>
8 </head>
9 <body>
10 <!-- EL表达式 -->
11 <!-- jsp java表达式 -->
12 ${user}
13 </body>
14 </html>
从浏览器键入URL:http://localhost:8081/180911/ApplicationAction
执行结果:
从浏览器键入URL:http://localhost:8081/180911/msg.jsp
执行结果:
更换浏览器,从浏览器键入URL:http://localhost:8081/180911/msg.jsp(信息依然存在)
执行结果:

浙公网安备 33010602011771号