Question

I'm writting a webapp that should be able to handle a request as following: localhost:8080/WeddingApp/report?tid=1

I want that in case the server gets the following requests: localhost:8080/WeddingApp/report localhost:8080/WeddingApp/report?tid=

to issue error 404/500 rather than the default 400. Not only changing the page that error 400 redirect to, but to change the error code retrived from the server as well.

How can that be achieved?

Thank you :)

Was it helpful?

Solution

Where your code looks for the request parameter tid, set the response status to your desired code like this:

response.setStatus(404);

Where response is the HttpServletResponse from your servlet class:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletExample extends HttpServlet {
  private void doGetOrPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // ~~~ your code snippet ~~~
    String value = request.getParameter("tid");
    if (value == null) {
        response.setStatus(404);
    } else {
        // do something
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top