If the user accesses the home before logging in he must be redirected to the index using jsp

Asked

Viewed 153 times

0

What verification should I do if the user directly accesses the home.jsp page without logging in? Noting that I am not using Servlet for this situation, only jsp pages.

Code from home.jsp page:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Bem vindo</title>
    </head>
    <body>

        <%
            if ((session.getAttribute("login").equals(null)) || (session.getAttribute("login").equals(""))) {
        %>
        Você não esta logado. <a href="index.jsp">Por favor, entre com a sua conta.</a>
        <%
            } else {
        %>
        Seja bem vindo,
        <%=session.getAttribute("login")%>
        <center>
            <a href="http://localhost:8080/Atividade07/listUsers">Listar -
                Servlet</a><br> <a href="listar.jsp">Listar - JSP</a><br> <a
                href='logout.jsp'>Log out</a>
        </center>
        <%
            }
        %>
    </body>
    </html>

Code of login.jsp page:

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Login</title>
    </head>
    <body>
        <form  action="checklogin.jsp" method="post">
            <center>
                <table border="1" width="30%" cellpadding="3">
                    <thead>
                        <tr>
                            <th colspan="2">Login</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>Login</td>
                            <td><input type="text" name="login"/></td>
                        </tr>
                        <tr>
                            <td>Senha</td>
                            <td><input type="password" name="senha"/></td>
                        </tr>
                        <tr>
                            <td><input type="submit" value="Login" /></td>
                            <td><input type="reset" value="Reset" /></td>
                        </tr>
                        <tr>
                            <td colspan="2">Ainda não esta cadastrado? <a href="register.jsp">Cadastra-se</a></td>
                        </tr>
                    </tbody>
                </table>
            </center>
        </form>
    </body>
    </html>

Clarifying further the context of this application follows an image of the application, which should implement the figure below (Only the part that is highlighted).

inserir a descrição da imagem aqui

  • Vitor Oliveira, I believe the answer: here may help in understanding your question.

1 answer

0

There are several ways to do this.

USING FILTERS

You can create a filter by implementing the interface javax.servlet.Filter:

@WebFilter(filterName = "MyFilter", urlPatterns = {"/principal.jsp"}, dispatcherTypes = {DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.INCLUDE})
public class MyFilter implements Filter {
   public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain)
      throws IOException, ServletException {


     HttpServletRequest req = (HttpServletRequest) request;

     if(req.getSession().getAttribute("login") == null) {
       response.sendRedirect("/login.jsp");
     } else {
       chain.doFilter(request, response);
     }

    }
}

UNDERSTANDING THE FILTER MyFilter

We use the Annotation @WebFilter that is present in the specification Servlet 3.1 to indicate that the created class will be a filter.

The attribute urlPatterns which is a Array of String, indicate which ones URL’s this filter will intercept. That is, the method code doFilter() shall be executed even before the request get into the Servlet, but only when the requested URL is principal.jsp.

Verification within the method doFilter was based on the code you posted in the question, but could be anything else. (It is assumed that after login, you use the method setAttribute with the key "login", saving some Java object indicating that the user is logged in).

USING PURE JSP

This form is strongly not recommended. Use filters for better code readability and elegance.

It is also possible to use only JSP with a check of the "login" attribute of the session at the beginning of the page. If negative, you redirect to login.

Would something like this:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% if(request.getSession().getAttribute("login") == null) {
  resp.sendRedirect("/login.jsp");
}
%>
<!DOCTYPE html>
<!-- Aqui continua seu HTML normalmente -->
<!-- ... -->

I think the code in JSP is clear and needs no further explanation.

Anyway, I hope I helped. Any doubt, can comment on the reply. Hugs.

  • 1

    Hello friend, very grateful to have elucidated this scenario. So, I had no knowledge about using Filter, but until then it was clear the real functionality of using Filter. The code of the home.jsp page worked, just rewritten and gave a clean on the project before startar; but it’s like you said q is not strongly recommended. For people who are learning how to log in and register in JSP, follow the site I took as an example: http://www.javaknowledge.info/login-registration-example-in-jsp-with-session/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.