我写了一个过滤器,它应该在登录后创建一个新的会话 修复会话固定。只有在用户登录系统时才应调用此方法:
//variables
public class GenerteNewSessionFilter implements Filter {
public static final String NEW_SESSION_INDICATOR = "cab";
// destroy
public void destroy() {
// TODO Auto-generated method stub
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
if (httpRequest.getSession(false) != null && httpRequest.getSession(false).getAttribute(NEW_SESSION_INDICATOR) != null) {
// copy session attributes from new session to a map.
HttpSession session = httpRequest.getSession();
// HashMap old = new HashMap();
HashMap<String, Object> old = new HashMap<String, Object>();
Enumeration keys = (Enumeration) session.getAttributeNames();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
if (!NEW_SESSION_INDICATOR.equals(key)) {
old.put(key, session.getAttribute(key));
session.removeAttribute(key);
}
}
// invalidation session and create new session.
session.invalidate();
session = httpRequest.getSession(true);
// copy key value pairs from map to new session.
for (Map.Entry entry : old.entrySet()) {
session.setAttribute((String) entry.getKey(), entry.getValue());
}
}
}
// initiatiliazion
public void init(FilterConfig filterConfig) throws ServletException {
}
}
但我只想在用户登录应用程序时执行一次,请指导我如何实现它。
感谢。
答案 0 :(得分:1)
您可以将过滤器应用于特定的servlet。因此,只将它应用于处理LoginAction的servlet,这样只有在用户登录时才会执行。
在web.xml
中更改过滤器路径
将<url-pattern>
更改为servlet的相同路径。
<filter>
<display-name>SessionFilter</display-name>
<filter-name>SessionFilter</filter-name>
<filter-class>com.session.SessionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>NewSessionFilter</filter-name>
<url-pattern>/your/path/LoginAction</url-pattern>
</filter-mapping>
或使用<servlet-name>
而不是<url-pattern>
<filter-mapping>
<filter-name>SessionFilter</filter-name>
<servlet-name>LoginAction</servlet-name>
</filter-mapping>
注意您也可以将<ulr-pattern>
应用于您的jsp。
<url-pattern>/your/path/login.jsp</url-pattern>