How to get the status after using HttpServletResponse.setStatus
I have a Http Upload Servlet (http-post) and a user can upload an XML file along with some form fields. I have put on some validation checks to see if there was a bad request (eg. null value). So I used the following code chunk to perform that.
String myID = request.getParameter("ID");
if (myID .equalsIgnoreCase("")|| myID ==null)
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
else
myBean.setMyId(myID );
Now that I set the response.setStatus, I wanted to see what response.getStatus would look like, but I did not find any method in the HttpServletResponse class (my response is HttpServletResponse) that could show me the status. I needed to ou开发者_StackOverflow中文版tput the status as a field called Server Response as a response to the upload. Please help me with suggestions.
The servlet APIs don't provide a way to do this directly, but there are ways you could do this.
The clean way would be to create a
Filter
to wrap the realHttpServletResponse
object with a wrapper class that allows you to get thestatus
.The hacky / non-portable way would be to look at the actual implementation class for the
HttpServletResponse
and see if there is an additional public method. (Or even a non-public method or field that you could access reflectively ... though that would be a really bad idea, IMO)
If by "output the status as a field", you mean show the status code in HTML, a typical way to do this in a webapp is for your request handling logic (controller) to store the status code somewhere (model) so that it can be retrieved and shown in whatever mechanism creates the HTML (view), hence the MVC pattern. Don't consider the HttpServletResponse as a place to store the data you need to render a view. It's nothing but your conduit back to the user. Data needed for view rendering should go somewhere else, like in a request attribute, maybe.
精彩评论