拦截器Filter
作者:互联网
package com.xxx.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 拦截非法访问index.jsp
*/
@WebFilter("/*")
public class fil2 implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//未登录跳入登录界面
HttpServletRequest req=(HttpServletRequest)servletRequest;
HttpServletResponse resp=(HttpServletResponse) servletResponse;
//获取请求路径
String url= req.getRequestURI();
System.out.println(url);
//放行登录界面(包括各种静态资源以及各种操作)
if(url.contains("/login.jsp")){
filterChain.doFilter(servletRequest,servletResponse);
return;
}
if(url.contains("/js")||url.contains("/image")){
filterChain.doFilter(servletRequest,servletResponse);
return;
}
if(url.contains("/loginServlet")){
filterChain.doFilter(servletRequest,servletResponse);
return;
}
//已经登录状态
String uname=(String) req.getSession().getAttribute("uname");
if(uname!=null){
filterChain.doFilter(servletRequest,servletResponse);
return;
}
resp.sendRedirect("login.jsp");
}
@Override
public void destroy() {
}
}
package com.xxx.servlet;
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("/loginServlet")
public class Login extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if(true){
req.getSession().setAttribute("uname","uname");
resp.sendRedirect("index.jsp");
}else{
req.getRequestDispatcher("login.jsp").forward(req,resp);
}
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="loginServlet" method="post">
uname:<input name="uname"><br>
<button>submit</button>
</form>
</body>
</html>
标签:拦截器,servletResponse,req,Filter,uname,import,servlet,javax 来源: https://www.cnblogs.com/lwx11111/p/16205148.html