开发者

HTTP Status code in Java server based web application

开发者 https://www.devze.com 2023-03-26 12:45 出处:网络
I have a web application in Java which does data exchange using XML. I have written a servlet and it uses HTTP Post to upload the XML file from a particular client. Once the Post method is completed s

I have a web application in Java which does data exchange using XML. I have written a servlet and it uses HTTP Post to upload the XML file from a particular client. Once the Post method is completed successfully, it sends 200 OK message to the client (using the default web server HTTP status). Now I need to include some HTTP status code in my application so开发者_开发问答 that the client gets some HTTP status message (eg. 400 Bad request, 502 bad gateway) when there is an issue with the upload. How should I add the HTTP status codes in my web application? Please help me with suggestion.Thanks


You can use HttpServletResponse#setStatus() or HttpServletResponse#sendError().

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {

    // handle upload

    // if error
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

    // or
    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                       "An unknown error occurred");
}

The methods differ in what they cause the servlet container to do, so choose the one most appropriate for your situation.

  • setStatus()

    If this method is used to set an error code, then the container's error page mechanism will not be triggered.

  • sendError()

    Sends an error response to the client using the specified status and clears the buffer. The server defaults to creating the response to look like an HTML-formatted server error page containing the specified message

The list of status code constants is available in the Field Summary of the javadoc. For the codes in your question:

  • HttpServletResponse.SC_BAD_REQUEST
  • HttpServletResponse.SC_BAD_GATEWAY


response.sendError(res.SC_BAD_REQUEST, "important_parameter needed"); Where response is your HttpServletResponse See

  • http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Response-Status-Line.html
  • http://www.java2s.com/Tutorial/Java/0400__Servlet/ServletResponseSendError.htm
0

精彩评论

暂无评论...
验证码 换一张
取 消