使用Servlet做一个简单的Error页面

/ java / 70浏览

使用Servlet做一个简单的Error页面

  1. 创建Error的java类

    image-20220410192544546

  2. 继承HttpServlet类,重写doGet,doPost方法,然后doPost调用doGet方法

    image-20220410192659484

    package top.lhhstudy.servlet;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    public class ErrorServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
  1. 再doGet中写下面的代码

    image-20220410193242634

            resp.setContentType("text/html");//设置相应的内容样式为html
            resp.setCharacterEncoding("utf-8"); //设置字符集编码为UTF-8
            PrintWriter writer = resp.getWriter(); //响应流
            writer.print("<h1>404</h1>");
    
  2. 去web.xml中注册Servlet和配置请求的路径

    image-20220410193510480

                 <servlet>
                    <servlet-name>error</servlet-name>
                    <servlet-class>top.lhhstudy.servlet.ErrorServlet</servlet-class>
                </servlet>
    
                <servlet-mapping>
                    <servlet-name>error</servlet-name>
                    <url-pattern>/*</url-pattern>
                </servlet-mapping>
    
  1. 启动tomcat服务器,默认进入的页面就是error界面

    image-20220410193623571

  2. 由于配置error配置的请求路径是/*,所以启动服务器进入后的页面就是404,但是你要进入那些已经配置的请求路径也是可以访问的,这是优先级问题。但是这种error做法有点low,待学习更好的方法先!

站长统计代码