目录
在user里面 装session
1、 LoginServlet.java
2、LoginFilter.java
3、配置路径
结果:
在user里面 装session
1、 LoginServlet.java
package com.by.servlet;
import com.by.pojo.User;
import com.by.service.UserService;
import com.by.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* 注意:
* 1、一次只写一层
* 2、复杂的代码先写注释,后写代码
* web层: 接受请求 控制跳转, 并调用service层
*/
public class LoginServlet extends HttpServlet {
private UserService userService = new UserServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try{
String username = req.getParameter("username");
String password = req.getParameter("password");
User user = userService.login(username,password);
//控制页面的跳转
if(user != null){ //登录成功
//在user里面 装session : session 可以设置失效时间--浏览器进行关闭
HttpSession session = req.getSession();
session.setAttribute("user",user);
session.setMaxInactiveInterval(60*30); //30分钟
//利用重定向
//重定向到selectServlet,在selectServlet查询数据,并把数据传递到main.jsp
resp.sendRedirect("selectUser");
// resp.sendRedirect("deleteUser");
}else{
resp.sendRedirect("login.jsp"); //登录失败 去登录页面
}
}catch (Exception e){
e.printStackTrace();
}
}
}
2、LoginFilter.java
package com.by.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//直接放行: “login.jsp”和“/”
String uri = request.getRequestURI();
if(uri.contains("login") || uri.endsWith("/")){
System.out.println("uri:"+uri+"中包含login或以/结尾 --> 直接放行");
//放行
chain.doFilter(req,resp);
//结束
return;
}
//1、从session获取user
Object user = request.getSession().getAttribute("user");
//2、获取到user,则放行
if(user != null){
System.out.println("用户已登录 --> 直接放行");
//放行
chain.doFilter(req,resp);
//结束
return;
}else{
System.out.println("用户未登录 --> 重定向到 login.jsp");
//3、没有获取到user,则重定向到login.jsp
response.sendRedirect("login.jsp");
}
}
@Override
public void destroy() {
}
}