只能访问login.jsp和"/login"注解,实现登录过滤效果
过滤类
//注解过滤器,括号里面写拦截的文件名
@WebFilter("/*")//拦截所有文件
public class Filter02 implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//相对特定的资源放行
//对servletRequest强转
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
//拿到当前请求的URL
String requestURI = request.getRequestURI();
//contains是包含的意思,例,requestURI.contains("/login"):有login,loginWork..都能被访问
//建议使用equals
if (requestURI.equals("/login.jsp")||requestURI.equals("/login")){
//对这两个进行放行
filterChain.doFilter(servletRequest,servletResponse);
}else {
//判断它是否登录过(获取登录成功时,存储的Session值)
Object isLogin = request.getSession().getAttribute("isLogin");
//判断有值就放行
if (isLogin!=null){
//如果设置的域对象不为空,说明他已经登录过
filterChain.doFilter(servletRequest,servletResponse);
}else {
//如果没有登录,重定向到login.jsp
response.sendRedirect("/login.jsp");
}
}
}
@Override
public void destroy() {
}
}
登录类
@WebServlet("/login")
public class Login extends HttpServlet {
private Cookie[] cookies;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//处理前端传来的数就编译成utf-8格式
request.setCharacterEncoding("utf-8");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取前端数据
String username = request.getParameter("username");
String password = request.getParameter("password");
if ("lisi".equals(username) && "123456".equals(password)) {
//使用Session存值放到前端
HttpSession session = request.getSession();
session.setAttribute("isLogin","hello");
//使用重定向
response.sendRedirect("/index.jsp");
}else {
//使用Session存值放到前端
request.getSession().setAttribute("msg","密码或账户错误!");
//登录失败返回原来页面
response.sendRedirect("/login.jsp");
//request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
}
login.jsp类
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<style type="text/css">
input{
margin: 10px 10px;
}
div{
width: 500px;
margin: 50px auto;
}
p{
font-size: 30px;
font-weight: bold;
color: red;
}
#d1{
margin: 0 auto;
}
</style>
<script type=""></script>
</head>
<body>
<div>
<div id="d1"><p>登 录 界 面</p></div>
<form action="/login" method="get">
账号:<input name="username" type="text"/><br>
密码:<input name="password" type="text"/><br>
<input type="submit" value="提交"/>
</form>
<p><%--获取后端数据--%></p>
</div>
</body>
</html>