我正在开发 jsf 登录和注销较小的 Web 应用程序。我看到了一些问题。我的注销方法没有删除会话并且无法重定向到登录页面。我已经从 stackoverflow.com 询问。Matt 用户向我回答了 Filter 类。然后我根据Matt研究过滤器和页面缓存。我曾经在web.xml文件等中使用过滤器的doFilter()方法。
这是我的代码:
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig config) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
UserController userController = (UserController) request.getSession().getAttribute("user");
if (userController == null || !userController.isLoggedIn()) {
response.sendRedirect(request.getContextPath() + "/login.jsf");
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
}
和注销()
public String logout() {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext ec = context.getExternalContext();
final HttpServletRequest request = (HttpServletRequest) ec.getRequest();
request.getSession(false).invalidate();
return "logout";
}
和 web.xml 配置:
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>org.bis.logic.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>*.jsf</url-pattern>
</filter-mapping>
登录后我渲染主页。
<body>
<!--
#{ session.invalidate();
response.sendRedirect("login.jsf");
} -->
<h:panelGrid rendered="#{userController.isLoggedIn()}">
Hello Mr . #{userController.user.name}
<br />
<h:form>
<p align="right">
<h:commandLink action="#{userController.logout()}"value="Logout" />
</p>
</h:form>
</h:panelGrid>
</body>
我的 userController managedBean 类:
@ManagedBean(name = "userController")
@SessionScoped 公共类 UserController {
private User user;
public UserController() {
user = new User();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public static void addErrorMessage(String msg) {
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
msg, msg);
FacesContext.getCurrentInstance().addMessage(null, facesMsg);
}
public String authenticate() {
if (user.getName().equals("admin") && user.getPassword().equals("")) {
return "success";
} else
addErrorMessage(String
.format("Username and Password didn't match !!!"));
return "fail";
}
页面导航xml:
<navigation-rule>
<from-view-id>/login.xhtml</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/home.xhtml</to-view-id>
<redirect />
</navigation-case>
<navigation-case>
<from-outcome>fail</from-outcome>
<to-view-id>/login.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/home.xhtml</from-view-id>
<navigation-case>
<from-action>#{userController.logout()}</from-action>
<from-outcome>logout</from-outcome>
<to-view-id>/index.xhtml</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>