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();
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.
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.
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.
Related
I am doing a simple Java Servlet POST request without using any HTML and only using Postman. And the response from getParameter() is always null.
Here is the servlet:
#WebServlet("/api/form")
public class FormServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String orderNumber = req.getParameter("testString");
System.out.println(orderNumber);
resp.getWriter().print(orderNumber);
}
}
And a picture with responses and how I am doing it:
EDIT
As was commented by Mukesh Verma.
All I had to do was add #MultipartConfig Annotation and I got the data.
This is not how method getParameter works. As stated in this question, you should call the servlet with the following URL:
http://localhost:8080/api/form?testString=test
Try using #MultipartConfig Annotation. It handles form-data mime type.
Changing Postman's radiobutton from form-data to x-www-form-urlencoded also does the trick and I am able to get the data.
I have passed the HttpServletRequest to another method in the servlet. Could I keep the servlet thread-safe? Is the below code thread-safe with er() method?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Your session Id: ").append(er(request));
}
public String er(HttpServletRequest request){
return request.getSession().getId();
}
it is perfectly fine, you are not modifying any state within the Servlet itself, the servlet lifecycle creates one instance of the servlet and calls the init() method, any additional requests come through the same instance. so if you don't have any unprotected instance variables, you should be fine.
Because request.getSession() optionally creates a session, the answer is that you may have a race condition where to "simultaneous" calls from the same client may result in different session objects created for that client and consequently, different IDs returned.
See also here
I'm using HttpRequestHandler to inject Spring beans into Servlets:
#Component("myServlet")
public class MyServlet implements HttpRequestHandler {
#Autowired
private MyService myService;
HttpServlet has separate methods doGet, doPost etc for different request methods.
But HttpRequestHandler has only one:
public void handleRequest (HttpServletRequest req, HttpServletResponse resp)
So how to handle GET and POST requests in this method separately? I need to have different logic for different request methods.
UPDATE:
Also I have a question: is there possibility to restrict handleRequest method to support only POST requests by configuration and to sendHTTP Error 405 automatically for other requests?
The HttpServletRequest provides the method getMethod()
Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. Same as the value of the CGI variable REQUEST_METHOD.
public void handleRequest (HttpServletRequest req, HttpServletResponse resp)
{
if(req.getMethod().equalsIgnoreCase("GET")){
//GET BODY
}
else if(req.getMethod().equalsIgnoreCase("POST")){
//POST BODY
}
}
//Below is my servlet called HtmlTable. I am trying to implement shopping cart like functionality here. addingItems is another class that puts elements in a ArrayList. Whenever I add something from website I want AJAX request to just call the method jusAdding() not the processRequest method. so that when sufficient items are added to the ArrayList I can print it on the screen by calling aI.getItems() which will happen automatically when simply call the servlet. Is it possible?? If yes how should I write the URL in AJAX request.
public class HtmlTable extends HttpServlet {
addingItems aI = new addingItems();
public void jusAdding(HttpServletRequest request, HttpServletResponse response){
aI.addItemsInCart(request, response);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
List<itemsCart> itemsInCart = aI.getItemsInCart();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet HtmlTable</title>");
out.println("</head>");
out.println("<body>");
//whatever content is in the itemsInCart will be displayed here in body tag
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
}
//forgive me if I am not clear. Let me know I'll update as per reader convenience.
You can't do that.
An HTTP request flowing through a Servlet will always go to the Servlet's service method. What you need is to use the service method as a controller, so it inspects the incoming request and calls jusAdding (or other methods) depending on the request's parameters.
Most likely, you will want to use an already-existing framework for doing that.
The following should give you more information, as well as some ideas how to go about doing so: How to use Servlets and Ajax?
None of your methods are going to be called by the container. You should start with the servlet specification (or at least the HttpServlet javadoc).
The container calls the service() method of your servlet, which in turn, for HttpServlet dispatches to the method corresponding to the request HTTP method: doGet(), doPost() etc. That's where you're supposed to hook your logic (overwrite one of those, or service() itself and put your code there).
In order to distinguish between a "full page request" and an "AJAX request", you need the client to include some discriminator in that call: some request parameter with distinct values, a different HTTP method or whatever. Once you have that, in your doGet() method for instance, you can check that discriminator and invoke either justAdd() or processRequest() according to the client request.
i have a question on how a servlet call a method and pass the value extracted from the web request. A scenario in which a web request is processed in a web request, i need to call a method and pass in the values extracted from the web request. When the method returns a value, send the value in the web response. thanks
If I understand you right you need something like this:
public class MyNewServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getParameter("paramname");
String result = MyBusinessClass.myBusinessMethod(param);
response.getWriter().append("The answer is: " + result);
}
}
When request comes from browser, it will first read web.xml and call service method of appropriate servlet. Then service method decide to call doPost or doGet method on the basis of request. Once you get parameter , you need to create object of requestDispatcher and call forward method which will send your response.