您的位置:首页 > 其它

2017.7.06 学习笔记 Servlet-----Session作用域

2017-07-07 00:39 375 查看


JSP

在javaweb编程中,可以在四个不同大小的可访问范围(时间、空间)中设置属性对象。即将一个对象绑定到一个字符串上。


JavaWeb中四大域对象的作用范围

ServletRequest :

作用范围是整个一次请求链(包括将此请求转发到的其它页面),也即从客户端发来一次请求开始,到本次服务端响应结束。

对应内置对象是request,EL中可用requestScope取得此对象。

设置该范围属性的写法是:request.setAttribute(string, Object)。

我们一会将会和session一起举例对比

Session : 
作用范围是一次会话。
对应内置对象是session,EL中可用sessionScope取得此对象。
设置该范围属性的写法是:session.setAttribute(string, Object)

注意:浏览器发送一次请求到服务器,服务器首先判断,该请求是否携带一个SessionID值 

如果这次请求没有携带一个SessionID值,服务器就知道了,这是第一次来访问该服务器 

浏览器与该服务器开始建立会话 

服务器会在相应请求的同时,将产生一个SessionID,作为该次会话的标识 

再把这个SessionID发给浏览器,浏览器就拥有一个SessionID了 

当再次访问该服务器时,浏览器会携带那个SessionID,被传到服务器 

服务器首先判断该请求是否携带一个SessionID值,此时有了,代表这不是一个新的会话的请求 

如果浏览器两个请求之间的时间太长,超出服务器等待的时间,服务器会删除这个session对象 

删除后,再次发送到该服务器,因为服务器里没有这个session对象了,就不能判断请求是否携带SessionID值 

也就是说判断不出来,就认为这是一个新的会话开始,又会产生一个SessionID,作为这次新会话的标识 

又把这个SessionID发给浏览器,浏览器就拥有一个新的SessionID了 

在会话开始时,服务器会自动分配一个空间(session对象),SessionID就在session对象里


Session的关闭

如果要立即销毁整个session可以调用invalidate(),其中各对象也全部清除。
session到最大等待时间后,session无效。
关闭浏览器后,session无效。
关闭服务器的后,session无效。

A . 只要浏览器和服务器没有配对的sessionId就表示session无效。

B . 有的服务器可以做到启动后恢复之前的session。即服务器正常关闭,再启动,Session对象会进行钝化和活化操作。同时如果服务器钝化的时间在session 默认销毁时间之内,则活化后session中的一些对象还是存在的,否则认为已经被释放了。

SessionServlet.Java:
/*这个是SessionServlet类*/
package com.yy.servlet.web.Session;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.junit.Test;

public class SessionServlet extends HttpServlet{

private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
/*接受页面提交来的数据*/
String username=request.getParameter("username");
String userpwd=request.getParameter("userpwd");
/*通过request请求把参数存起来*/
request.setAttribute("username", username);
request.setAttribute("userpwd", userpwd);
/*通过request获得session把请求把参数存起来*/
HttpSession session = request.getSession();
System.out.println(session.getId());
session.setAttribute("session_username", username);
session.setAttribute("session_userpwd", userpwd);
/*转发去其他页面顺便把请求参数带过去*/
request.getRequestDispatcher("/session/session.jsp").forward(request, response);
return;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

这个是login_test.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>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script>
var password=0;
function  showName(){ /*判断用户输入的名字是否为空*/

var name=document.getElementById("name").value;
//name=trim(name);
if(name==""){

document.getElementById("nameFont").innerHTML="<img src ='image/wrong.jpg' style='margin-top:0px;'/><div style='color:red;margin-top:-19px;font-size:10px;margin-left:30px;'>你输入的名字为空</div>";
}else{
document.getElementById("nameFont").innerHTML="<img src ='image/right.jpg'/>";
}
}

function  showPwd(){ /*判断用户输入的密码是否为空*/

var pwd=document.getElementById("pwd").value;
//name=trim(name);
if(pwd==""){

document.getElementById("pwdFont").innerHTML="<img src ='image/wrong.jpg' style='margin-top:0px;'/><div style='color:red;margin-top:-19px;font-size:10px;margin-left:30px;'>你输入的密码为空</div>";
}else if(pwd.lenght>8&&pwd.lenght<16){
document.getElementById("pwdFont").innerHTML="<img src ='image/wrong.jpg' style='margin-top:0px;'/><div style='color:red;margin-top:-19px;font-size:10px;margin-left:30px;'>密码需要在8-16位</div>";
}else{
document.getElementById("pwdFont").innerHTML="<img src ='image/right.jpg'/>";

}
}

</script>
</head>

<body>

<center>
<h1 style ="color:red;font-size:60px">用户登录</h1>
</center>
<hr></hr>
<form action="session" method="get">
<table cellpadding="5">
<tr>
<td><span>NAME:</span></td>
<td ><input style="width:200px" type="text" value="youe name" name="username" id="name" onfocus="showName()"  onblur="showName()"/></td>
<td id="nameFont"></td>
</tr>

<td><span>PWD:</span></td>
<td><input style="width:200px" type="password" value="888"  name="userpwd" id="pwd" onfocus="showPwd()"  onblur="showPwd()"/></td>
<td id="pwdFont"></td>
</tr>
<tr>
<td>
<input type="submit" value="登录" />
</td>
<td>
</td>
</tr>

</table>
<hr></hr>
</form>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

web.xml
<servlet>
<servlet-name>SessionServlet</servlet-name>
<servlet-class>com.yy.servlet.web.Session.SessionServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SessionServlet</servlet-name>
<url-pattern>/session</url-pattern>
</servlet-mapping>
1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
7
8
9

session.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>My JSP 'session.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
<h1>repuset作用域测试:</h1>
<span>1:姓名:<%=request.getAttribute("username") %></span>  <span>密码:<%=request.getAttribute("userpwd") %></span>
<br/>
<span>2:姓名:${username}</span>  <span>密码:${userpwd}</span>
<hr/>
<h1>Session作用域测试:</h1>
<span>1:姓名:<%=session.getAttribute("session_username") %></span>  <span>密码:<%=session.getAttribute("session_userpwd") %></span>
<br/>
<span>2:姓名:${session_username}</span>  <span>密码:${session_userpwd}</span>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

运行结果(服务器上运行):

login_test.jsp —>SessionServlet —>session.jsp , 效果图



现在我们比较下request和 session的作用域: 

我们现在直接单独访问session.jsp(http://localhost/ServletForWord/session)

运行结果: 



现在我们发现request作用域已经不存在了

ServletContext 
作用范围是整个Web应用。
当Web应用被加载进容器时就会创建代表整个web应用的ServletContext对象,当服务器关闭或Web应用被移除时,ServletContext对象跟着销毁。
设置该范围属性的写法是:application.setAttribute(string, Object)。
对应内置对象是application,EL中可用applicationScope取得此对象。

/*web.xml配置*/
<context-param>
<param-name>jdbcDriver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
1
2
3
4
5
1
2
3
4
5
/*FirstServlet类*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*获取ServletContext对象*/
ServletContext application=this.getServletContext();
System.out.println(application.getInitParameter("jdbcDriver"));
/*再存在ServletContext对象里面*/
application.setAttribute("jdbc", application.getInitParameter("jdbcDriver"));

}
1
2
3
4
5
6
7
8
9
10
11
1
2
3
4
5
6
7
8
9
10
11
/*ScecondServlet类*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*获取ServletContext对象*/
ServletContext application=this.getServletContext();
System.out.println(application.getInitParameter("jdbcDriver"));
/*再从ServletContext对象里面取出来*/
System.out.println(application.getAttribute("jdbc"));
}
1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
7
8
9

运行结果:console 都 打印出了 value”com.MySQL.jdbc.Driver” 

所以说:ServletContext作用范围是整个Web应用

PageContext 
作用范围是该JSP页面本身,是最小的一个作用范围。
对应内置对象是pageContext,EL中可用pageScope取得此对象。
设置该范围属性的写法是:pageContext.setAttribute(string, Object)。

总结:作用范围从小到大依次为:PageContext,ServletRequest,Session,ServletContext。


Filter

filter翻译为过滤器。在web项目中,经常需要在正式处理请求前,做一些特殊的处理或常用的例程,于是就发明了这个filter。


作用:

过滤非法文字和信息。
设置统一字符编码。
对用户进行登录验证 。
改变图片文件格式。
对相应内容做压缩处理。
对XML的输出使用XSLT来进行转换。


步骤:

第一步:通过在web.xml中的元素和元素来配置filter,以决定用户请求的URL应被哪些filter类来处理一次。
<!--web.xml配置过滤器-->
<filter>
<filter-name>FirstFilter</filter-name>
<!--配置FirstFilter过滤器类-->
<filter-class>com.yy.servlet.web.filter.FirstFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>FirstFilter</filter-name>
<!--(代表整个web项目都要过滤,如果指定某个url就只过滤这个url)-->
<url-pattern>/*</url-pattern>
</filter-mapping>
1
2
3
4
5
6
7
8
9
10
11
1
2
3
4
5
6
7
8
9
10
11
步骤二:编写filter的Servlet类。 
我们的filter类需要实现父接口javax.servlet.Filter。
实现父接口的各个方法。包括init(),doFilter(),destroy(),这3个方法。 
init()方法和destroy()方法分别用来初始化和销毁时调用。
init()方法在 Filter 生命周期中仅执行一次。服务器启动时就会执行。
destory()方法在Filter的生命周期中仅执行一次,即Web容器卸载Filter对象之前调用它。主要做释放资源的操作。

对doFilter(req,resp,chain)方法操作。
chain.doFilter(request,response)。

注意:chain参数则通过调用自己的doFilter方法来将请求向下传递,如果没有调用doFilter()方法,则相当于阻止了本次请求。 

创建如下:

/*这个是FirstFilter过滤器类*/
package com.yy.servlet.web.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class FirstFilter implements javax.servlet.Filter{

public void destroy() {
// TODO Auto-generated method stub

}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filter) throws IOException, ServletException {
/*如果没有调用doFilter()方法,则相当于阻止了本次请求。*/
filter.doFilter(request, response);

System.out.println("filter is ok");
}

public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

这个样子我们就可以过滤web项目的所有url了!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐