Call servlets doGet() method with RequestDispatcher - java

How is it possible to call doGet() method from RequestDispatcher?
RequestDispatcher rd = sc.getRequestDispatcher("/CartServlet");
rd.forward(request, response);
This code calls doPost() as the default action.

It calls doPost() because your original request used POST method.
Generally servlets cannot "call" each other. They just can forward or redirect request. In both cases the same HTTP method that was used in original request is used.
If you want to call doGet() of other servlet it is the time to refactor your application, i.e. separate the logic implemented in doGet(), put it to other class and call this class from both servlets.

Check out below link, using HttpURLConnection to send request internally by POST or GET methods. I had felt the need for this for a long long time.
Java - sending HTTP parameters via POST method easily

Related

How to send values from one jsp page to other but redirect to some other page?

I want to send values from jsp1.jsp to jsp2.jsp but redirect jsp1.jsp to jsp3.jsp . I used the following code in servlet for jsp1
response.sendRedirect("welcome1.jsp");
request.setAttribute("usern",user);
RequestDispatcher rd = request.getRequestDispatcher("afterlogin.jsp");
rd.forward(request,response);
but it keeps on giving this error "org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP".
you can use the possiblites of sessions in those case so you can access the parameter in jsp2 and redirect the jsp 1 to 3
https://www.javatpoint.com/servlet-http-session-login-and-logout-example
http://java.candidjava.com/tutorial/Servlet-Jsp-HttpSession-Login-logout-example.htm
You can use a HttpSession object as a user session, or use the ServletContext object for sharing global application information. Then use methods getAttribute (String attb) and setAttribute (String attb, String value) for sharing information within JSPs. The issue when you use a request is that the domain of the request is constraining you to use this information only when you receive this request.
You can also use JavaBeans to share information within JSPs
EDIT: Have you included your Java code inside a scriptlet? Using <% your code here %>
when you are using the sendRedirect function it will immediately redirect to that page it will not read next line code.
So according to your code your compiler is smart enough to check it so it is giving you an error.
please see below
1) SendRedirect ():
This method is declared in HttpServletResponse Interface.
Signature: void sendRedirect(String url)
1)In case of sendRedirect request is transfer to another resource to different domain or different server for further processing.
2)When you use SendRedirect container transfers the request to client or browser so URL given inside the sendRedirect method is visible as a new request to the client.
3)In case of SendRedirect call old request and response object is lost because it’s treated as new request by the browser.
4)SendRedirect is slower because one extra round trip is required because completely new request is created and old request object is lost.Two browser request required.
5)But in sendRedirect if we want to use we have to store the data in session or pass along with the URL.
2) Forward():
This method is declared in RequestDispatcher Interface.
Signature: forward(ServletRequest request, ServletResponse response)
1)When we use forward method request is transfer to other resource within the same server for further processing.
2)In case of forward Web container handle all process internally and client or browser is not involved.
3)When forward is called on requestdispather object we pass request and response object so our old request object is present on new resource which is going to process our request
4)Using forward () method is faster then send redirect.
5)When we redirect using forward and we want to use same data in new resource we can use request. setAttribute() as we have request object available.
more in : https://www.javatpoint.com/q/3577/difference-between-requestdispatcher-and-sendredirect

Life cycle of Servlet and its methods

I know that Servlets consist of the init, service and destroy methods. I also know that there are the doPost and doGet methods available. The question is how the service method relates to the doPost and doGet methods. Are they called from within the service method after the request is being identified? Is the service omitted when the do methods are implemented? I need some clarifications here.
For example in a life cycle of a Servlet that receives a single POST request, I would have guessed that the order would be:
init() is executed
when init() is finished the service() is called
service() identifies the request and calls the doPost() method
when both doPost() and service() finish the destroy() method is executed
Would that be right?
No, it isn't right.
init() and destroy() are called only once. The servlet is instantiated by the container, and its init() method is called. That usually happens at startup, or when the first request for the servlet comes in.
Then all the requests are handled by the service() method, which calls the appropriate doXxx() method based on the request type (as documented).
Then, when the application is undeployed (or the server stopped), the destroy() method is called.
The javadoc is your friend. Read it. It contains all the answers to your questions. The specifications are also freely available.
From the documentation, service is responsible for dispatching to the relevant servlet method, based on the HTTP method called (POST, GET...)
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.
HTTPServlet.service
This is the basic flow,
- The servlet is initialized by calling the init () method.
The servlet calls service() method to process a client's request.
The service method invokes the doGet or doPost based on the request
type came from the client if get request came doGet is invoked if
post request doPost is invoked
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of the
JVM.
The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Servlet Life Cycle

Obtain servlet response when using Cross-Context

I'm using cross-context to call a servlet in another server application: Servlet /bar from server application 'A' calls /foo servlet on server application 'B'.
I'm using this very nice solution, just as in the Abhijeet Ashok Muneshwar answer, I forward the request from server application A to the /foo servlet on server application B.
I'm using the class RequestDispatcher () to send a request, but the response is returned in the same call?
RequestDispatcher rd = context.getRequestDispatcher("/Servlet2");
rd.forward(request, response);
How can I process and return the response from server application B in A's servlet.
Thanks.
If you use a forward, that passes control to the target of the forward. The other option with a RequestDispatcher is to do an include.
If you want more control than that, you'll have to use an HTTP client to retrieve the response and then apply whatever processing you want to but using an HTTP client this way is not something I'd recommend. You'd be better off refactoring your application so you can use RequestDispatcher.include.

Java Servlet and Jquery

Im currently making a Java Servlet that can respond to jquery calls and send back data for my web page to use. But this is only a response using the doGet method.
Is there a way to have multiple methods in a Servlet and call them each with JQuery?
i.e. have a method called Hello and it returns a String "Hello" and another method called Bye and it returns a String "Bye". Is there a way using Jquery or some other technology to do this kind of thing?
Im quite new to servlets so Im still not sure what they are fully capable of. So is the doGet the only method to 'get in' and I just branch responses from there?
With Servlet you can either call the service method, so may be for your scenario you could pass the parameter to decide which method to invoke from doGet()
also you could identify if request is coming from AJAX using header check
There are other technologies available which will allow you directly invoke method See JSF, DWR
See
How to invoke a method with Openfaces/JSF without rendering page?
How to call a java method from jsp by clicking a menu in html page?
Personally I use reflection in my controllers(servlets) which basically let me achieve this.
If I have a servlet called UserController
The main url to call the servlet will be /user.
Knowing this, I always pass my first parameter as ?action=add
Then in my servlet I have a method called add or actionAdd. Whichever you prefer.
Then I use the following code;
String str = String str = request.getParameter("action").toLowerCase();
Method method = getClass().getMethod(str, HttpServletRequest.class, HttpServletResponse.class);
method.invoke(this, request, response);
Explanation:
str will have the action parameters value, add in this case.
Method method will be a reference to a method with the given name(str) and its expected parameter types.
I then invoke the method, passing the context, request and response.
The add method would look something like this;
public void add(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
//do add stuff
String url = "/user/index.jsp";
RequestDispatcher dispatcher = context.getRequestDispatcher(url);
request.setAttribute("User", user);
dispatcher.forward(request, response);
}
I don't know about only passing back a string. But this should get you a basic idea.
Do note that reflection can cost you, altohugh it shouldnt really affect you much like this. And it is error prone as method names/signatures need to match perfectly.
So from jquery you would do an ajax request to the url:
localhost/projectname/user/add (if you use urlrewrite)
or
localhost/projectname/user?action=add (if you dont)
Servlet Container supports Custom Http methods since Servlet 3.0. For Ex,
public void doHello(HttpServletRequest req, HttpServletResponse res) {
//implement your custom method
}
The above method in Servlet can be invoked using hello http method.
But i am not sure if jquery has the support to invoke custom HTTP methods.
If it does not have, then the only option you have.
Invoke Servlet using GET and action parameter.
Read the action parameter and invoke the method using reflection.

When is doPut() called in a servlet?

Hi I was just curious when is the doPut() method in a servlet called. I know that if the form on a jsp/html page has a "post" method then the doPost() is called otherwise if it has a "GET" then the doGet() is called.When is the doPut() called ??
When an HTTP PUT request is received, naturally.
Can a page do a PUT request by code?
The only valid method attribute values of a <form> are get and post, according to the HTML5 spec. I assume that's what you're asking.
The doPut() method handles requests send by using the HTTP PUT method. The PUT method allows a client to store information on the server. For an example, you can use it to post an image file to the server. As the above answer says, goGet() and doPost() are in use, mostly. In my case, I use only these two, and I am getting only get requests, so I simply transfer the get request to doPost() and do my job easily.
if you want to send some confidential values in url via form you must use the post method, If you will use the get method for the form like login the values parameters like userid and password will be visible in url and anyone can hack that thing. So better to use post method in forms. By default it will call get method.
in get the url is like http://url?method=methodname&userid=123&password=123
so if you use post method the url will be like this http://url/methodname.do

Categories

Resources