关于Java:会话过滤器的用法

Session Filter usage

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

directory

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

我的课程LoginFilter在软件包filtro

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@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{

            }    
}
    }

}

您有两种选择:

  • 将过滤器URL映射更改为/faces/app*,因为这就是访问页面的方式。
  • 在web.xml文件中,摆脱/faces/* servlet映射,而使用*.xhtml。 这将需要将您的欢迎文件更改为仅index.xhtml
  • IMO我将使用选项2,因为我不喜欢Faces Servlet处理非JSF相关的请求,如JavaScript,CSS和图像文件。