一、application作用域
application作用域中存储的数据所有的客户端是共享的。
当项目从服务器移走,或者服务关闭后重新启动,application才失效。
application实现计数器
实现的jsp代码
java"><%
Object str = application.getAttribute("count");
if(str==null){
//当第一个人访问时,将初始值为1
application.setAttribute("count", 1);
}else{
//当不是第一个人时,先将类型转换,再加一
Integer i = (Integer)str;
application.setAttribute("count", i+1);
}
%>
<p>当前访问的人数为:<%=application.getAttribute("count") %>人</p>
session_41">二、session作用域
session意思是会话,客户端和服务器端建立的一次会话。
打开浏览器,在地址栏输入url地址访问服务器的时候,会话创建成功了。即在服务器端存储也在客户端存储。
存储的内容是:sessionid。
客户端存储一份,服务器端存一份
sessionid的获取主要是通过cookie,浏览器允许cookie服务器就会在客户端写入。
-
对于cookie禁用时
session.setAttribute("username", name); String address = request.getContextPath()+"需要跳转的url"; String url = response.encodeURL(address); response.sendRedirect(url);
1 获取新的访问路径: request.getContextPath()
2 通过: response.encodeURL() 生成新的jsessionid
sessioncookie_70">session实现cookie禁用登录
需要三个jsp文件 login,dologin,welcome;
login
java"><%@ 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 address = request.getContextPath()+"/dologin.jsp";
//带jsessionid的url
String url = response.encodeURL(address);
%>
<form action="<%=url %>" method="post">
<table>
<tr>
<td>用户名:<input type="text" name="username"/></td>
</tr>
<tr>
<td> 密码:<input type="password" name="pwd"/></td>
</tr>
<tr>
<td >
<input type="submit" name="login" value="登录"/>
<input type="button" name="exit" value="退出"/>
</td>
</tr>
</table>
</form>
</body>
</html>
dologin
java"><%@page import="com.openlab.dao.UserDao"%>
<%@page import="com.openlab.bean.User"%>
<%@page import="com.openlab.dao.imp.UserDaoImp"%>
<%@ 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>
<%
//1 设置格式
response.setCharacterEncoding("UTF-8");
//2 获得参数
String name = request.getParameter("username");
String pwd = request.getParameter("pwd");
//UserDao是数据库与用户登录之间的接口,实现类在UserDaoImp中
UserDao ud = new UserDaoImp();
//组件user对象 ,testName是校验数据库中的用户信息
User user = ud.testName(name);
//3 判断是否为空
if(user!=null){
//用户名正确
if(pwd.equals(user.getPwd())){
//密码正确
//登录成功后
session.setAttribute("username", name);
String address = request.getContextPath()+"/welcome.jsp";
String url = response.encodeURL(address);
response.sendRedirect(url);
}else{
//密码不正确
response.sendRedirect("login.jsp");
}
}else{
//用户名为错误
response.sendRedirect("login.jsp");
}
%>
</body>
</html>
welcome
java"><%@ 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>
<% int i=0;
Object name = session.getAttribute("username");
//防止不登录,直接进入欢迎页面
if(name==null){
response.sendRedirect("login.jsp");
}
%>
<p>欢迎您:<%=name%></p>
</body>
</html>