权限过滤器
程序员文章站
2024-01-21 14:33:22
...
场景
项目运行过程中,希望某些资源不能被用户直接访问到,只有登录后才可以访问。
解决方案
创建一个自定义过滤器,在过滤器中为这些资源分别配置好路径,在过滤器中判断用户是否登录,登录成功,放行,没有登录,返回提示信息。
过滤器代码
package com.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import com.domain.User;
public class PriviledgeFilter implements Filter {
public PriviledgeFilter() {
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest myReq = (HttpServletRequest) request;
// 判断当前的session中是否存在已经登录成功的用户
User user = (User) myReq.getSession().getAttribute("user");
if (null != user) {
// 如果存在,放行
chain.doFilter(request, response);
} else {
// 如果不存在,转入到提示页面
myReq.setAttribute("msg", "请用户登录之后再去访问");
// 转入到提示页面
myReq.getRequestDispatcher("/jsp/info.jsp").forward(request, response);
}
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
web.xml配置
<filter>
<display-name>PriviledgeFilter</display-name>
<filter-name>PriviledgeFilter</filter-name>
<filter-class>com.filter.PriviledgeFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PriviledgeFilter</filter-name>
<url-pattern>/jsp/index.jsp</url-pattern>
<url-pattern>/jsp/...jsp</url-pattern>
<url-pattern>/jsp/...jsp</url-pattern>
<url-pattern>/jsp/...jsp</url-pattern>
<url-pattern>/jsp/...jsp</url-pattern>
</filter-mapping>
备注:<url-pattern>/jsp/...jsp</url-pattern>
选择自己要设置的权限页面
上一篇: 暴雪首席战斗设计师回顾副本的设计构思
下一篇: java反射学习