Cookie笔记 下载本文

内容发布更新时间 : 2024/12/25 13:03:20星期一 下面是文章的全部内容请认真阅读。

* context域对象:不合适,可能会覆盖数据。

* request域对象: 不合适,整个网站必须得使用转发技术来跳转页面 * session域对象:合适。 */

//request.setAttribute(\

//request.getRequestDispatcher(\response);

//response.sendRedirect(request.getContextPath()+\ /**

* 一、登录成功后,把用户数据保存session对象中 */

//1.创建session对象

HttpSession session = request.getSession(); //2.把数据保存到session域中

session.setAttribute(\, userName); //3.跳转到用户主页

response.sendRedirect(request.getContextPath()+\); }else{

//登录失败 //请求重定向

response.sendRedirect(request.getContextPath()+\); } }

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

2>主页面:

public class IndexServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType(\); PrintWriter writer = response.getWriter();

String html = \; /**

* 接收request域对象的数据

*/

//String loginName = (String)request.getAttribute(\ /**

* 二、在用户主页,判断session不为空且存在指定的属性才视为登录成功!才能访问资源。

* 从session域中获取会话数据 */

//1.得到session对象

HttpSession session = request.getSession(false); if(session==null){

//没有登录成功,跳转到登录页面

response.sendRedirect(request.getContextPath()+\); return; }

//2.取出会话数据

String loginName = (String)session.getAttribute(\); if(loginName==null){

//没有登录成功,跳转到登录页面

response.sendRedirect(request.getContextPath()+\); return; }

html = \欢迎回来,\+loginName+\,

href='\+request.getContextPath()+\安全退出\;

writer.write(html); }

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

3>退出:

public class LogoutServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /**

* 三、安全退出: * 删除掉session对象中指定的loginName属性即可! */

}

}

//1.得到session对象

HttpSession session = request.getSession(false); if(session!=null){ //2.删除属性

session.removeAttribute(\); }

//2.回来登录页面

response.sendRedirect(request.getContextPath()+\);

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }