用Filter实现用户登录权限控制。(15分) 要求: (1)编写正确的Java代码,包名com.qst.filter,类名LoginFilter (2)使用session 进行用户数据的存储。 (3)编写正确的过滤器,如果登录放行否则调转到登录页面。
时间: 2024-02-19 13:57:56 浏览: 32
下面是实现用户登录权限控制的Java代码:
```java
package com.qst.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(filterName = "LoginFilter", urlPatterns = {"/admin/*"})
public class LoginFilter implements Filter {
public void init(FilterConfig config) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
HttpSession session = request.getSession();
String uri = request.getRequestURI();
if (uri.contains("/login") || uri.contains("/register") || uri.contains("/css/") || uri.contains("/js/") || uri.contains("/images/")) {
chain.doFilter(request, response);
} else if (session.getAttribute("username") != null) {
chain.doFilter(request, response);
} else {
response.sendRedirect(request.getContextPath() + "/login.jsp");
}
}
public void destroy() {
}
}
```
该代码中,我们通过`@WebFilter`注解将`LoginFilter`过滤器与所有以`/admin/`开头的URL进行了关联。在`doFilter`方法中,我们首先获取了`HttpServletRequest`对象、`HttpServletResponse`对象和`HttpSession`对象,然后判断请求的URL是否是登录、注册、CSS、JS、图片资源等无需登录权限的URL,如果是,则直接放行;如果不是,则判断当前用户是否已经登录,如果已经登录,则放行;如果未登录,则重定向到登录页面。最后,我们需要将`LoginFilter`过滤器注册到Web应用程序中,可以在`web.xml`文件中进行配置,也可以使用注解方式进行配置。
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)