AJF
AJF

Reputation: 1921

Extract URL from HttpServletRequest

I am maintaining a Java servlet application and now have to extract the URL from the web service request to determine what action to take depending on what URL called the web service. I have found that it is something to do with HttpServletRequest which I have imported to the class. I have tried setting up the following inside the web service end point but it keeps telling me that the urlrequest is not initialised. What am I doing wrong?

HttpServletRequest urlrequest;
StringBuffer url = urlrequest.getRequestURL();

Upvotes: 0

Views: 951

Answers (3)

Ali Motevallian
Ali Motevallian

Reputation: 1380

You cannot define a variable in java and call a method on it without initializing it beforehand. In the first line: HttpServletRequest urlrequest; you are just defining a variable. Since it is not initialized it is null and you cannot use it.

Remove this line and use the argument passed to the doGet (or doPost) method in your Servlet. For example if your servlet is like this:

public class MyServlet extends HttpServlet {

    ...

public void doGet(HttpServletRequest request,
                  HttpServletResponse response) throws Exception {

    ...
}

Instead of your code just add below line in the body of the doGet method:

public void doGet(HttpServletRequest request,
                  HttpServletResponse response) throws Exception {

    ...
    StringBuffer url = request.getRequestURL();
    ...
}

After this line you should be able to use the url variable.

Upvotes: 0

Manas Pratim Chamuah
Manas Pratim Chamuah

Reputation: 1567

The HttpServletRequest you are using should be the input parameter HttpServletRequest of either doGet,doPut,doPost or doDelete. Then Surely HttpServletRequest.getRequestURL will reconstruct the URL used by the client,excluding the query string parameters.

Upvotes: 3

Michael Sanchez
Michael Sanchez

Reputation: 1265

Your code is correct but it has to be accessed within the doPost(request, response), doGet(request, response) etc. methods of a class extending HttpServlet.

The reason for this is the when the service() method of HttpServlet is called, it populates the request and response objects for you given the client who prompted the request to your servlet.

Upvotes: 0

Related Questions