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 :)

有帮助吗?

解决方案

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
    }
  }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top