Java servlet故意抛出http 500错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20772837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:14:01  来源:igfitidea点击:

Java servlet throw http 500 error on purpose

javaservletswebglassfishhttp-error

提问by AdrianES

I am developing a java servlet. I am using glassfish server 4.

我正在开发一个java servlet。我正在使用 glassfish 服务器 4。

End users are sending me information through URL parametars, something like this:

最终用户通过 URL 参数向我发送信息,如下所示:

http://myIP:8080/TestProject/TestServlet?param1=test1&param2=test2&param3=test3

I am getting the values from param1, param2 and param3 and i want to write them in my database. If I get a SQL exception while writing the informations in my db i want to throw "500 Internal Server Error" to let them know that i have some technical problems and to resend their request. I want to know is there a default way to do this, set some status, display text ...?

我正在从 param1、param2 和 param3 获取值,我想将它们写入我的数据库中。如果在我的数据库中写入信息时遇到 SQL 异常,我想抛出“500 内部服务器错误”,让他们知道我有一些技术问题并重新发送他们的请求。我想知道有没有默认的方法来做到这一点,设置一些状态,显示文本......?

Here is the code:

这是代码:

@WebServlet(urlPatterns = {"/TestServlet"}, initParams = {
    @WebInitParam(name = "param1", value = ""),
    @WebInitParam(name = "param2", value = ""),
    @WebInitParam(name = "param3", value = "")})
public class TestServlet extends HttpServlet {

    String param1;
    String param2;
    String param3;
    boolean dbOK;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //Get parametars from the request
        param1 = request.getParameter("param1");
        param2 = request.getParameter("param2");
        param3 = request.getParameter("param3");
        //Input in db
        dbOK = Database.saveParams(param1,param2,param3);

        //Print response
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>T-Mobile Interface</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1> dbOK=" + dbOK + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

采纳答案by Zyga

You should be able to do that with response.sendError(int)

你应该能够做到这一点 response.sendError(int)

EDIT: Was meant to say that the parameter is the error code you want to send, so in your case 500.

编辑:意思是说该参数是您要发送的错误代码,因此在您的情况下为 500。

回答by Leos Literak

AFAIK ServletException is translated to Error 500 as well. But typically you set status on response and redirect (dispatches) to JSP, which contains your custom error page. You can set request attributes to customize JSP content.

AFAIK ServletException 也被转换为错误 500。但通常您会设置响应状态并将(调度)重定向到 JSP,其中包含您的自定义错误页面。您可以设置请求属性来自定义 JSP 内容。

req.setAttribute("MY_ERROR", "Database request failed");
resp.setStatus(HttpServletResponse.SC_ERROR);
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher("/error.jsp");
dispatcher.forward(req, resp);