java - JSF 登录过滤器

标签 java jsf session

我正在我的网站上编写登录信息,不幸的是我遇到了一些问题。

用于日志记录的 MengedBean:

@ManagedBean
@SessionScoped
public class LoginMB {

    private static final String PERSISTENCE_UNIT_NAME = "ejbPU";
    private static EntityManagerFactory factory;
    private String login;
    private String password;
    private User user;

--konstruktor, gettery i settery

    public String validate() {
        factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        EntityManager em = factory.createEntityManager();
        Query q = em.createQuery("SELECT u FROM User u WHERE u.personalId = :login AND u.password = :password");
        q.setParameter("login", login);
        q.setParameter("password", password);
        try {
            user = (User) q.getSingleResult();
            if (login.equals(user.getPersonalId()) && password.equals(user.getPassword())) {
                return user.getRole();
            }
        } catch (Exception e) {
            System.out.println("Błąd: " + e.getMessage());
            return "failed";
        }
        return "failed";
    }

    public String logout() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "abcd";
    }
} 

过滤器:

public class FilterLogin implements Filter{

    FilterConfig fc;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        fc = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession(true);
        String pageRequested = req.getRequestURL().toString();

        if (session.getAttribute("loginMB") == null && !pageRequested.contains("/login.xhtml")) {
            resp.sendRedirect("/login.xhtml");
        } else {
            chain.doFilter(request, response);
        }  
    }

    @Override
    public void destroy() {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

web.xml

<filter>
        <filter-name>filter</filter-name>
        <filter-class>pl.ePrzychodnia.filter.LoginFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping> 
    <session-config>
        <session-timeout>
            1
        </session-timeout>
    </session-config>

日志页面:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>Logowanie</title>
    </h:head>
    <h:body>
        <h1>Login</h1>
        <h:form>
            <h:panelGrid columns="3">
                <h:outputLabel value="Login"></h:outputLabel>
                <h:inputText id="login" value="#{loginMB.login}" label="Login"/>        
                <h:message for="login" style="color:red" />
                <h:outputLabel value="Haslo"></h:outputLabel>
                <h:inputSecret id="pass" value="#{loginMB.password}" label="Password"/>        
                <h:message for="pass" style="color:red" />
                <h:commandButton value="Zaloguj" action="#{loginMB.validate()}"></h:commandButton>
                <h:commandButton value="Załóż konto" action="#{userMB.createAccount()}"></h:commandButton>
            </h:panelGrid>
        </h:form>
    </h:body>
</html> 

当 session 过期时,当我尝试转到另一个页面时,我收到错误:

An Error Occured: viewId:/adminPanel.xhtml - View /adminPanel.xhtml could not be restored.

而是转到页面login.xhtml。为什么? 帮助某人?

最佳答案

您需要处理 ViewExpiredException,如果您在 session 超时后尝试单击任何内容,则会发生这种情况。 JSF 将尝试恢复 View ,因此您会收到异常

查看:How to handle session expiration and ViewExpiredException in JSF 2?

关于java - JSF 登录过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16968718/

相关文章:

mysql - 表达 mysql session

javascript - 无法在 Node.JS 中检索 session

java - 如何检查 JFrame 中选中了哪些复选框?

java - 使用终端启动 java 应用程序

jquery - 如何获取<p :selectOneMenu> value using JQuery

java - ValueChangeEvent.getNewValue() 未从 JSF 2 中的下拉列表中返回正确的字符串值

java - 如何从 Java 读取命令行输出(通过 Runtime.getRuntime().exec(...))

java - 正则表达式提取方括号和括号内的内容

jsf - 填写其他输入时禁用一个输入

php - Laravel 5 Session_driver 数据库 token 不匹配