我正在使用Spring Mvc 3.x版本。我不想在每个页面上写一个if检查。相反,我需要Spring内部支持的代码
答案 0 :(得分:0)
过滤器最适合此类用例。您可以拦截每个请求并检查是否存在活动会话
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class AuthenticationFilter implements Filter {
private ServletContext context;
public void init(FilterConfig fConfig) throws ServletException {
this.context = fConfig.getServletContext();
this.context.log("AuthenticationFilter initialized");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession session = req.getSession(false);
if (session == null) { //checking whether the session exists
this.context.log("Unauthorized access request");
res.sendRedirect(req.getContextPath() + "/loginPage.html");
} else {
// pass the request along the filter chain
chain.doFilter(request, response);
}
}
public void destroy() {
//close any resources here
}
}
此示例摘自https://medium.com/@kasunpdh/session-management-in-java-using-servlet-filters-and-cookies-7c536b40448f。查看文章以了解详细信息。
答案 1 :(得分:0)
在web.xml中添加过滤器,例如:
<filter>
<filter-name>SessionFilter</filter-name>
<filter-class>
com.java.util.SessionFilter
</filter-class>
<init-param>
<param-name>avoid-urls</param-name>
<param-value>/Page1.htm</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SessionFilter</filter-name>
<url-pattern>*.htm</url-pattern>
</filter-mapping>
Filter实现可能类似于-
public class FilterTest implements Filter {
...
private ArrayList<String> urlList;
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String url = request.getServletPath();
boolean allowedRequest = false;
if (urlList.contains(url)) {
allowedRequest = true;
}
if (!allowedRequest) {
HttpSession session = request.getSession(false);
if (null == session) {
response.sendRedirect("startup.jsp");
} else {
chain.doFilter(request, response);
}
} else {
chain.doFilter(request, response);
}
}
public void init(FilterConfig config) throws ServletException {
String urls = config.getInitParameter("avoid-urls");
StringTokenizer token = new StringTokenizer(urls, ",");
urlList = new ArrayList<String>();
while (token.hasMoreTokens()) {
urlList.add(token.nextToken());
}
}