calling Servlet's method from JSP - java

I am developing a web application using JSP and Servlets.
I wants to call servlet's method from JSP page when user click's on the Update button.
<input type="button" value="Update" onclick="<%MyServletName.Update(request, response);%>"></input>
When I click on Update button then this method is calling the servlet, But the problem is that when form is loaded then this method is called automatically.
Thanks in advance.....
Source Code....
<%#page import="MyPackageName.MyServletName"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Update</title>
</head>
<body>
<form>
<%
String[][] data = (String[][])request.getAttribute("data");
String[] columnNames = (String[])request.getAttribute("columnNames");
//fill the table data
if(columnNames.length!=0 && data.length!=0)
{
%><table><%
}
for(int i=0;i<data.length;i++){
%>
<tr> <td><%= columnNames[0] %></td> <td><input type="text" name="text1" value="<%= data[i][0] %>"></td> </tr>
<tr> <td><%= columnNames[1] %></td> <td><input type="text" name="text2" value="<%= data[i][1] %>"></td> </tr>
<tr> <td><%= columnNames[2] %></td> <td><input type="text" name="text3" value="<%= data[i][2] %>"></td> </tr>
<%
}
%>
<tr>
<td></td>
<td><input type="button" value="Update" onclick="<%PlanProtocolEdit.Update(request, response);%>"></input></td>
</tr>
</table>
</form>
</body>
</html>
Is there any way that I can call the servlet method other than dogGet() and doPost() without invoking the servlets dogGet() and doPost() methods?

You should specify the action on the form itself not the actual input button.
If you define an action on the form. E.g.
The forms submit button will submit the form to that URL. E.g.
<form action="/mypath/someurl">
<input type="submit" value="Submit" />
</form>
You can add an additional attribute to the form tag to specify whether you want the request to be a get or a post.
<form action="/mypath/someurl" method="POST">
Would send a post request, you can then pick this up in your Servlet with the handlePost method
The above approach should be used, currently you are trying to call a Java method on a javascript onclick event. This is incorrect and it is not doing what you think it is.
The code in PlanProtocolEdit. Update should be in a doGet or doPost method of a servlet which will be triggered by configuring your form as described above.

<input type="button" value="Update" onclick="<%MyServletName.Update(request, response);%>"></input>
This line in your jsp will be evaluated to
<input type="button" value="Update" onclick=""></input> in HTML page. If you want to call your servlet on click, first map your servlet to a url path say /myservletpath in web.xml and then
use
<input type="button" value="Update" onclick="location.href='/myservletpath'"></input>

You can call a servlet method other than doPost() and doGet() by creating a useBean of jsp.
<jsp:useBean id="someid" class="SomePackageName.PlanProtocolEdit">
and call the servlet method onclick as:
<input type="button" value="Update" onclick="<% someid.Update(args[0], args[1]); %>" />
This jsp bean would identify your servlet class which you now can access in your jsp page with the id given to it in useBean tag.
Do not forget to close the useBean tag.

Related

Different calls from the same JSP page

In a JSP page I use one form to get the entire DB and another form (and the related servlet request and the specific sort command). Once I sort a field, the form with the whole DB become empty, so the two Forms are not working one after another, as I expected.
For the moment I am not sure whether it's a HTML problem or something else, so I put just a second button to get a refresh. However, I assume there must be a smarter & simpler way using jQuery.
Thank you in advance!
<table cellpadding="10">
<form name="Refresh" action="AllPost">
<input type="submit" value="Refresh " /> ¦
</form>
<form name="F" action="SortedPost" id="formular" method="post">
<input type="submit" value="Sort: " />
<select name="Titl">
<c:forEach items="${AllPost}" var="p">
<option> ${p.Item} </option>
</c:forEach>
</select>
</form>
</table>
<table>
<c:forEach items="${SortedPost}" var="p">
<tr>
<td>ID: ${p.id}</td>
<td>bla bla : ${p.blabla}</td>
</tr>
</c:forEach>
</table>
<table>
<c:forEach items="${AllPost}" var="p">
<tr>
<td>${p.id}</td>
<td>bla bla : ${p.blabla}</td>
</tr>
</c:forEach>
</table>

Redirecting to a servlet from a JSP on button click

Am trying to link from a JSP to a servlet . On clicking the button with the name="conf" I need to redirect to a servlet "/Initial" . The problem is when I use type="button" nothing happens, while when I use type="submit" the page gets directed to servlet "/Initial" and does the action there. Am not able to identify the problem.
Here is my code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="reg.serv.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="post">
<center>
<table border="1" width="30%" cellpadding="3">
<thead>
<tr>
<th colspan="2">Register Here</th>
</tr>
</thead>
<tbody>
<tr>
<td>Username</td>
<td><input type="text" class="" id="username" name="username1" value="" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password1" id="password" value="" /></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="password" name="confirmpassword1" id="confirmpassword" value="" /></td>
</tr>
<tr>
<td>Mobile Number</td>
<td><input type="text" class="" id="mob" name="mob1" value="" /></td>
</tr>
<tr>
<td>Email ID</td>
<td><input type="text" class="" id="email" name="email1" value=" " /></td>
</tr>
<tr>
<td>Address</td>
<td><textarea id="address" name="address1"></textarea></td>
</tr>
<tr>
<td colspan="2">Already registered Login Here</td>
</tr>
</tbody>
<tr>
<td><input type="button" value="confirm" name="conf" /></td>
<td><input type="reset" value="Reset" /></td>
<td><input type="button" value="Cancel" name="Cr" onclick="openPage('Initial.jsp')" /></td>
</tr>
</table>
</form>
<script type="text/javascript">
function openPage(pageURL) {
window.location = pageURL;
}
</script>
<%
String x = request.getParameter("conf");
if (x != null && x.equals("confirm")) {
//response.sendRedirect("/Initial");
RequestDispatcher dispatcher = request.getRequestDispatcher("/Initial");
dispatcher.forward(request, response);
}
%>
</body>
</html>
Please help me . Any help would be greatly appreciated. Thanking You.
you have to write
<form action=/your_servlet_page_name>
And you have to use
<input type="submit" value="confirm" name="conf"/>
And also you have to map your servlet page into web.xml file like
<servlet-mapping>
<servlet-name>CheckLogin</servlet-name>
<url-pattern>/CheckLogin</url-pattern>
</servlet-mapping>
<form action = "servlet-name" method = "method in the servlet">
<input type ="submit" value = "val">
</form>
This is a simple way to do this. If you are using the latest jre i think 7 and up, you don't need to declare the servlet in your web.xml file. the #WebServlet("/servlet-url") will do the trick.
if you want to use type="button" instead of type="submit". you can use javascript function on the click on the button. Like
<script>
function doSubmit(){
var actionURL ="MENTION URL YOU WANT TO REDIRECT";
// perform your operations
myForm.submit(actionURL); OR
myForm.submit();
}
</script>
<form name="myForm">
<input type="button" name="conf" value="conf" obclick="doSubmit();">
</form>
hope it will help you.
try by changing the script only
<script type="text/javascript">
function openPage(pageURL)
{
window.location.href = pageURL;
}
</script>
function openPage(pageURL) {
window.location = pageURL;
}
In above code snippet, pageURL has to be an absolute URL which in case of dealing with servlets may vary.So instead of this below can be used
location.href = (location.href).substr(0, (location.href).lastIndexOf('xyz.jsp'))+"/abc";
Here 'abc' is the servlet to which we have to redirect the 'xyz.jsp' .This can even work if there are many buttons.The respective functions could be written to redirect to respective servlets.
Also it works in case of input type is "button" or "submit".
I dont get exactly what you are trying to do,but redirect is working with:
response.sendRedirect(request.getContextPath());
or
response.sendRedirect(String url);

How can I submit a html form post that has several different iterated values?

This is a Spring MVC project.
So the following JSP
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<table>
<c:forEach items="${nameList}" var="studentList">
<tr>
<td><c:out value="${studentList.name}"/> ${studentList.regNo}</td>
</tr>
</c:forEach>
</table>
returns values like
Ramu
Somu
Mamu
Komu
I want to make each value as a post url, so that, if the user clicks any one link, I would like to submit as like the following jsp code does
<form method="post" action="number" id="number">
<div style="text-align: center;" >
<input width="20" type="text" data-validation="numbers" id="regNo" name="regNo" size="30" maxLength="50" placeholder="Enter Register Number">
</div>
</form>
I don't wanna do GET.
How can I do this? Please help me.
Use this
<td><a href='www.xyz.com:port/number?regNo=${studentList.regNo}><c:out value="${studentList.name}"/> </a></td>
And regNo you can get as the request parameter in controller
or
Path parameter in your controller like
<td><a href='www.xyz.com:port/number/${studentList.regNo}><c:out value="${studentList.name}"/> </a></td>
And modify your controller's configuration accordingly.

changing destination JSP page and servlet

I'm new to JSP and Servlet so please bear with me for a while!
I have a problem regarding the communication between JSP and Servlet.
I am trying to create a LogIn Page.
This is my Index JSP page for LogIN
<%#page contentType="text/html"%>
<%#page pageEncoding="UTF-8"%>
<html>
<head><title> index.jsp</title></head>
<body bgcolor="orange">
<h2> <font color=white> JSP index.jsp at</font>
<%= request.getContextPath () %>
<font color=white>
</font></h2><hr>
<form action="LibrarySysServlet" method ="POST">
<font color=navy><h3>Login</h3>
<table>
<tr>
<td> MemberId </td>
<td align="left"><input type="text" name="memId" length="30"/></td>
</tr>
<tr>
<td> Password </td>
<td align="left"><input type="text" name="password" length="30"/></td>
</tr>
</table>
<br>
<p><input type="submit" value="Submit"/></p>
</font>
</form>
<br>
</body>
</html>
I am really confused on what to put for the form action for the index page when logging in as the destination changes according to whether the logIn is correct or not.
For my Servlet side, i tried to scan in index page and pass it through a function to check whether logIn is correct and redirect it according to the different answer.
However when run, it does not redirect but it just proceeds to whatever was specified in form action.
Short snippet of the code (didn't paste the whole thing because it was too long):
RequestDispatcher dispatcher;
ServletContext servletContext = getServletContext(); //links to index.JSP
String page = request.getPathInfo();
page = page.substring(1);
if ("index".equals(page)) {
if (logIn(request)) {
dispatcher= servletContext.getRequestDispatcher("/result.jsp");
} else {
dispatcher= servletContext.getRequestDispatcher("/Menu.jsp");
}
}
HELP really confused ! WHat am i doing wrong??
RequestDispatcher dispatcher;
ServletContext servletContext = getServletContext(); //links to index.JSP
//check here your username and password and put into a variable true or false
if (variable== true) {
dispatcher= servletContext.getRequestDispatcher("/result.jsp");
} else {
dispatcher= servletContext.getRequestDispatcher("/Menu.jsp");
}
}
it is better off to use reponse.sendRedirect("{url}") not dispatcher.
Also test your logIn method see if it works as you wish
You could leverage the container and use FORM-based authentication. In the web.xml:
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>login.html</form-login-page>
<form-error-page>login_error.html</form-error-page>
</form-login-config>
</login-config>
then in the login.html:
Please log in:
<form method="POST" action="j_security_check">
<input type="text" name="j_username">
<input type="password" name="j_password">
<input type="submit" value="Login">
</form>
You must use j_security_check, j_username, and j_password for this to work.

Using javascript to perform two actions on uploading a file. File and file details are not passed onto the javascript function

I am using this code to upload a file. I have to perform two submit actions. So I call a javascript function onclick(). However, neither the file nor the file details entered using the form are transferred to the javascript function. What am I missing here?
<jsp:include page="template-top.jsp" />
<script type="text/javascript">
function onSubmit(){
document.forms["frm"].action="http://192.168.1.53/api.php/submit.xml";
document.forms["frm"].target="_blank";
document.forms["frm"].submit();
document.forms["frm"].action="directuploadsubmit.do";
document.forms["frm"].target="_blank";
document.forms["frm"].submit();
}
</script>
<style type="text/css">
td.boldtext{
font-weight: bold;
font-family:Helvetica,sans-serif;
font-size:16pt;
color:black;
width:200;
}
</style>
<%# page import="databeans.Submit" %>
<%# page import="databeans.User" %>
<%# page import="databeans.Sandboxes" %>
<%
User user = (User) session.getAttribute("user");
%>
<div style="visibility:hidden">
<iframe NAME = "iframe1" WIDTH="40" HEIGHT="40"></iframe>
</div>
<form id="frm" name="frm" method="POST" enctype="multipart/form-data">
<table>
<tr> <td class="boldtext">
Direct Submission
</td>
</tr>
</table>
<table>
<tr>
<td colspan="2">
<font color="red">Complete notes as Case#:Notes (Example: <font color="blue">"Case12345:test sample"</font>)
</font>
</td>
</tr>
<tr>
<td width=50>
<font color="black" face="Helvetica,sans-serif">File:* </font></td>
<td><input type="file" name="file" value="${filename}" size="100"/></td>
</tr>
<tr>
<td width=50>
</td>
<td><input type="hidden" name="email" readonly="readonly" value="<%=user.getUserName() %>" size="100"/></td>
</tr>
<tr>
<td width=50>
<font color="black" face="Helvetica,sans-serif">Notes: </font></td>
<td><input type="text" name="notes" value="" size="100"/></td>
</tr>
<tr>
<td width=50>
<font color="black" face="Helvetica,sans-serif">Sandbox: </font></td>
<td><select name="sandboxes[]">
<option value="00-0C-29-CF-B8-A6">VMSB1 - Win7</option>
<option value="00-0C-29-0A-AB-9A">VMSB2 - WinXP</option>
</select>
</td>
</tr>
<tr>
<td width=50 colspan="2" align="left"><font face="Helvetica,sans-serif" color="FF0000">All * marked fields are mandatory
</font>
</td>
</tr>
<tr>
<td width=50 colspan="2" align="center">
<!-- <input type="submit" name="submit" value="Submit" onclick= "this.form.target='_blank'; return true;">
-->
<input type="submit" name="button" value="Submit" onClick="onSubmit()">
</td>
</tr>
</table>
</form>
<jsp:include page="template-bottom.jsp" />
You should bind the onSubmit function to the form, instead of the submit button.
<script type="text/javascript">
function onSubmit(){
//First form submission:
document.forms["frm"].action = "http://192.168.1.53/api.php/submit.xml";
document.forms["frm"].submit(); //Submit #1
//Change the action
document.forms["frm"].action = "directuploadsubmit.do";
}
</script>
...
<form action="directuploadsubmit.do" onsubmit="onSubmit();" name="frm" method="POST" enctype="multipart/form-data" target="_blank">
... rest of page
When the user has disabled JavaScript, the default action is to only submit the form to directuploadsubmit.do, in a new window. When JavaScript is enabled, the following happens:
The action attribute is changed, to submit.xml.
The form submits (using .submit()
The action attribute is changed (back to direcuploadsubmit.do
The form submits, because the user clicked at the submit button.[1]
[1] When an user clicks at submit, the following events occur:
The submit event is triggered (if JavaScript is enabled)
The form is submitted to the page as mentioned at action.
you must prevent the default action of either the form or the submit button, by calling onclick="onSubmit(); return false;"
that won't let your form to get submited and allow you to handle the request beforehand

Categories