What check should I make if the user directly accesses the home.jsp page without logging in?
What check should I make if the user directly accesses the home.jsp page without logging in?
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 Servlet 3.1 specification to indicate that the created class will be a filter.
The urlPatterns
attribute, which is a Array
of String
, indicates which URL's this filter will intercept. That is, doFilter()
method code will be executed even before request
reaches Servlet , but only when the requested URL is principal.jsp
.
The check done within the doFilter
method was based on the code you posted in the question, but could be anything else. (It is assumed that after login, you use the setAttribute
method with the "login" key, saving some Java object indicating that the user is logged in.)
USING PURE JSP
This form is strongly not recommended. Use the filters for better readability and elegance of the code.
You can also use JSP-only with a session "login" attribute check at the top of the page. If you give negative, you are redirected to login.
It would look 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 the JSP is very clear and does not require further explanation.
Anyway, I hope I have helped. Any questions, you can comment on the answer. Hugs.