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
Related
Someone guided me towards the spring MVC form tld yesterday morning and I've been struggling to do what looks like a very simple task ever since! It looks like a simple solution but I just can't seem to get it right. I'm thinking I must be misunderstanding something very fundamental to be unable to get it working. I was wondering if someone could point out where I'm going wrong?
At the moment all I'm trying to do is display a list of values in a jsp select.
The model entity is very simple (and I realise needs a little fine tuning)
#Entity
#Table(name = "user")
public class User {
#Id private String userId;
private String userName;
private String passwordCode;
private Date dateOfBirth;
public String getUserId() {
return userId;
}
public String getUserName() {
return userName;
}
public String get PasswordCode () {
return passwordCode;
}
public Date getDateofBirth() {
return dateOfBirth;
}
}
My controller is also currently very simple
#Controller
#RequestMapping("/")
public class HomeController extends JFrame {
#Autowired private MeetingDAO meetingDAO;
#RequestMapping(method = RequestMethod.GET)
public String HomePage(Model model) {
List<User> userlist = userDAO.ListAll();
model.addAttribute("userlist ", userlist);
model.addAttribute("User", new User());
return "Home";
}
I got this far by using another q/a on stack overflow and I wonder if this is where my misunderstanding originates. I am passing in the list of values as an attribute as I have all along. I got a lot of errors doing this until I realised that I also needed to 'pass' the User model so that the spring tags in the jsp would understand the structure of the User object. This means I am now passing 2 attributes - User, as I understand it just so the form understands the structure (although maybe if I was cleverer this would also return the selected object?) and the userlist which is the actual data.
In the jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<body>
<h2>Users List Page</h2>
<form:form action="/home" method="Post" modelAttribute="User" >
<form:select path="userName">
<form:options items="${userlist}"/>
</form:select>
<input type="submit" id="submit" value="View"/>
</form:form>
</body>
</html>
I have paired this back down for simplicity but have tried quite a few things (itemvalue, itemlabel amongst others). This code returns all the data but in a comma separated list of all values (id, name, password, date). Whatever I try to do with path, itemvalue etc it won't just display one field. Ideally I wold like to display - userName (userId) - but at this stage I would probably settle for userName!
From my flapping about my impression is not connecting that User is an item in the userlist. If I feel I'm getting close it complains that userId (etc) is not a method of type array (which I assume means it is looking at the list) or if it seems to have understood the properties it has no data (which I guess means it's not picking up the list!).
could anyone help !?
Just to add this is the closest I think I have got but it complains that User is not valid a property of User ?
<form:form action="home" method="Post" modelAttribute="User" >
<form:select path="User" >
<form:options items="${userlist}" itemValue="userId" itemLabel="userName" />
</form:select>
<input type="submit" id="submit" value="View"/>
</form:form>
<form:form action="home" method="Post" modelAttribute="User" >
<form:select path="userId" >
<form:options items="${userlist}" itemValue="userId" itemLabel="userName" />
</form:select>
<input type="submit" id="submit" value="View"/>
This code will have the selected userId set in User object which you will get when you post the form.
path variable should be bound to backing object property here backing object is User so you should bind its userId property.
You can try the following for setting options (assuming userlist is a list of User objects and has fields userId and userName):
<c:forEach var="u" items="${userlist}">
<form:option item="${u}" itemValue="${u.userId}" itemLabel="$(u.userName}" />
</c:forEach>
Many thanks to all that helped. Actually although this was very useful it also made me realise I've been looking in the wrong place for 1 - 2 days! As I was filling the UserList from a stored proc not directly from hibernate it wasn't actually a list of Meeting objects after all but a list of comma separated values. Apologies I didn't post this bit of code (or look at it again until now). Ouch!
I should be using getRemoteUser functionality to get the logged in user. Until the authentication part get created I am trying to hard code the user in the jsp page and pass that in the my servlet. But when I try to print out the value its null:
<input type="hidden" name="userId" id="userId" value="123456789" />
Here is how I tried to get the user:
String fakeUser = request.getParameter("userId");
PrintWriter out = response.getWriter();
out.println(fakeUser);
System.out.println(fakeUser)
I also tried the solution mentioned following Stackoverflow post but that didn't work either.
passing value from jsp to servlet
As you are trying to use hidden-form field I assume that you are trying to do some sort of state management.
try something like this
<form action="urlOfYourServlet" method="post">
Enter your name : <input type ="text" name = "name">
<input type="hidden" name="hidden" value="Welcome">
<input type="submit" value="submit">
</form>
In servlet
String getHiddenValue=request.getParameter("hidden");
String name=request.getParameter("name");
System.out.println(name+" Hidden field Value is :"+getHiddenValue);
Disadvantage :
Only textual information can be persisted between request.
This method works only when the request is submitted through input form
Instead try url-redirecting or HttpSession
Inside a POST in a .jsp file, I'd like to do something like this:
<input type="text" name="...">
And inside the servlet I'd like to do:
request.getParameter(...)
Now where should and how should I declare "..." so that I can avoid duplication and reuse the same String.
Should this go in an interface like this:
public interface SO {
String POST_PARAM = "userinput";
}
Or in a property file? Or ...?
In any case, how do I then access this from the .jsp and from the .java file?
You can define constants like final String POST_PARAM = "userinput"; and then use them in markup: <input type="text" name="<%=POST_PARAM%>">.
Moving fields names to properties file does not sound as a beneficial unless you have reasons to do this.
To get parameter value from HTTP request caused by form submit say request.getParameter(POST_PARAM).
I hope this helps.
You might get the ... from a bean using EL. However, it is not usual for me.
You can use standard actions: jsp:useBean, jsp:setProperty and JavaBean technology:
Example:
A.jsp should call HTTP POST to B.jsp. B.jsp should automatically map all fields and redirect to your servlet.
// model.MyBean.java
class MyBean {
private int age;
// getters&setters
}
// A.jsp:
<form method="POST" action="B.jsp">
<input type="text" name="age">
</form>
// B.jsp
<jsp:useBean id="form" class="model.MyBean" scope="request" />
<jsp:setProperty name="form" property="*" />
<jsp:include page="/servletURL" />
Small description:
MyBean class will be created. This bean should has exactly the same
fields name like name in your form: for <input type="text"
name="age"> in bean should exists int age field and getter/setter.
jsp:setProperty with wildcard map all values from form A.jsp into your bean automatically.
if you want to call your servlet you can simple include appropriate url. Then in the servlet you will have access to request attribute "form" which will has MyBean with entered values.
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.
<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);
}