I have a little bug that I hope someone can solve for me.
servlet1:
The story here is simple - I created a form and inside it an image. When you click this image information should be submitted to servlet2.
public void f1(HttpServletRequest request, HttpServletResponse response) throws
IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<html></br>");
out.print("<script language='javascript' type='text/javascript'
src='functions.js'></script></br>");
out.print("<body></br>");
out.print("<form method='post' name='mainForm' action='servlet2'><br/>");
out.print("<img id='someId' src='someSrc' onclick='submit()'/><br/>");
out.print("<label id='gameStatus'>Welcome!</label></br>");
out.print("</form></br>");
out.print("</body>\n</html></br>");
}
OK, I clicked the image and information is now submitted (I suppose)
servlet2:
Here I would just like to print out the parameters submitted earlier.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Enumeration parameters = request.getParameterNames();
while (parameters.hasMoreElements())
{
out.print((String)parameters.nextElement() + "<br/>");
}
}
unf. my output is null so i guess information was not submitted. The question is why? any typos? or a logical prob?
Thank you!
What information you are trying to pass? I don't see any input field in your form.
Kindly try to add input in your form. Let us see if it is displayed in your second servlet.
out.print("<form method='post' name='mainForm' action='servlet2'><br/>");
out.print("<input type='text' name='param1' value='test' /><br/>");
out.print("<img id='someId' src='someSrc' onclick='submit()'/><br/>");
out.print("<label id='gameStatus'>Welcome!</label></br>");
Check if param1 is displayed.
Related
One of the webservices I am trying to connect requires me to submit a form to an url, lets say LINK_A.
I have a form view VIEW_A, I submit VIEW_A to my own servlet called SERVLET_A. Here in SERVLET_A from the form params, I generate a signature key, which is required by the webservice.
Then I need to submit to LINK_A programmaticaly from my servlet, BUT they told me that I need to submit it and redirects to LINK_A, so unlike what I've known so far (using httpclient httppost and getting the response data), I need to do something like a redirect with post data to their link.
So in summary:
1. from my view, submit a form
2. modify post data from servlet
3. submit the form to the webservice link and move to that link (as if the form from the view submit directly to the webservice link)
How can i do this?
If you need the form to be submitted from the browser (not from within your servlet using httpclient) your servlet needs to return a self-submitting form. E.g. use document.getElementById('myForm').submit() on documentReady.
If your form params can be submitted via GET you might also respond with a HTTP 302 redirect containing all params in the query string.
mean if you want collect request from previous form and check in servlet class and forward to new form den check this logic if its help
form code within servlet
rotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<html body=\"red\"> <center>");
pw.println("<form action=\"./NewFile.do\" method=\"get\">");
pw.println("<h2>enter the name </h2> <input type=\"text\" name=\"username\">");
pw.println("<h2>enter the password </h2> <input type=\"text\" name=\"passward\">");
pw.println("<input type=\"submit\" value=\"login\">");
pw.println("</form>");
pw.println("<center></body></html> ");
}
this below code to check and initialize path, before that you have to configure web.xml for this servlet class to behave as controller.
public class ServletControl extends HttpServlet {
#Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("inside the servlet");
String servletpath=request.getServletPath();
String path = null;
if(servletpath.equalsIgnoreCase("/NewFile.do")){
path="NewFile.jsp";
}
if(path!=null){
RequestDispatcher dis=request.getRequestDispatcher(path);
dis.forward(request, response);
}
}
}
I have a working servlet wich originates back from this template:
http://www.objectdb.com/tutorial/jpa/eclipse/web/servlet
So the basic rountrip works.
I added a new feature where I POST data to the servlet, construct a call/request out of the data to a remote http server, retrieve the response-html-string (the content of the website I requested) and want to show this HTML String now as response to my original POST call.
I tried it like this:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
boolean showDetails = Boolean.valueOf(request.getParameter("showDetails"));
if (showDetails) {
String details = detailsLoader.loadDetails(String.valueOf(request.getParameter("value1")),
String.valueOf(request.getParameter("value2")));
response.getWriter().println(details);
response.getWriter().flush();
response.getWriter().close();
return; // <----------------- if showDetails then this is the end of doPost
}
// Display the list of guests:
doGet(request, response);
}
When I press the link that creates the POST event I see in the logfile, that "loadDetails" has succesfully loaded the content from the remote server, but the browser window does not refresh. Why?
PS: a simple redirect to the other side is not possible for technical reasons.
Try making a ajax request to your servlet which gives to html content as string sent it back to ajax call and set it to innerHTML of a div element.
I changed to use GET instead of POST and I used a separate Servlet for this kind of call. This solved my problem.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String details = detailsLoader.loadDetails(String.valueOf(request.getParameter("value1")),
String.valueOf(request.getParameter("value2")));
response.getWriter().println(details);
response.getWriter().flush();
response.getWriter().close();
}
I have a requirement to set custom headers in http response and read them whenever required. I use the following code to read the header.
servlet1:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.addHeader("cust-header", "cust-value");
RequestDispatcher rd = request.getRequestDispatcher("servlet2");
rd.include(request, response);
}
servlet2:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getHeader("cust-header"));
}
When I tried to read the custom header value, I got "null" in the console. Why this is happening? How can I read custom headers set in response whenever required?
From the RequestDipatcher include method API doc:
[...]
The ServletResponse object has its path elements and parameters remain
unchanged from the caller's. The included servlet cannot change the
response status code or set headers; any attempt to make a change is
ignored.
[...]
So, if you look at your code, you are setting the header at the response object, but trying to get it from the request.
As they remain unchanged, it won't work.
The most common way to pass values from a servlet to another in a forward or include redirection, is passing it as a request attribute:
servlet1:
//set a request attribute
request.setAttribute("cust-header", "cust-value");
RequestDispatcher rd = request.getRequestDispatcher("servlet2");
rd.include(request, response);
servlet2:
System.out.println(request.getAttribute("cust-header"));
I'm trying to display a PDF report on a webApp, I've been following this tutorial here
and it creates the pdf file fine, but I'm having trouble trying to display it in the browser. In my xhtml I have a button, once that button is clicked, a function calling the servlet is called. it goes into the servlet and created a pdf document fine. but I can't seem to figure out how to display it on the screen. is there a way to show the document on a new browser window, or new tab? or even the same one.
I'm working with Java Server faces 2.0 in Eclipse. and have a Tomcat 7.0 server.
on my webxml I added the following code specified in the example:
<servlet>
<servlet-name>PdfServlet</servlet-name>
<servlet-class>com.bravo.servlets.PdfServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PdfServlet</servlet-name>
<url-pattern>/PdfServlet</url-pattern>
</servlet-mapping>
and my servlet looks like this ( pretty much the same as the example):
#WebServlet("/PdfServlet")
public class PdfServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Font font = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.NORMAL, BaseColor.RED);
/**
* Default constructor.
*/
public PdfServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
invokePDFViewer(response);
Document document = new Document();
try{
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
addContent(document);
document.close();
}catch(DocumentException e){
e.printStackTrace();
}
}
private void invokePDFViewer(HttpServletResponse response){
response.setContentType("application/pdf");
}
private void addContent(Document document)throws DocumentException {
PdfPTable table = new PdfPTable(2);
Paragraph paragraph = new Paragraph ("Este es un parrafo en celda 1", font);
table.addCell(paragraph);
table.addCell("2");
table.addCell("3");
table.addCell("4");
table.addCell("5");
table.addCell("6");
document.add(table);
}
}
the xhtml I'm calling the servlet from looks like this:
....
function callPdfServlet(){
$.ajax({
type: 'POST',
cache: 'false',
data: 'codeType=notUsed',
url: '/miloWeb/PdfServlet',
async: false,
success: function(data){
},
error: function (xhr, ajaxOptions, thrownError){
alert(ajaxOptions);
}
});
}
.....
<h:commandButton id="reportButton" action=" " styleClass="button" value="get Report" onclick="callPdfServlet();"></h:commandButton>
So at the end, all it does right now is I go into the xhtml in my browser, click on the button, and it hits the servlet, goes through the code, and then thats it. my browser just reloads the screen and nothing else happens. so i need to show the pdf I just created. Thanks in advance for your help!
//************************************************************************************
EDIT 01/02/12:
after reading this and this
I can see that the action in the commandButton will take me to the "response".xhtml with "response" being a string that I either hardcode in, or is returned by an action in a Managed Bean. that response ( if not put in my faces-config file ) will take me to the page IF it's in the same folder as my current page.
so I believe that when I put "miloWeb/PdfServlet" as a response for the action, It looks for the page in the same folder ( which it's not) and since it doesn't find anything just reloads the page. And since I have a break point In the servlet, I am 100% sure it's not hitting it.
so my question is: How do I redirect my page to miloWeb/PdfServlet??
to clarify, it works fine if I put the name of another xhtml in the same folder. so it is working that way.
//This is what I tried just for reference:
Instead of going through the ajax call I've changed the button to
<h:commandButton id="reportButton" action="/miloWeb/PdfServlet" styleClass="button" value="get Report"></h:commandButton>
but it Just reloads the page and doesn't take me to the Servlet.
so another thing I tried was tried to go thought the action of the button calling a Managed Bean:
public String actionPdf(){
return "/miloWeb/PdfServlet";
}
again,same thing, the function returns the string, but it still doesn't take me to the servlet.
Just post a regular form rather than posting in AJAX, and the browser will load the response from your PDF servlet in the page rather than loading it from JavaScript and ignoring it completely:
<form method="post" action="/miloWeb/PdfServlet">
<input type="hidden" name="codeTyped" value="notUsed"/>
<input type="submit" value="Show PDF"/>
</form>
in the action of the commandButton, I had to type this in:
public String doThis(){
String url = "url of your servlet";
FacesContext context = FacesContext.getCurrentInstance();
try {
context.getExternalContext().dispatch(url);
}catch (Exception e) {
e.printStackTrace();
}
finally{
context.responseComplete();
return "";
}
So with this, I get the context root and redirect it there. url being /PdfServlet
I have a servlet that creates an html text box and then redirects to another servlet on submit. How can I access the value of the html text box from the new servlet? I am able to access servlet variables from the new servlet but I am not aware of how to access the value of the html generated code.
thanks,
Here is the servlet that gets the text input
public class ServletB extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
String value = System.getProperty("card");
PrintWriter out = response.getWriter();
out.println("<center><h1>Your preffered method of payment is "+value+"</h1><br />");
out.println("Please Enter Card Number<input type =\"text\" name = \"number\"/><form action=\"http://codd.cs.gsu.edu:9999/cpereyra183/servlet/ServletC\"><input type =\"submit\" value=\"Continue\" /><input type=\"button\" value=\"Cancel\" /></center>");
}
}}
This is the servlet the first servlet redirects to all I do is try to do is output the text input
public class ServletC extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
String value = System.getProperty("card");
PrintWriter out = response.getWriter();
out.println(request.getParameter("number"));
}
}
If you give the input field a name
<input type="text" name="foo">
then you can access it in the postprocessing servlet as a request parameter by the input field's name.
String foo = request.getParameter("foo");
See also:
Servlets info page - contains a hello world
Unrelated to the concrete question, in contrary to what the majority of servlet tutorials want to let believe us, HTML actually belongs in JSP, not in a Servlet. I'd suggest to put that HTML in a JSP.
If your markup looks something like this...
<form action="anotherServlet">
<input name="myTextbox" />
</form>
...then you can get the value out of the HttpServletRequest object in the doGet() or doPost() method of anotherServlet like this:
String textboxValue = request.getParameter("myTextbox");
See: ServletRequest#getParameter().
public class Formvalid extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter pr = response.getWriter();
boolean flag = true;
int count=0;
response.setContentType("text/html");
Enumeration enume;
enume = request.getParameterNames();
while (enume.hasMoreElements()) {
count++;
String name = (String) enume.nextElement();
String value = request.getParameter(name);
if (value == null || value.equals("")) {
pr.println("<h5 style='color:red;'>please enter manditory values :"
+ name + "</h5>");
flag = false;
}
}
pr.println("<h3>Employe Registation</h3>");
if (!flag || count==0) {
pr.println("<form method=\"get\" action=\"formvalid\"><br />EmpName *:<input type='text' name='Empname' ><br />"
+ "Age *:<input type='text' name='age' ><br /><tr><td>Qulification *:<input type='text' name='Qualification' ><br />Address<textarea> </textarea><br /><input type='submit' value='submit'><input type='reset' value='reset'></FORM>");
} else {
pr.println("<h3 style='color:green;'>submitted successfully</h3>");
}
}
}