In NetBeans 6.7.1, I have made a j2ee project,
In this project I have Servlet that extends HttpServlet,
Of whatever little I know about servlets, they should have a service method however in the class in NetBeans I find only thefollowing methods.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {}
public String getServletInfo() {}
doGet and doPost in call the processRequest method.
Where is the service method?
A servlet does not need to (re)implement the service() method of the javax.servlet.Servlet or javax.servlet.http.HttpServlet class. Regurgitating from the API doc, the service() method is used to dispatch requests to the doXXX() methods of the servlet. It is already implemented in the HttpServlet class, for the HTTP protocol, and hence there is no need to override it in another servlet relying on the HTTP protocol.
By the way, NetBeans automatically creates the doGet(), doPost(), getServletInfo() and processRequest() methods for convenience, when you create a servlet. It does not mean that the service() method is not available - most servlet programmers do not have to implement the service() method.
Related
This question already has answers here:
Sending redirect to another servlet/JSP without loosing the request parameters.
(2 answers)
doGet and doPost in Servlets
(5 answers)
Closed 2 years ago.
I have servlet A where there is this code :
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("gestion-avis");
rd.forward(request, response);
}
And then another servlet B which refers to "gestion-avis" :
#WebServlet("/gestion-avis")
public class GestionAvisServlet extends HttpServlet
The code of the A servlet normally redirect to the doGet method of the servlet B.
But this redirect me to an empty html page called "gestion-avis".
Thank you for your help !
This could be the reason for your issue.
Since you are forwarding request to another servlet mapped at url gestion-avis, the request goes to your GestionAvisServlet and its doGet method.
Now if your GestionAvisServlet.doGet method is not writing any data to HttpServletResponse, you will get a blank screen.
So to see some data either you need to write data to HttpServletResponse like this:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.getWriter().println("Hello");
}
Otherwise you can forward to another page.
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.
I know about Servlet Filters and Event Listeners but I'm not sure if that's what I need to use.
Let's say I have a method:
Integer count = 0;
public void increment() {
count++;
}
and then a doGet:
public void doGet(HttpServletRequest request, HttpServletResponse response) {
System.out.println(count);
}
When performing a Get request for the first time, I'd expect count=1 and not count=0 because I want the method increment() to be executed first, before any other business logic in the web application.
Also, the count should be different for each user. It should be based on the number of requests a particular user has made.
What can I use to solve this problem?
I would prefer to not use Spring or any other 3rd party library
This all depends on where the count should be available, but you can create an abstract HttpServlet sub class that calls some abstract method to perform logic before handling the request
public abstract class BaseServlet extends HttpServlet {
#Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// wrap it in try-catch if you need to
prePerformLogic(req, resp);
// call super implementation for delegation to appropriate handler
super.service(req, resp);
}
protected abstract void prePerformLogic(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException;
}
Now your own Servlet implementation will extend from this class. You'll implement it as you see fit. But, as Luiggi has stated in the comments, the example you've posted brings up many possible concurrency issues. A Servlet shouldn't normally have any mutable state.
If you just want to add an counter attribute to the HttpSession, synchronize on the HttpSession, check if an attribute exists. If it doesn't, add one starting at 0. If it does, increment it and add it back as an attribute. You might get better performance with a AtomicInteger, but you need to synchronized the check for the existence of the attribute.
A Filter would probably be more appropriate in that sense, since the Servlet wouldn't have any state anyway.
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
}
}
I'm building an application where I'd like to intercept HTTP requests and decide whether or not to pass them to a JAX-RS implementation for processing.
I basically have a single filter-and-front-controller-servlet combination and would like the servlet to delegate routing either to Jersey or to my "standard" router.
I can see lots of examples of using Jersey as a servlet, or of starting up an HTTP server, but there doesn't seem to be a handy way to take an HttpServletRequest/HttpServletResponse pair and say "here you go Jersey, route this for me".
Am I missing something obvious?
In this case, I think a RequestDispatcher might helps
A RequestDispatcher object can be used to forward a request to another resource, so you can try something like the following:
public class FrontServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext sc = this.getServletContext();
if (someCondition) {
sc.getRequestDispatcher("/jersey/servlet").forward(req, resp);
}else{
sc.getRequestDispatcher("/standard/router").forward(req, resp);
}
}
}