您的位置:首页 > 其它

玩转web之servlet(六)---session介绍及简单使用(登录验证中保存信息)

2014-04-29 17:01 796 查看
在浏览器与服务器进行交互时,往往需要把涉及到的一些数据保存下来,这时就需要使用cookie或session进行状态管理。

这篇文章先来说说session怎么用,首先在servlet中创建一个session来保存信息,举个例子,在做登陆验证时,如果登陆成功,需要将用户的信息保存到session中,怎么保存呢?下面给出代码:

public class Login_Do extends HttpServlet {
String order_name = "";
String order_password = "";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
order_name= new String(request.getParameter("name").getBytes("ISO-8859-1"),"utf-8") ;
order_password = request.getParameter("password");
PrintWriter out = response.getWriter();
JSONObject json = new JSONObject();
String msg = "";
try {
json.put("msg",login());
out.print(json.toString());
HttpSession session = request.getSession();
session.setAttribute("user_name", login());

} catch (SQLException e) {
e.printStackTrace();
}
}
public String login() throws SQLException{
Order_User_Dao u = new Order_User_Dao();
Order_User user = new Order_User();
user = u.login(order_name,order_password);
if(!"".equals(user.getUser_name())){
return user.getUser_name();  //如果登陆成功,会返回用户的用户名
}
else
return null;
}
}


关于session的创建是那两行红色字体,将用户名绑定到了session对象上,那怎么使用呢?

HttpSession session = request.getSession();
String user_name = String.valueOf(session.getAttribute("user_name"));


使用这个方法,无论是在servlet中,还是前台脚本段里,都可以轻松的获取所需要的信息。

再来说说怎么清楚session,当浏览器关闭时,我们需要清除掉session,一个是考虑到安全性,一个是要确保你退出后其他用户可以登录,这就用到session的invalidate方法了。

在jsp中,当退出时写上

<%
session.invalidate();
%>


就会清除掉绑定在session上的信息。

关于session的优缺点:

优点:1:session会将所有状态写在服务器端,所以相对于cookie比较安全,一般用来保存登录用户的信息或其他重

要信息

2:session可以保存的数据类型比较丰富,而cooike只能保存字符串

3:session保存的数据大小更大,而cooike只能保存大约4k的信息,理论上session是没限制的

缺点:由于将信息保存到服务器端,对系统资源占用比较大。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: