public class UserSessionFilter implements Filter {
protected FilterConfig filterConfig;
private String redirectPage;
public void init(FilterConfig config) {
filterConfig = config;
redirectPage = config.getInitParameter(
Constants.REDIRECT);
}
public void destroy() {
filterConfig = null;
}
private boolean check(ServletRequest request, ServletResponse response) throws
IOException, ServletException {
boolean result = false;
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession(false);
if (session != null) {
Object object = session.getAttribute(Constants.USER_KEY);
if (object != null) {
result = true;
}
}
if (redirectPage.equals(req.getServletPath())) {
result = true;
}
return result;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException,
ServletException {
if (check(request, response)) {
chain.doFilter(request, response);
} else {
HttpServletResponse res = (HttpServletResponse) response;
res.sendRedirect(redirectPage);
}
}
}
web.xml
web.xml<filter>
<filter-name>User Session Filter</filter-name>
<filter-class>com.realcampaign.manager.filters.UserSessionFilter</filter-class>
<init-param>
<param-name>redirect</param-name>
<param-value>/login.vm</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>User Session Filter</filter-name>
<url-pattern>*.vm</url-pattern>
</filter-mapping>

博客给出了UserSessionFilter类的代码,该类实现了Filter接口。包含init、destroy、check和doFilter等方法,用于检查用户会话,若会话中用户对象不为空或请求路径为指定重定向页则放行,否则重定向到指定页面,还提及了web.xml。
644

被折叠的 条评论
为什么被折叠?



