forward from doPost() to doGet() [duplicate] - java

This question already has answers here:
HttpServletResponse sendRedirect permanent
(2 answers)
Closed 7 years ago.
I am making a servlet for attendance. So in the doGet() method all the front end is displayed and if any error is generated ; i.e., something is left blank then the doPost() method should call the doGet() again for completing the blank spaces.
How can I call doGet() method from the same servlet's doPost()?

If I take your question literally (i.e. invoke doGet() from doPost()), you can just invoke the doGet() method... it's a standard method like any other.
Here's a tip: When the doPost() and doGet() methods share a common set of logic, it's a good practice to isolate that logic into a separate (private) method that is to be invoked by all relevant do***() methods. For example:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// GET-based logic
processCommonLogic();
// Other GET-based logic
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// POST-based logic
processCommonLogic();
// Other POST-based logic
}
private void processCommonLogic() /* throws ServletException and/or IOException if needed */ {
// Common logic
}
You can use this pattern to create a processError() method that can be invoked wherever you need it.
However, if the scope your question goes beyond invoking doGet() from doPost(), I suggest you have a look at the references pointed by Alain O'Dea.

You can do that, it's a simple
this.doGet(req, resp);
return;
However, it's not a best practice. Generally better to implement view logic as a JSP, and dispatch to it from the post logic...
this. getServletConfig().getRequestDispatcher("my_view.jsp")
.forward(req,resp);;
return;
Or use include(), or an MVC framework like Struts...

Related

Servlet thread safety: instance variables vs. request scope attributes [duplicate]

This question already has answers here:
How do servlets work? Instantiation, sessions, shared variables and multithreading
(8 answers)
Passing an object from JSP page back to Servlet
(3 answers)
How can I store state for an individual browser tab/window?
(2 answers)
Closed 5 years ago.
This is the sample code, illustrating the usage of instance variable and request attribute:
#WebServlet(name = "Upload", urlPatterns = {"/upload"})
#MultipartConfig()
public class Upload extends HttpServlet {
private String txt;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
String txt2 = (String) request.getAttribute("txt2");
//txt and txt2 variables are available for processing.
..........
} finally {
txt = null;//Prepare variable for next request.
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
.....
request.setAttribute("txt2", someValue);
//vs
txt = someValue;
processRequest(request, response);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
.....
processRequest(request, response);
}
}
Now I know that instance variables should be never declared in servlets, because the same servlet is shared between concurent requests. But what about request attributes? Is it safe to use them?
Not sure what you mean by initializing variables. On a servlet you mean or where?
Depending on what you need to do, maybe there are APIs involved in which you don't have control about the contracts (since they are not your APIs).
For example, when requesting is being processed by a filter chain. Maybe one filter is interested on data being set by a filter executed previously in the chain. You don't have means to pass data on the filter chain contract. Request attribute might be an option. Playing with ThreadLocal might be another, but it has performance implications and is not always suitable.
Another example, maybe you forward one request from a servlet to another. Again, you will not have an option to play with whatever member variable you define.
Also, if you were thinking on adding member variables on a servlet, remember Servlets are not thread-safe. What would you do? synchronize request processing, only one request being processed per servlet?
Your servlet is going to serve hundreds on concurrent request each one of them will use same shared instance of the servlet, therefore using private instance variable will lead to inconsistent behavior. Unless you synchronize access to it, which will lead to greater contention on access to this private field, therefore slowing down response time, producing bottleneck.
While storing attribute within binded to single request will allow you to avoid such problem, moreover it was designed to overcome issues similar to yours.

doGet or doPost method invocation [duplicate]

This question already has answers here:
How doGet() or doPost method invokes service() method internally
(3 answers)
Closed 6 years ago.
How does the servlet container know whether to call doGet or doPost method.
When I make a get request doGet is called, When I make a post request doPost is called , but where is the logic to decide this .
You never really call doGet() or doPost() (the service() method will, and it is called by the Web container as you read in the lifecycle).
The service() method detects the HTTP method used and delegates to doGet(), doPost() and other methods which process HTTP requests in a HTTPServlet. It also encapsulates the ServletRequest and ServletResponse objects in HttpServletRequest and HttpServletResponse objects which contain additional context data from the HTTP headers.
Tahnks to #helderdarocha.
For more;
The logic is in the HTTP protocol and its management by the servlet container (Tomcat, Glassfish, Jetty, ...)
The first word of the request (at the TCP level) is the HTTP verb, generally GET or POST but it can be DELETE, PUT, OPTIONS, HEAD, TRACE,...
The servlet container call the service method of the servlet, but the default implementation of HttpServlet.service method contains the logic to dispatch to the proper method. Extract from the Javadoc :
public void service(ServletRequest req,
ServletResponse res)
throws ServletException,
java.io.IOException
Dispatches client requests to the protected service method. There's no need to override this method.
protected void service(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,
java.io.IOException
Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class. This method is an HTTP-specific version of the Servlet.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) method. There's no need to override this method.
javax.servlet.http.HttpServlet.service(HttpServletRequest req, HttpServletResponse resp) contains the logic for that.
Request Method is a standard HTTP/1.1 token, which is sent as part of request headers
Please refer to:-
http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html

ProcessRequest Method

When do ProcessRequest method called?
I am having a hard time why ,what and how the process request is called? why it is called and how it was called by the servlet container.
The servlet has two important methods for handling the client's request:
1. doPost: in general handles requests coming from forms with post method.
2. doGet: handled requests coming from get method.
Now, ProcessRequest method, is any other method that you can use into your code which is not bound (overridden) to anything.
It is called from the above methods to not complicate the code in them thus the requests are handled in it.
so you can use ProcessRequest to handle your request if and only if it's called from one of the methods above.
The only ProcessRequest I could find, and the example includes this
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
and
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
So, it's called when you call it.

How to execute a method/event as soon as a servlet is called/page is loaded

I have a servlet that is called from a link on another page. The link actually references the servlet which then SHOULD write xml to the screen (outputting RSS XML information). Right now the link properly references and loads the servlet but because I have the code in the doPost method with nothing actually calling the doPost method nothing happens. (I'm new to Java EE) So how do I make that code execute without actually have a form that references the servlet through the "action =.." tag?
Can I call an init or main method that always executes on page refresh/load?
You can implement that logic in your doGet method. It has the same method signature as your doPost method.
Please see this thread
doGet and doPost in Servlets
For the difference between get vs post please see this article.
http://stevenclark.com.au/2008/01/12/get-vs-post-for-the-beginner/
You can also override Servlet.service method which is entry point for serving requests. This way you will handle both POST and GET requests.
Alternatively, you can implement logic in doGet method and invoke doGet from doPost:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// do request processing
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request, response);
}

Servlet : doGet and doPost [duplicate]

This question already has answers here:
doGet and doPost in Servlets
(5 answers)
Closed 6 years ago.
I have 2 parameters, User and Pass. I want to send them to a servlet.
If I use the doGet method of the servlet it would look like this :
"link?User="+TextFieldValue+"&pass"textFieldValue
user= UserName.getValue();
pass= password.getValue();
Resource newPictureResource = new ExternalResource("http://localhost:8888/PieChart?UserName="+name+"&Password="+pass);
Success.setSource(newPictureResource);
editContent.addComponent(Success);
send them to servlet :
String UserName = request.getParameter("UserName");
String Password = request.getParameter("Password");
It works (tested)
If the Username + pass are right then he get a "success" picture posted on the screen.
But nobody passes the parameters via URL.
My question: How do I send the parameters using doPost method of the servlet ?
info : im working with eclipse on a liferay portal with a Vaadin portlet.
You don't send parameters in doPost(..). You receive them there. HTTP has many methods, two of which are GET and POST. It is up to the client-side to choose which method to use. POST is most often used with html forms - <form method="POST".
Vaadin should be able to send POST requests as well - see this thread
Not sure how Vaadin interacts, but typically portlet requests are handled differently. Looking though The Book of Vaadin - Portal Integration sheds some insights on configuration and action processing.
If you're looking for a way to handle both request types without reusing logic, simply choose your method of submission by either post or get from your application interface:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Enter logic here
}

Categories

Resources