最近学习了cookie,session,application的用法,发现网上关于这三者的介绍和区别都很详细,但是却没有简单易懂的例子来直观的表示,特写下这篇博客,希望能使需要学习这方面知识的读者更容易理解。
首先先创建一个登录表单(userLogin.jsp):
其次创建表单提交给的页面(userLoginSuccess.jsp):
- 表单效果:
利用session保存用户名并跳转至index.jsp页面中,在该页面中显示用户名
- 此处要修改userLoginSuccess.jsp中的代码,如图:
上面代码中response将我们的请求重新定位到index.jsp上,改变URL的地址,实现了跳转
- index.jsp代码::
<body>
<%
Object o = session.getAttribute("user");
if(o == null){
%>
<%}else{
out.println("欢迎" + o.toString()+"登录成功");
}
%> <a href = "userLoginout.jsp">注销</a><!-- 此处跳转实现清除session数据 -->
</body>
上面index.jsp中最后有个超链接,此超链接的作用注释已写了,若没有清除session的操作可能会导致性能问题或服务器崩溃
- userLoginout.jsp代码::
<body>
<%
session.removeAttribute("username");
session.invalidate();
response.sendRedirect("index.jsp");
%>
</body>
利用cookie保存用户名,当我们注销且关闭浏览器后下次登录实现用户名已填
- 首先在userLogin.jsp中加入如下代码:
<%
String username="";
Cookie[] cookies = request.getCookies();//利用request获取cookie的值
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie.getName().equals("user")) {
username=cookie.getValue();//如果和预设值相同,则将cookie值赋值给username
}
}
}
%>
- 修改userLoginSuccess.jsp中代码:
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
if((username.equals("系统管理员")&&password.equals("123"))){//只有是系统管理员才增加cookie
Cookie cookie = new Cookie("user",username);
cookie.setMaxAge(60*60);//设置cookie的生存周期
response.addCookie(cookie);
session.setAttribute("user", username);
response.sendRedirect("index.jsp");
}else{
request.setAttribute("mess", "登录失败,用户名或密码输入不正确!");
request.getRequestDispatcher("userLogin.jsp").forward(request, response);
}
%>
</body>
重新打开浏览器登录后的效果:
application中存储的数据在整个web项目中都可以使用,所以通常用来计数,比如一个网页被浏览的次数就是用application来实现
- 在userLogin.jsp中增加如下代码,实现知道你是第几个注册的人:
<%
Object count = application.getAttribute("count");
if(count==null){
application.setAttribute("count", new Integer(1));
}else{
application.setAttribute("count", (Integer)application.getAttribute("count")+1);
}
count = application.getAttribute("count");
out.println("你是第"+count+"个注册的人");
%>
效果如下:
总结:上面的例子可以比较简单的概括,session可以实现在多个页面中显示用户信息,cookie可以实现自动填写用户名(当然可以自动填写密码,但是公共场合下或大部分情况下较隐私的信息不建议用cookie保存)application则可以实现统计页面的访问次数,这个访问可以是不同的浏览器。希望对大家有点帮助~