java - session 过滤器的使用

标签 java jsf session

我需要做一个 session 过滤器。 localhost:8080/Project/faces/index.xhtml 是登录名。如果登录成功,用户将被重定向到app/conta.xhtml,但如果用户直接写入localhost:8080/Project/faces/app/conta.xhtml地址栏且未登录的情况必须再次重定向到 index.xhtml

directory

未经成功登录,不得访问 app/* 中的所有页面。

我的类LoginFilter位于包filtro

@WebFilter("/app/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig config) throws ServletException {
        // If you have any <init-param> in web.xml, then you could get them
        // here by config.getInitParameter("name") and assign it as field.
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);

        if (session == null || session.getAttribute("idUsuario") == null) {
            response.sendRedirect(request.getContextPath() + "../index.xhtml"); // No logged-in user found, so redirect to login page.
        } else {
            chain.doFilter(req, res); // Logged-in user found, so just continue request.
        }
    }

    @Override
    public void destroy() {
        // If you have assigned any expensive resources as field of
        // this Filter class, then you could clean/close them here.
    }

}

我的 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>

    <filter>
        <filter-name>Login Filter</filter-name>
        <filter-class>filtro.LoginFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>Login Filter</filter-name>
        <url-pattern>/app/*</url-pattern>
    </filter-mapping>
</web-app>

尽管如此,我仍然可以进入/faces/app/conta.xhtml并正常访问!

这是我的登录验证代码 = validarLogin()

BeanUsuarios.java

@ManagedBean
@ViewScoped
public class BeanUsuarios {

    private Usuario usuario;

    public Usuario getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }

    @PostConstruct
    public void BeanUsuario(){
        if(getUsuario()==null){
            usuario = new Usuario();
        }
    }


    public void validarLogin(){
        UsuarioJpaController cUsuario = new UsuarioJpaController();
        cUsuario.getEntityManager().createNamedQuery("Usuario.findByLogin").setParameter("login", this.usuario.getLogin()).getSingleResult();

        if(usuario != null){
            if(usuario.getSenha().equals(this.usuario.getSenha())){
                FacesContext fc = FacesContext.getCurrentInstance();
                HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);

                session.setAttribute("idUsuario", this.usuario.getId());

                try {               
                    FacesContext.getCurrentInstance()
                            .getExternalContext()
                            .redirect("app/conta.xhtml");
                } catch (IOException ex) {
                    Logger.getLogger(BeanUsuarios.class.getName()).log(Level.SEVERE, null, ex);
                }

            }else{

            }    
}
    }

}

最佳答案

您有两个选择:

  1. 将过滤器网址映射更改为 /faces/app*,因为这就是您访问页面的方式。
  2. 在 web.xml 文件中,删除 /faces/* servlet 映射并使用 *.xhtml 代替。这需要将您的欢迎文件仅更改为 index.xhtml

IMO 我会使用选项 2,因为我不喜欢 Faces Servlet 将非 JSF 相关请求作为 JavaScript、CSS 和图像文件处理。

关于java - session 过滤器的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15735004/

相关文章:

ruby-on-rails - session 在 Rails 中是如何工作的

java - VAADIN 在生产模式下找不到主题

java - 一个简单的Windows批处理文件来运行java

java - 从 servlet 获取 Spring ConfigurableApplicationContext 运行时

java - session 过期时如何禁用重定向到 JBoss 中的登录页面?

javascript - 是否可以为每个选项卡生成唯一 ID?

java - InputStream和InputStreamReader在读取多字节字符时的区别

java - 使用正则表达式获取 url 的最后一部分

jsf - Omnifaces 套接字 + commandScript 组合

php - 安全地维护 PHP 中的用户 session