private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//判断用户是否登录,从session中获取用户登录标识user,若不为null表示已经登录,否则未登录
request.setCharacterEncoding("UTF-8");
//获取session对象
HttpSession session=request.getSession();
String name=(String)session.getAttribute("user");
if(null!=name){
//已登录
System.out.println("已经登录,登录用户:"+name+",可以访问!");
}else {
//未登录
System.out.println("用户还未登录,禁止访问!");
}
}
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置请求字符集
request.setCharacterEncoding("UTF-8");
String name=request.getParameter("loginName");
String pwd=request.getParameter("loginPwd");
//验证用户有效性
if("admin".equals(name)&&"123".equals(pwd)||"张三".equals(name)&&"666".equals(pwd)){
//登录成功
//在session中存储用户登录的标识
HttpSession session=request.getSession();
session.setAttribute("user", name);
//转发index页面
request.getRequestDispatcher("index.html").forward(request, response);
}else {
//登录失败
//转发login页面
request.getRequestDispatcher("login.html").forward(request, response);
}
}
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取session对象,并将session销毁
HttpSession session=request.getSession();
session.invalidate();
System.out.println("已经注销用户!");
response.sendRedirect("index.html");
}
session会话
最新推荐文章于 2020-08-12 08:42:16 发布