gpt4 book ai didi

java - 登录后创建新 session

转载 作者:行者123 更新时间:2023-11-28 22:56:38 25 4
gpt4 key购买 nike

我写了一个过滤器,它应该在登录后创建一个新 session 修复 session 固定。这应该只在用户登录系统时调用:

//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 {

}
}

但我只想在用户登录应用程序时执行一次,请指导我如何实现它。

谢谢。

最佳答案

您可以将过滤器应用于特定的 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>

关于java - 登录后创建新 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25569415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com