How to send data from servlet to another servlet? [duplicate] - java

This question already has answers here:
How to pass a String value from one servlet to another servlet? [duplicate]
(3 answers)
Closed 4 years ago.
This is my simple code in servlet 1. I want to use this data in other servlet. How can I do that?
String nic = request.getParameter("nic");
String name = request.getParameter("name");
String mobile = request.getParameter("mobile");
List<String> ab = new ArrayList<>();
ab.add(nic);
ab.add(name);
ab.add(mobile);
for (String data : ab) {
allData += data + "<br>";
}

If you want to use it immediately (in the same HttpServletRequest)
If the other servlet's doGet or doPost methods are accessible, use...
request.setAttribute(String name, Object o);
add everything to the request object and call it like this,
new servlet2().doPost(request, response);
Else if the other servlet's doGet or doPost methods are inaccessible
Use the RequestDispatcher
RequestDispatcher rd = request.getRequestDispatcher("servlet2");
rd.forward(request, response);
Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name. ~ RequestDispatcher (Java EE 6 ), Java doc
If you want to use it in multiple HttpServletRequests,
Add the data into a HttpSession
request.getSession().setAttribute(String name, Object o);
this will remain until the user session is being destroyed.

Related

I am trying to call one servlet to another servlet, unable to call servlet [duplicate]

This question already has answers here:
How do I execute multiple servlets in sequence?
(2 answers)
Closed 3 years ago.
I have build the code for jdbc-Servlet, I made jdbc connection for Data retrieving.Now I want to call servlet,How do I call one Servlet to another Servlet?
Use RequestDispatcher
RequestDispatcher rd = request.getRequestDispatcher("servlet2");
//Forwards a request from a servlet to another resource (servlet, JSP file,
// or HTML file) on the server.
rd.forward(request,response)
//Includes the content of a resource (servlet, JSP page, HTML file) in the response.
rd.include(request,response)

Send array from one servlet to another servlet and print it?

First of all, I want to send parameters from html to Servlet and it works.
Then I create an array from parameters and I want to send that array to another servlet. and just print it in Servlet2.
Here is my code:
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//System.out.println("XML servlet called!");
response.setContentType("text/html");
response.getWriter();
//read value from selection
String videoname = request.getParameter("video");
String videoformat = request.getParameter("format");
String videoquality = request.getParameter("quality");
//System.out.println("Name" + videoname);
//System.out.println("format" + videoformat);
//System.out.println("quality" + videoquality);
String [] chain1 = {"v1","f1","q1"};
String [] chain2 = {"v1","f1","q2"};
if (videoname.equals(chain1[0]) && (videoformat.equals(chain1[1])) && (videoquality.equals(chain1[2])) ){
request.setAttribute("chain",chain1);
}
}else if (videoname.equals(chain2[0]) && (videoformat.equals(chain2[1])) && (videoquality.equals(chain2[2])) ){
request.setAttribute("chain",chain2);}
RequestDispatcher dispatch = request.getRequestDispatcher("/Servlet2");
dispatch.forward(request, response);
And in Second Servlet , my code is :
String value = (String)request.getAttribute("chain");
System.out.println("Chain is" + value);
My problem is this is doesn`t work. I have 2 problems. 1) how to send attribiute 2) is that possible to see the result in servlet2 in the same mashin? becuse I just create another class wich name is Servlet2 on the same project and define the name and the path in web.xml. Is that right approch?
How to send attribute?
What you are doing to send the attribute (using request.setAttribute and then using dispatch.forward is correct.
Assuming you have just created one new servlet named Servlet2 within the same project and have configured it correctly in web.xml, you should be able to get the attribute in that servlet's GET or POST method.
I believe that you are running into issues because you are modifying the response, which should be done by Servlet2 and not Servlet1. Remove the following lines from your code
response.setContentType("text/html");
response.getWriter();
,since you are not handling the response in Servlet1. This should work, if not, modify your question and include the complete stack trace of the error that you get when you try to compile/run this.
Servlets are created to handle requests sent by clients. I assume that your servlet2 class does a such service. If you declare a public static variable in a servlet, it is accessible by any class. Therefore you don't need to send your data to client from servlet1 and get the client sent them back to servlet2. If you have common variables to all servlets in a web server, you can use static variable. If the sole purpose of servlet2 is printing your data, it shouldn't be a servlet, just a java class would be fine.
Remember that only 1 servlet instance will be created for all requests. Therefore don't use instance variables to store client specific data. Try to use sessions.
This should help you.

for sendredirect which method gets called doGet or doPost() [duplicate]

This question already has answers here:
doGet and doPost in Servlets
(5 answers)
Closed 6 years ago.
I am new to servlets.
My Q is if I use for response.sendredirect()
which method gets called doGet or doPost()?
I know that in jsp to servlet get or post method will get called according to method type.
But if it is servlet to servlet request using response.sendRedirect() which method will get called?
how servlet engine decides which method to call?
Thanks in avdance.
redirect is always use get method,
redirection means a new request..
when we give send redirect actually happening is a new request from the user..
and it is always get..
since it is a new request we cant access the old request parameters
response.sendRedirect is always a GET
A sendRedirect() is always a 2 step process in which the server sends a URL Location and a status code of 301 to client browser.
The client browser then GET's the URL and then goes to that url location.(You can see this url in the address bar).
Remember a request to a Http or a URL link is always a Get request whether the URL is to a servlet within application or to external location.
Refer
http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpServletResponse.html#sendRedirect%28java.lang.String%29

Servlet doGet, doPost, and Ajax [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 6 years ago.
Intro:
I am a bit of a noob to the relationship between doGet and doPost in servlets.
Scope:
I am building a tool to help me with an online auction site where:
I (the user) enter a name into a form (html page), this name will be a URL (potentially for sale ->business method determines this through an API)
the html form posts the form name in doPost and then doPost uses the form name as an argument to call a business method
after the call to business method I redirect to a results html/js page that uses Ajax to call the doGet method to get the associated output (a public class String populated in business logic method)
Problem:
The Ajax page does not seem to get the output from doGet (actually doGet does not seem to have the String to give, no errors- just blank like String="". Which it is until business logic method adds to it).
Question 1:
How can I use doPost to request the form String 'st' so that I may call the business method while also redirecting to the html/js results page AND also am able to call doGet from Ajax
Question 2:
I've been trying to solve my answer by reading SO and other sites- but would like to formally ask rather than impute: is the use of a servlet the fastest way to achieve the Scope(above)? As opposed to JSPs or any other java server side libraries/ frameworks?
hw/ sw: CentOS 6.3, 16gb ram, physical node, corei7 #3.2, container is tomcat 7
HTML
<html>
<head>
<title>URL Search Page</title>
</head>
<body>
<CENTER>
<FORM ACTION="/ResultServlet/Results" METHOD=GET>
<INPUT TYPE=TEXT NAME="st">
<INPUT TYPE=SUBMIT VALUE=Submit>
</FORM>
</CENTER>
</body>
</html>
Servlet
#WebServlet("/Results")
public class Results extends HttpServlet {
private static final long serialVersionUID = 1L;
public static String str="";
public static void businessLogic(String q){
try {
str = new compute.URL.GetAvailURI( "https://www.registerdomains.com/auctionAPI/Key:a05u3***1F2r6Z&urlSearch="+q);
/*more boring number crunching */
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printWriter = response.getWriter();
printWriter.println(str);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String st = request.getParameter("st");
businessLogic(st);
response.sendRedirect("results/resultActionURL.html");
}
}
One problem you form methos is get so when you submit the form it will run the doget method in the servlet which does nothing in your case.
so first change the method to post then try running, also post the code of the html page on which you have written the ajax code.
I think so you are calling the same servlet from the ajax method but at that time the value in the str wont remain so append the needed data as query string while redirecting to
response.sendRedirect("results/resultActionURL.html?st="+ st);
This value you can get from using javascript
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
var st=getParameterByName(st);
//add your ajax call code and pass st as data there.
Hope this answers your question.
You are making your application stateful by doing this. You are storing data in server across requests.
That means your logic depends on the fact that the same servlet object is triggered, in sequence
Post request - calls business method and populates a string
Get request - tries to retrieve the string populated in last request.
First thing is this is not needed at all, you can pass the populated String to browser during redirect from doPost itself as a parameter or cookie value.
Even if you want to do this store this String in session
request.getSession().setAttribute("str", populated string)
and in doGet method retrieve that using
request.getSession().getAttribute("str"
This much better than having an instance variable in your servlet,.
Once you redirect to other page servlet will destroy request and response objects and variable values... so you can't get the old one... So try to get before redirect or save it on session object...

Can we somehow change the url in addressbar after dispatching request from servlet to jsp

I am having a weird problem here, and I am really stuck, need to get this work badly.
so i have a page say index.jsp with a link say "a href=servlet?id=10". when I click on this link it will go to doGet() on my servlet and here is the code in my servlet.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("id");
// search database and create an arraylist
if(//user logged in)
address = "s/results.jsp";
else
address = "results.jsp";
// set arraylist in session object
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request,response);
}
So the above code works fine but after request forwarding, my browser shows the url as
http://localhost/project/servlet?id=10.
I don't want the above url as i am forwarding to two different jsp's based on the user login status one is in 's' folder and other is outside of that.
if user is logged in then i forward to 's/results.jsp' and if user is not logged in i am forwarding to 'results.jsp'.
in case of s/results.jsp i am accessing resources like images and scripts from outside of 's' folder by using ../ in the results.jsp.
as url is not changing to s/results.jsp , i am unable to access the resources with '../'
and as i am using jsp pagination , when i click next the url is changing to s/results.jsp
and in that case i am able to access resources using ../
one solution in my mind is to copy all resources in s folder , but that would increase
redundancy.
one other solution in my mind is to create two different servlets for two jsp's
but i don't know where to put the servlet so that it can access resources outside of s folder with ../
is their any other good way i can do the task..
I have tried to find information about this but haven't been able to figure it out.
Any help will be very much appreciated.
You have basically instructed your webbrowser to send a request to exactly that URL. The forward does not change the URL. It is entirely server side. Apart from using response.sendRedirect() instead -which would trash the current request, including all of its attributes, and create a brand new request on the given URL-, you could also just change your link to <a href="results?id=10">, or when the user is logged in, to <a href="s/results?id=10">.
<a href="${user.loggedin ? 's/' : ''}results?id=10">
Finally alter the servlet mapping accordingly so that it get invoked on those URLs.
<url-pattern>/results</url-pattern>
<url-pattern>/s/results</url-pattern>
You'll only miss the JSP extension. But JSPs which are to be used by a dispatcher belong in /WEB-INF folder anyway so that they cannot be viewed by the enduser directly without invoking the servlet first. You also end up with nicer URLs.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("id");
// search database and create an arraylist
if(//user logged in)
address = "s/results.jsp";
else
address = "results.jsp";
// set arraylist in session object
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request,response);
}
in the above code instead of using request dispatcher,
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request,response);
we can try with
response.sendRedirect(request.getContextPath()+"/address");

Categories

Resources