I have two JSP files, one for getting the user input and the other for printing the result.
I have a class file called getdata.java. How should I access that class when the user inputs something and print the result in the result page?
/// getdata.java when user click button it redirect to result page..
<form action="Result.jsp" method="post">
<input type="text" name="textname" /><br></br>
<input type="submit" name="submit" value="Search"/> remove
//// class file
public class On_Classes {
public void printData()
{
....
}
}
/// result page
Perhaps this might help? http://www.rgagnon.com/javadetails/java-0508.html
Unless you wanted to link to the java page? If so upload the java class to the WEB-INF directory and then in the form action make it link to /servlet/classname?
Or if you wanted to retrieve form data:
String resName = request.getParameter("formfieldname");
in the class.
Related
I am assigning href to a button and passing a value to the controller
JSP page
<td><input type="button" name="remove" value="DELETE"/>
</td>
In controller, I am trying to get the value when the button is clicked using:
if(request.getParameter("remove") !=null)
{
int cart_id=(Integer)request.getSession(false).getAttribute("cartid");
b_id = (String) request.getParameter("book_id");
int bid=Integer.parseInt(b_id);
System.out.println(bid);
}
This prints a null value though I have passed book_id value in the URL.
I want to know how can I get the value passed in the URL via the button.
You can't combine [a] tag with an [input] tag like that.
Try using a form instead with hidden inputs:
<form action=viewController>
<input type=hidden name=remove value=delete>
<input type=hidden name=book_id value=<%=vo.getBookId()%>>
<input type=submit value='Delete'>
</form>
The resulting url will be : viewController?remove=delete&book_id=...
When submit button is pressed, the entire form will be sent. You can select where data will be sent by using attribute action:
<form action="demo_form.jsp">
<!--inputs here-->
<input type="submit">Send me now</input>
</form>
In that case form will be sent to demo_form.jsp. In HTML5 you can use formaction attribute if you want use different servlets for different buttons
Any way, you shouldn't use links for sending forms.
It is possible to use links without button:
Remove
I've got a JSP page which contains a textbox, wrapped in a form. This form's action is set to a servlet.
I would like to manipulate the string (from the user's input in the textbox) before it is sent to the servlet, thus basically carrying out a simple request.setParameter call from the JSP to the servlet. Can this be done? If so how can I obtain the textbox's value in the JSP?
<form action="MyServlet" method="post">
<input type="text" name="txtUsername"/><br/>
<input type="submit" value="Submit"/>
</form>
You cannot do this using JSP code.
Remember, a JSP is processed, outputting its contents to the browser; that's where the JSP's request/response cycle ends.
Your options are:
Using JavaScript.
Using a Filter: http://docs.oracle.com/javaee/5/api/javax/servlet/Filter.html
Call a Javascript function on submit e.g. below:
function fnSubmit(){
document.getElementById("txtUsername").value = "new Value";
document.forms[0].submit();
}
In my JSP I do the following :
<!-- Bank manager's permissions -->
<!--more stuff goes here -->
<fieldset>
<legend>To open a new account</legend>
<form action="blablabla">
<input type="hidden" name="hdField" value="myValue" /> // note I pass a "myValue" as string
Press here to continue
</form>
</fieldset>
And in my Servlet I grab the hidden input :
#WebServlet("/employeeTransaction1")
public class Employee1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String getHiddenValue=request.getParameter("hdField");
System.out.println("Hidden field Value :"+getHiddenValue);
// forwards to the page employeeOpenNewAccount.jsp
request.getRequestDispatcher("/WEB-INF/results/employeeOpenNewAccount.jsp").forward(request, response);
}
}
And System.out.println produces : null at the Console
Why do I get a null of not the actual value is I pass ?
Regards
EDIT:
After changing to :
<fieldset>
<legend>To open a new account</legend>
<form action="/employeeTransaction1" method="GET">
<input type="hidden" name="hdField" value="myValue"/>
Press here to continue
</form>
</fieldset>
A null is still presented at the console .
What you are trying to do is to send a form to the server. But, in fact, you don't do that. You just issue a GET request (when the user clicks your link: Press here to continue)
If you want to send the form make sure you set the attributes of the form tag properly and add a submit button to the form:
<form action="/employeeTransaction1" method="GET">
...
<input type="submit" value="Submit" />
...
</form>
Depending on your preferred way of sending the form, you can change the method="GET" paramater to method="POST" and make sure that in the servlet you handle the form in the doPost() method
Alternatively, if your purpose is not to send the from to the server but just to pass the value of the hidden input, you should add its value as a prameter encoded in the GET request. Something like:
/employeeTransaction1?hdField=myValue
To achieve this, you need some client processing, i.e. when the user clicks the link, the hidden input should be added to the get and then the request should be issued.
Using an href tag does not submit your form, i.e. it does not pass the parameters defined in the form to the request. You should use input type="submit" or button tags instead. Also make sure the form action matches your #WebServlet definition.
<fieldset>
<legend>To open a new account</legend>
<form action="/employeeTransaction1">
<input type="hidden" name="hdField" value="myValue" /> // note I pass a "myValue" as string
<input type="submit" value="Submit" />
</form>
</fieldset>
I have a JSP form. My requirement is to get this form's data and create a java beans object on the server side.
Example: my form has fields like Name, SSN, EMAIL & Phone Number
public class Test {
long ssv= 1282199222991L;
long phone= 4082224444L;
String email = "abcdef#yahoo.com";
String name="abcdef"
}
From the knowledge i have , i was thinking to create bean object using servlet, which is created out of JSP, at the server side. My question is how i access this "server created" servlet for getting the variables data?
PS: I am beginner in web programing & server side scripting. Please let me know if the question is not clear. Any information would very valuable for me. Please do let me know if i am thinking in the right way. Trailer Thanks!
The JSP should indeed submit the form to the servlet. The servlet should indeed create the bean and use it to transfer the submitted data through the necessary layers (save in database using DAO class and/or redisplay in result JSP after submit).
Here's a kickoff example of how the JSP should look like:
<form action="register" method="post">
<p><input name="name">
<p><input name="email">
<p><input name="phone">
<p><input name="ssv">
<p><input type="submit">
</form>
And here's how you could write the doPost() method of the servlet which is listening on an url-pattern of /register.
String name = request.getParameter("name");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
String ssv = request.getParameter("ssv");
// Do the necessary validations here and then ..
User user = new User(name, email, phone, Long.valueOf(ssv));
// Now you have an User javabean with the necessary information.
// Do with it whatever you want. E.g. saving in database.
userDAO.save(user);
See also:
Beginning and intermediate JSP/Servlet tutorials
Well its been a long time since this question was asked. However, I believe this is the required answer.
Start with a HTML form to collect the data as below (I used only username and email)
<HTML>
<BODY>
<FORM METHOD=POST ACTION="process.jsp">
Name <INPUT TYPE=TEXT NAME=Name SIZE=20><BR>
Email <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
To collec this data in a bean create a class e.g. MyData as shown
package datapackage;
public class MyData{
String name;
String email;
public void setName( String value )
{
name = value;
}
public void setEmail( String value )
{
email = value;
}
public String getName() { return name; }
public String getEmail() { return email; }
}
Make sure it is compiled and available to your application's environment
Then create a JSP page process.jsp to receive this data
<jsp:useBean id="data" class="datapackage.MyData" scope="session"/>
<jsp:setProperty name="data" property="*"/>
<HTML>
<BODY>
You can output the data here too with e.g. <%= data.getName() %> but that was not your question
</BODY>
</HTML>
At this point you have an object in session (can be in page, application and request scopes too if you set the scope parameter on the jsp page to any of them). Any servlet that is called while the user still has a valid session after filling the form can access the object from session like this;
package datapackage;
import java.io.IOException;
import javax.servlet.http.*;
public class SalesServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
HttpSession session = request.getSession();
MyData d = (MyData)session.getAttribute("data"); //data is the variable name set in the JSP page
}
}
This, I believe, is the general flow to your show you how you can access a Java Bean's data from within a Servlet.
Take a look at the tutorial on Handling Form Data
if you need to be far to servlets, you can pass object to other JSPs from one page to another.
let's say your class is com.company.beans.User
on first page GetInput.jsp
you have the following code
<jsp:useBean id="user" class=com.company.beans.User />
now the object user can be reused in all JSPs pages such the container create an instance of the class ..
in the same page you can have a form that pass the form input to another jsp page
<form action="second.jsp">
<input type="text" name="uname"/>
<input type="password" name="pass"/>
<input type="submit" value="submit"/>
</form>
on the second page you can access the object named user
<jsp:useBean id="user" class="com.deeb.beans.User" />
<%
user.setUsername(request.getParameter("uname"));
user.setPassword(request.getParameter("pass"));
%>
also on the another page you can get the values
<html>
<body>
<form action="Test1.jsp" method="post">
<select name="source" onchange="">
<option value="rss">RSS LINK</option>
<option value="other">OTHER LINK</option>
</select>
Enter URL to be added <input type="text" name="url" size=50>
Enter the Source Name of the URL<t><input type="text" name="source1" size=50>
<input type="Submit" name="submit1" value="Add URL in DB">
</form>
</body>
</html>
The above code is stored in Addurl1.jsp file which calls the other jsp file named Test1.jsp.
The code under Test1.jsp is as follows
<%# page import="myfirst.*" %>
<%
String url1=request.getParameter("url");
String source1=request.getParameter("source1");
myfirst.SearchLink p=new myfirst.SearchLink();
String result=p.addURL(url1,source1);
out.println(result);
System.out.println(result);
%>
Test1.jsp calls addURL(String, String) function of SearchLink.java program.
In the dropdownbox of Addurl1.jsp program, if the user selects RSS link, the addURL() method must be called. If the user selects OTHER LINK, there is another method named addURL1() in the same java program which must be called.
Please let me know how the above codes can be modified inorder to achieve my task.
Thanks in advance!
At first it is better to change Addurl1.jsp into a servlet and implement the doPost method. Jsp files are supposed to only contain the presentation layer and no Java code. Java code should go in servlets (or controllers if you are using an MVC framework).
What you are asking can easily be achieved with an if statement:
final String RSS_LINK = "rss";
final String OTHER_LINK = "other";
String url1=request.getParameter("source");
String result="";
if (url1 != null && url1.equals(RSS_LINK)) {
result=p.addURL(url1,source1);
}
else if (url1 != null && url1.equals(OTHER_LINK)) {
result=p.addURL1(url1,source1);
}