简体   繁体   中英

HTTP Status code in Java server based web application

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM