Error 404 directed/or not to the Servlet. Problems with Layout

Asked

Viewed 1,201 times

3

I am studying java for web (EE) and would like to know if you could help solve a java problem!

I have in my web.xml a call to the erro404.jsp file that is at the root of the site to filter out pages that do not exist!

It turns out that if the missing page called is at the root as well, for example /site/paginaInexiste.jsp, it will be at the same level as erro404.jsp and when erro404.jsp is called, all its internal links (css, includes[code]) will work.

However, when the Missing Page is inside any root folder, that is, outside the level of error404.jsp, example /site/pasta/paginaInexistente.jsp, so erro404.jsp is called normally but its internal links don’t work.

I tried sending 404 errors to a Servlet RequestDispatcher to call erro404.jsp because both Servlet and erro404.jsp are at the same level, but it didn’t work!

web xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>imwsaogotardo</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>AdminServlet</servlet-name>
    <servlet-class>imwsaogotardo.src.controller.AdminServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>AdminServlet</servlet-name>
    <url-pattern>/imwsaogotardo/AdminServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>ProfessorServlet</servlet-name>
    <servlet-class>imwsaogotardo.src.controller.ProfessorServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ProfessorServlet</servlet-name>
    <url-pattern>/imwsaogotardo/ProfessorServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>SalaServlet</servlet-name>
    <servlet-class>imwsaogotardo.src.controller.SalaServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>SalaServlet</servlet-name>
    <url-pattern>/imwsaogotardo/SalaServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>UsuarioServlet</servlet-name>
    <servlet-class>imwsaogotardo.src.controller.UsuarioServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UsuarioServlet</servlet-name>
    <url-pattern>/imwsaogotardo/UsuarioServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>PerguntaServlet</servlet-name>
    <servlet-class>imwsaogotardo.src.dao.pergunta.PerguntaServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>PerguntaServlet</servlet-name>
    <url-pattern>/imwsaogotardo/PerguntaServlet</url-pattern>
  </servlet-mapping>

  <error-page>
    <error-code>404</error-code>
    <location>/ErrosServlet</location>
  </error-page>
  <error-page>
    <error-code>500</error-code>
    <location>/ErrosServlet</location>
  </error-page>
</web-app>

And in Servlet

package erros;

import java.io.IOException;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(
            name="ErrosServlet", 
            urlPatterns={"/ErrosServlet"}
           )
public class ErrosServlet extends HttpServlet 
{
    private static final long serialVersionUID = 1L;

    public ErrosServlet()
    {
        super();
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)    throws ServletException, IOException
    {
        Throwable throwable = (Throwable) req.getAttribute("javax.servlet.error.exception");
        Integer statusCode = (Integer) req.getAttribute("javax.servlet.error.status_code");

        req.setAttribute("errorType", throwable);
        req.setAttribute("statusCode", statusCode);

        //colocando o setStatus OK
        res.setStatus(HttpServletResponse.SC_OK);

        // We have to remove the exception from the request. If we do not remove the IE9 will not display out error page.
        // IE9 will think that some error created a crash inside our application if we do not remove the exception from the request.
        req.setAttribute("javax.servlet.error.exception", null);
        req.setAttribute("javax.servlet.error.status_code", null);

        RequestDispatcher requestDispatcher = null;

        if(statusCode==404)
        {
            requestDispatcher = req.getRequestDispatcher("/erro404.jsp");
        }
        else if(statusCode==500)
        {
            requestDispatcher = req.getRequestDispatcher("/erro500.jsp");
        }

        requestDispatcher.forward(req, res);    

    }

    public void doGet(HttpServletRequest req, HttpServletResponse res)    throws ServletException, IOException
    {
        doPost(req, res);
    }   
}

Note: I did not launch Servet on web.xml

Is there any other resource?

Adding the error page:

<jsp:useBean id="constantes" class="util.Constantes" />     
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>    
<%@ 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">
<link type="text/css" rel="stylesheet" href="_global/_css/estiloSite.css" />
<title>${constantes.tituloSite}</title>
</head>
<body class="fadeIn">

 <div id="topo"> <jsp:include page="_global/topoErro.jsp" /> </div>
 <div id="meio"> <jsp:include page="erro404Conteudo.jsp" /> </div>
 <div id="mapa"> <jsp:include page="_global/mapaErro.jsp" /> </div>
 <div id="creditos"> <jsp:include page="_global/creditosErro.jsp" /> </div>

 </body>
</html>

Next erro404Conteudo.jsp

<div id="central">

        Esta página não existe! <br/>
        Código do Erro : ${statusCode} <br/>
        <img src="_img/editar.png">
        <a href="_global/topoErro.jsp">Editar</a>
        <jsp:include page="_global/topoErro.jsp" />

</div>

Good, remembering that Dispatcher is done naturally. The error is due only to the style and image links. Hrefs and includes usually occur!

  • Could you include the technologies?(frameworks) and put your web.xml in the question? @Carlosrocha

  • I added to the question!

1 answer

1


I don’t know how your project is going and what I suggest is a way to solve, not necessarily the most elegant.

Since you have not posted your page with the links that are not working, I assume that you OR are using fixed paths OR relative paths, always starting with current path, which in certain cases will give error.

How to solve? You should always consider the context of your application when composing the links, in order to always have the complete link to your resource, making the reference to be direct to the resource and not reporting, in the same folder, etc. To do this you can do it in various ways, like these:

  • JSTL: If you are using JSTL you can do something like this:
<!-- recupera caminho do contexto e configura uma variável com este valor -->
<c:set var="ctx" value="${pageContext.request.contextPath}" scope="request" />

<!-- usa a variável -->
<a href="${ctx}/site/pagina.jsp" />
  • Using JSP scriptlet: if you are not using JSTL, you can do something less friendly by recovering more or less like this:
<!-- recupera caminho do contexto e configura uma variável com este valor -->
<%
String ctx = request.getContextPath();
%>

<!-- usa a variável -->
<a href="<%=ctx%>/site/pagina.jsp" />

Or directly:

<a href="<%=request.getContextPath()%>/site/pagina.jsp" />
  • It’s a real study project! Here’s the link. http://www.funerariasaopedro.net.br/imwsaogotardo.zip If you can take a look thank you! In this case, I’ll have to use <%=request.getContextPath() %> to compose all links. That’s it?

  • @Carlosrock this, one of the approaches cited. Test and let me know, if you need to look at your project. Or you can include an example page in your question.

  • Is there a way to use like a filter or something?

  • @Carlosrocha does not see how a filter would be a good alternative. What would he do? Even so you can use, if you think it solves

  • I added the error page to the question. I thought: As the filter picks up the whole site, so in all subfolders of the system it would be. Then, the links would not fail. If you take my project you will see that in the admin folder you have a filter that scans the folder and has a folder too. With this filter, whatever page does not exist, erro404.jsp normally opens. But in the forumebd folder, there is no filter and missing pages inside it occur error!

  • @Carlosrocha the approach mentioned solves your problem, test and see if it meets. If you want a filter for this, build it and if in doubt include new questions.

  • Yes friend$, I would also like to know if this is the standard used to solve this case. In other words, this is how people use it. Because I’m finding it a little weird to use context on all the links. Although it seems not to have left even since Servlet just redirects pages correctly at its hierarchy level!

  • @Carlosrocha is yes, and not only in java. If you look for this, you will find numerous references of people using.

  • Let me ask you one more thing and let’s close this question with your guidance? Is it me or Dispatcher (or will it be Servlet) handling different style and image links than href links? Thank you for the guidelines!

  • @Carlosrocha did not understand your question. How do you treat the result differently, you say? Why links are links, it will always be reference to another resource, regardless of the type of resource.

  • Look at the end of the question where it looks like this: Then error404Conteudo.jsp. Note that there is a href and a jsp include for the same address. Href, if cleaved, goes correctly. But include says it didn’t find the address (this is still in the eclipse)

  • @Carlosrocha, you’re confusing things. The link is direct access to an existing resource, an already compiled JSP, css, etc. include does, as the name says, the inclusion of a "sub-resource" at compile time. In erro404Conteudo.jsp you will not find _global/topoErro.jsp for inclusion, because there is no such thing as aa/_global/topoErro.jsp, but you will find the link. Why this? Because you will access from the root, then you will go straight to the resource. For inclusions as you are doing, use relative paths. In case the link (a) keeps, but include will be something like ../_global/topoErro.jsp.

  • Well, I think I got it. No includes were not necessary, but in the images, hrefs and page styles that received Dispatcher it was necessary to use the context: ${pageContext.request.contextPath}. Updated there. You can take a look to see that it is correct. I put the zip on http://www.funerariasaopedro.net.br/imwsaogotardo.zip.

  • @Carlosrocha cool, if it was helpful, consider accepting the answer. Read more about the community’s use of the tour and the help section

  • Thanks for everything! In the end, I ended up using the guidelines collected here! Again, many thanks!

  • @Carlosrocha ok, if you have helped, consider accepting the answer. If not, let me know so I can edit it. Also, see the tour and also the help section, there you will understand the format of the community. I saw that you did not accept any of the questions in your answer so far, it is interesting to visit the two links =)

Show 11 more comments

Browser other questions tagged

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