兄弟姊妹章节
- 页外目录链接
-------------------------------<request篇>-------------------------------
本章学习目录
一,在类中将对象存到session作用域
HttpSession session=request.getSession();
session.setAttribute("user",user);
二,在jsp文件下通过session得到该对象
<%
//从session中获取user属性的值
User user = (User) session.getAttribute("user");
if (user == null) {
%>
//得到user中的属性
<%=user.getUser_name()%>
三,该方法在登陆方法下的体现(service dao层的代码在章节的展示篇传送门:数据的展示篇)
package com.jazhong.servlet;
import com.jazhong.service.UserService;
import com.jazhong.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String user_name=request.getParameter("user_name");
String user_password=request.getParameter("user_password");
UserService userService=new UserServiceImpl();
if (userService.login(user_name,user_password)==true){
HttpSession session=request.getSession();
session.setAttribute("User_name",user_name);
response.sendRedirect("/index.jsp");
}else {
response.sendRedirect("/register.jsp");
}
}
}
四,将该方法体现在主页中
<%@ page import="com.jazhong.model.User" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<%
//从session中获取user属性的值
User user = (User) session.getAttribute("user");
if (user == null) {
%>
<a href="login.jsp">登录</a>
<a href="register.jsp">注册</a>
<%
} else {
%>
欢迎您:<%=user.getUser_name()%>
<a href="exit.do">退出</a>
<a href="querygoods.do">商品列表</a>
<%
}
%>
</body>
</html>
五,考虑到向session中加入了元素所以要删除
package com.jazhong.servlets;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/exit.do")
public class ExitServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().removeAttribute("user");
response.sendRedirect("index.jsp");
}
}
六,将该方法在浏览器上展示:
- index.jsp的浏览器页面:(尚未登录所以index.jsp显示需要登录或者注册)
- 登陆界面:
- 输入账户和密码,yyx ,admin 得到(由于在index页面进行了判断,已经登陆,所以显示可以退出)
)
- 点击退出