Calling Servlet from JavaScript - java

I intend to call a function in JavaScript which then calls a Servlet after an <input type="image"> is clicked.
JSP:
<head>
<script type="text/javascript">
function callServlet() {
document.location.href="test-servlet.jsp";
}
</script>
</head>
<body>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
...
<input type="image" name="submit"
src="https://www.paypalobjects.com/webstatic/en_US/btn/btn_buynow_pp_142x27.png"
onclick="callServlet()" alt="PayPal - The safer, easier way to pay online!">
</form>
</body>
Servlet (test-servlet.jsp):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>TestServlet called successfully!</h1>");
}
Context Root:
http://localhost:8080/mysite/test-servlet.jsp
However, nothing happens when I click the image button. I am new to JavaScript.

Try this code
<a href="#" onclick="callServlet()"><img
src="https://www.paypalobjects.com/webstatic/en_US/btn/btn_buynow_pp_142x27.png"
alt="PayPal - The safer, easier way to pay online!"></a>
EDIT:
Finally we discovered that a servlet should be mapped without extension and doGet method is used to get the request from javascript.

I Could see multiple errors in your jsp .
First of all ,
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
And also use the img tag with button as Roman says
the url in the action is called , when your form is being submitted
so try replacing it with ,
<form action="./test-servlet" method="post">
and using your JavaScript now,
You cant use window.location.href to make a POST request . check pass post data with window.location.href
<script type="text/javascript">
function callServlet() {
document.forms[0].submit;
}
</script>

Related

URL rewriting in Servlet/JSP

I know that response.sendRedirect() destroys the request/response object and new request is sent to the resource. So how come request.getParameter("") fetches me the value if the earlier request/response object has already been destroyed.
NewFile.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action ="MyServlet">
<label>Username</label>
<input type="text" name="textbox1"/><br>
<label>Password</label><input type="password" name="textbox2"/>
<input type="submit"/>
</form>
</body>
</html>
Servlet
/**
* Servlet implementation class MyServlet
*/
#WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("textbox1");
String password = request.getParameter("textbox2");
if (user.equals("abc")&&password.equals("123"))
{
response.sendRedirect("NewFile.jsp?name="+user);
}
}
}
Newfile.jsp
<%= "hi there"+request.getParameter("name") %>
I repeated here the comment so you can mark your question as solved by this answer :D
If you are talking about your jsp getting parameter "name"... it's simply because you have put the request directly in the url (NewFile.jsp?name=xuser). If not, I didn't understand your question, please try to be clearer
It is because at very first request, you are getting the parameter, after that you are sending redirect response, if you will do same thing on redirected page or servlet, you will not able to get any thing. In your case, you are sending parameter name with value, so you will be able to get it.
Go to your "NewFile.jsp" page, in that page <%=request.getParameter("name")>.
It will simply get the value you passed in URL("NewFile.jsp?name="+user).

invoking java scriptlet in JSP using HTML

I am trying to find a way to invoke a piece of java code within the JSP using HTML form
<form method="get" action="invokeMe()">
<input type="submit" value="click to submit" />
</form>
<%
private void invokeMe(){
out.println("He invoked me. I am happy!");
}
%>
the above code is within the JSP. I want this run the scriptlet upon submit
I know the code looks very bad, but I just want to grasp the concept... and how to go about it.
thanks
You can use Ajax to submit form to servlet and evaluate java code, but stay on the same window.
<form method="get" action="invokeMe()" id="submit">
<input type="submit" value="click to submit" />
</form>
<script>
$(document).ready(function() {
$("#submit").submit(function(event) {
$.ajax({
type : "POST",
url : "your servlet here(for example: DeleteUser)",
data : "id=" + id,
success : function() {
alert("message");
}
});
$('#submit').submit(); // if you want to submit form
});
});
</script>
Sorry,not possible.
Jsp lies on server side and html plays on client side unless without making a request you cannot do this :)
you cannot write a java method in scriptlet. Because at compilation time code in scriptlet becomes part of service method. Hence method within a method is wrong.
How ever you can write java methods within init tag and can call from scriptlet like below code.
<form method="get" action="">
<input type="submit" value="click to submit" />
</form>
<%
invokeMe();
%>
<%!
private void invokeMe(){
out.println("He invoked me. I am happy!");
}
%>
Not possible.
When the form is submitted, it sends a request to the server. You have 2 options:
Have the server perform the desired action when the it receives the request sent by the form
or
Use Javascript to perform the desired action on the client:
<form name="frm1" action="submit" onsubmit="invokeMe()"
...
</form>
<script>
function invokeMe()
{
alert("He invoked me. I am happy!")
}
</script>
You can't do this since JSP rendering happens on server-side and client would never receive the Java code (ie. the invokeMe() function) in the returned HTML. It wouldn't know what to do with Java code at runtime, anyway!
What's more, <form> tag doesn't invoke functions, it sends an HTTP form to the URL specified in action attribute.

JQuery - Servlet post fails erratically

I am new to JQuery, I am running into a wierd issue here, I try to do a post of my HTML form to a servlet, and try to print data on the servlet. Data gets printed most of the times I submit the form (say 7 times out of 10) with new values. But It fails the other 3 times, I could not find a pattern at which this is failing.
I tried using firebug and chrome tool, I don't see an error on the console, and I get 200 response in the resources/HTML tool in chrome every time I submit the form with correct values set.
Here is my code
HTML
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.16.custom/js/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<form id="fcall">
<p> Start Date: <input type="text" name="start" id="ibox_start">
End Date: <input type="text" name="end" id="ibox_end"> </p>
<div id="buttonID">
<input type="submit" value=" Find " class="button"></div>
</form>
main.js
$().ready(
function(){
$('#ibox_start').datepicker();
$('#ibox_end').datepicker();
$('#fcall').submit(
function(){
var start = $('#ibox_start').val();
var end = $('#ibox_end').val();
alert(start);
$.post("DServlet", {start:start,end:end}, function(data) {});
}
);
}
);
Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String start = request.getParameter("start");
String end = request.getParameter("end");
System.out.println("Date Recieved "+start);
}
I would expect to see one of the following :
natural HTML form submission
natural HTML form submission with a submit handler which validates form values and returns either true to allow form submission or false to suppress it.
a submit handler that submits form data by AJAX, establishes a .done() handler to handle the HTTP response, and returns false to inhibit natural HTML form submission.
The code above looks like a hybrid of these possibilities.

Liferay : How to call a Servlet from a JSP Page

This is my first Portlet. I am not getting values inside my servlet. Please, see the program. Inside my custom portlet Java class doView() method, I show a JSP page
public void doView(RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
include(viewJSP, renderRequest, renderResponse);
}
Inside the view.jsp page, I refer to a servlet to receive the values:
<form action="formServlet" method="post">
<h1>Please Login</h1>
Login: <input type="text" name="login"><br>
Password: <input type="password" name="password"><br>
<input type=submit value="Login">
</form>
Inside web.xml file:
<servlet>
<servlet-name>formServlet</servlet-name>
<servlet-class>FormServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>formServlet</servlet-name>
<url-pattern>formServlet</url-pattern>
</servlet-mapping>
Inside my servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = (String)request.getParameter("login");
System.out.println("The Name is "+name);
}
But I don't know why the servlet is not being called.
NOTE: This is an answer to a somewhat complicated question. If you are trying to learn the basics of portlet creation, I posted a better answer in another question.
You are submitting a form using the POST method but your servlet just implements doGet(), which serves the GET method. You should either submit your form using GET or implement the doPost() method (which would be preferable in other situations).
Also, it is necessary to precede the <url-pattern> content by a slash if it is an absolute pattern. That is, it should be
<url-pattern>/formServlet</url-pattern>
instead of
<url-pattern>formServlet</url-pattern>
That said, forget servlets now!
You are doing it in one of the worst ways. It is really a bad idea to write a portlet which calls a servlet. After a long time working with Liferay I can imagine situations where it would be more or less reasonable, but it is not here and will not be most of the times.
So, what should you do? You should submit your form to an action URL. To do it, first include the portlet taglib in your JSP:
<%# taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
Now, replace the action of your form by the <portlet:actionURL />. This tag will be replaced by a special URL generated by the portal. Also, precede each input name with the tag <portlet:namespace />; your <input type="text" name="login"> should become <input type="text" name="<portlet:namespace />login"> then. This tag will be replaced by a string which is associated with only your portlet; since you can have a lot of portlets in a page, each input should specify from what portlet it comes from. This is the final result:
<form action="<portlet:actionURL />" method="post">
<h1>Please Login</h1>
Login: <input type="text" name="<portlet:namespace />login"><br>
Password: <input type="password" name="<portlet:namespace />password"><br>
<input type=submit value="Login">
</form>
Now you are going to submit your data correctly - but how to get the submitted data? It certainly is not necessary to use a servlet! Instead, add to your custom portlet class a method called processAction(). This method should return void and receive two parameters, of the time javax.portlet.ActionRequest and javax.portlet.ActionResponse. This is an example of an empty processAction():
public void processAction(ActionRequest request, ActionResponse response) {
// Nothing to be done for now.
}
When a request to an action URL (as the one generated by <portlet:actionURL />) is sent to the server, it is firstly processed by the processAction() method and then by doView(). Therefore, the code you would write in your servlet should be put in your processAction(). The result should be then:
public void processAction(ActionRequest request, ActionResponse response) {
String name = (String)request.getParameter("login");
System.out.println("The Name is "+name);
}
Try it and you will see that it will work well.
yyy - Here's the answer to your comment:
In your JSP page you'll need to add the following for each of the actions you want that portlet to perform:
<portlet:actionURL var="addUserURL">
<portlet:param name="<%= ActionRequest.ACTION_NAME %>" value="addUser" />
</portlet:actionURL>
<form method="post" action="<%= addUserURL %>">
Then in your com.test.Greeting portlet you'd have for each of these:
public void addUser (ActionRequest actionRequest, ActionResponse actionResponse) {}
Does this answer your question?
Also it's usually best to start a new question rather than adding a comment.

JSP form parameters disappear when I POST my form to another page

If I leave the action attribute out of my form so it posts back to the same JSP I have no trouble reading the request parameters. However when I add an action attribute to handle the form with a separate JSP, the request parameters are null. Here's a short example (FormTest.jsp) that illustrates how I'm reading the request.
<HTML>
<HEAD>
<TITLE>FormTest.jsp</TITLE>
</HEAD>
<BODY>
<H3>Using a Single Form</H3>
<%
String command = request.getParameter("submit");
%>
You clicked <%= command %>
<FORM NAME="form1" METHOD="POST">
<INPUT TYPE="SUBMIT" NAME="submit" VALUE="First">
<INPUT TYPE="SUBMIT" NAME="submit" VALUE="Second">
<INPUT TYPE="SUBMIT" NAME="submit" VALUE="Third">
</FORM>
</BODY>
</HTML>
The above page works as expected. Initially the page prints You clicked null along with the form. Clicking any of the three buttons changes the message to You clicked First, etc.
Now I change just one line in the page above to add the action attribute:
<FORM NAME="form1" METHOD="POST" ACTION="FormHandler.jsp">
I added a separate JSP to my project to read the request parameter as follows:
<HTML>
<HEAD>
<TITLE>FormHandler.jsp</TITLE>
</HEAD>
<BODY>
<H3>Form Handler</H3>
<%
String command = request.getParameter("submit");
%>
You clicked <%= command %>
</BODY>
</HTML>
I expected the new FormHandler.jsp to just print out which button was pressed on the other page, but it seems the request parameter is always null.
What could be interfering with the request parameters being sent to a separate JSP?
Update:
This project has a JSF configuration file as well. I changed the action attribute to ACTION="FormHandler.faces" and the code above works but I don't quite understand why yet. Here's the method that's redirecting requests that end in .jsp.
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String uri = request.getRequestURI();
if (uri.endsWith(".jsp")) {
int length = uri.length();
String newAddress = uri.substring(0, length - 3) + ".faces";
response.sendRedirect(newAddress);
}
else { //Address ended in "/"
response.sendRedirect("login.faces");
}
}
Now I guess I need to know 1) how to figure out if this is the source of the problem, and 2) is there a way to preserve the request parameters when the response is redirected?
There's also an entry in the web.xml configuration file for this project that sets a filter mapping.
<filter-mapping>
<filter-name>faces-redirect-filter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
I suppose (but it's probably clear by now that I'm new to JSF, so someone correct me if I'm wrong) that using the .faces extension in my action attribute bypasses this filter.
POST parameters are lost because sendRedirect() sends a 302 Moved Temporarily redirect, which instructs the browser to load the specified page with GET request.
To retain parameters you need to use 307 Temporary Redirect instead - it instructs the browser to repeat a POST request to the specifed URI:
response.setHeader("Location", newAddress);
response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);

Categories