This question already has answers here:
Passing an object from JSP page back to Servlet
(3 answers)
Closed 6 years ago.
I have one Java Web Application.
My User_Objects class is given below
public class User_Objects {
public String firstName;
public String middleName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
}
I forward request with my Java User_Objects to JSP with using following code
User_Objects fillObj = fillData(request);
request.setAttribute("reqObj", fillObj);
RequestDispatcher view = request.getRequestDispatcher("/organization.jsp");
view.forward(request, response);
public User_Objects fillData(HttpServletRequest request) {
User_Objects fillObj = new User_Objects();
try {
fillObj.setFirstName(request.getParameter("txtFirstname"));
} catch (Exception e) {
}
try {
fillObj.setMiddleName(request.getParameter("txtMiddlename"));
} catch (Exception e) {
}
return fillObj;
}
I successfully receive this Object into my JSP form. But I want to send this Object again to the Servlet and When I click on Submit button on my JSP form and try to get this Object into my Servlet using below code
User_Objects obj = (User_Objects) request.getAttribute("reqObj");
request.getAttribute("reqObj") gives me null
My JSP form code is given below
<%# page import="otn.aitc.io.User_Objects" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!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>Organization</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.12.4.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
$(function() {
var reqObj = '${reqObj}';
var reqStatus = '${orgStatus}';
var orgJson = '${reqOrgJson}';
orgJson = orgJson.replace("/", "'");
if(reqStatus != "" || orgJson != "") {
if(reqStatus == "false") {
document.getElementById("lblError").style.display = '';
}
else {
document.getElementById("lblError").style.display = 'none';
}
var availableTutorials = [];
if(orgJson != "") {
var parsed = JSON.parse(orgJson);
for(var x in orgJson) {
if(parsed[x] != undefined) {
availableTutorials.push(parsed[x]);
}
}
}
$("#txtOrgName").autocomplete({source: availableTutorials});
}
else {
window.location.href = "index.jsp";
}
});
function validateOrg() {
var orgName = document.getElementById("txtOrgName");
if (orgName.value.trim().length == 0) {
alert("Enter Org Name");
return false;
}
}
</script>
</head>
<body>
<form name="orgname" action="org_name" method="post">
<table align="center">
<tr align="center">
<td colspan="4"><img src="images/logo.jpg" /></td>
</tr>
<tr>
<td>Organization :</td>
<td><input type="text" id="txtOrgName" name="txtOrgName" /><label style="color: red;">*</label></td>
</tr>
<tr>
<td align="center" colspan=2><br/><input type="submit" name="btnOrgName" id="btnOrgName"
value="Validate" onclick="return validateOrg();" /></td>
</tr>
</table>
<p align="center"><label id="lblError" style="color: red;">Error Message.</label></p>
</form>
</body>
</html>
I am using Java with Eclipse.
Don't mix and match the different execution scopes.
The serlvet and the JSP page are executed on server side (actually the JSP page is compiled to a servlet, too). Once the HTTP request is finished all request based objects are discarded, including the request attributes.
In the end it is a templating engine producing HTML text.
This HTML text (with embedded JavaScript) is executed by the client's browser. This execution scope is totally different to your server request scope, which has created this HTML page. So in your JavaScript code all the Java objects used to create that page on server side are unknown and unaccessable.
So you have two alternatives.
While creating the HTML include enough information to recreate your server side object. E.g. if you have a Person object with name and age attributes, you can include name and age as hidden form fields. After submitting the form you can recreate the Person object with the hidden field values coming in as request parameters.
Pro: Simple to implement.
Con: Only feasable for small data. Data is exposed to the client and can be manipulated.
Store the object on server side inside the session.
Pro: Data is not exposed to the client.
Con: Implementation more complex because of possible concurrent access to the session variables (browser can do multiple requests for the same session at the same time).
Related
I'm having a JSP page as follows :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Admin Tools</title>
<jsp:include page="/basic/nav.jsp"/>
<link rel="stylesheet" type="text/css" href="tools.css"/>
</head>
<body>
<div class="container">
<h2>Admin Tools</h2>
<br/><br/><br/><br/>
<%#page import="java.sql.ResultSet"%>
<%
boolean def_admin = false, def_admin_changed = false;
conn.connect.main(null);
conn.dbc.main(null);
ResultSet rstools = conn.connect.st.executeQuery("select * from admins where uname='admin'");
if (rstools.next()) {
if (rstools.getString("uname").equals("admin") && rstools.getString("password").equals("123")) {
def_admin = true;
}
if (rstools.getString("uname").equals("admin") && !rstools.getString("password").equals("123")) {
def_admin_changed = true;
}
}
%>
<%if (def_admin == false) {%>
Add Default Admin Account :<br/>
<input type="button" value="Add" onclick="<% add_admin(); %>"/>
<% } else if (def_admin == true && def_admin_changed == false) { %>
Delete Default Admin Account :<br/>
<input type="button" value="Delete" onclick="<% delete_admin(); %>"/>
<% } else if (def_admin == true && def_admin_changed == false) { %>
The Default Admin Password Exists but the password has been changed<br/>
Do you still want to delete the Default Admin Account?<br/>
<input type="button" value="Even so, Delete it" onclick="<% delete_admin(); %>"/>
<% }%>
<div id="tools_error"></div>
<%!
boolean insert_success = false;
void add_admin() {
try {
int Urows;
Urows = conn.connect.st.executeUpdate("insert into admins(uname,password) values('admin','123');");
if (Urows == 1) {
insert_success = true;
} else {
insert_success = false;
}
%>
<script>
(function () {
boolean i_s = "<%=insert_success%>";
if (i_s == false) {
document.getElementById("tools_error").value = "There has been an error in Adding Default Admin";
}
});
</script>
<%!
} catch (Exception e) {
}
}
void delete_admin() {
}
%>
</div>
</body>
<jsp:include page="/basic/footer.jsp"/>
</html>
As you can see when the button is clicked I have made it to run the declared JSP functions. But when the JSP file is loaded the functions run automatically and the insert MYSQL query runs which automatically inserts the values given in the query.
I don't want it the functions add_admin() and delete_admin() to run automatically on load. Any suggestions?
The events in the webpage (onclick event for example) is executed client side when someone opens your webpage and clicks the button. The JSP scriplets are executed when the webpage is opened and their result is the actual page that the client receives. So your method executes ONLY when the page is loaded (and the JSP is compiled). The java code is not even visible in the webpage you generate. If you open it in browser and check the source you will see what I mean.
TL;DR: You can't
Your Java code is executed once, when the page is loaded. The page is not on the server anymore, so you can't use its back-end capabilities. Otherwise, that would mean someone reewriting your HTML could make your page execute any code on your back-end.
Once your page is loaded, all there is on it is HTML and Javascript (CSS if you want to bicker).
Here is my index.jsp
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id="ContentLoader" class="com.content.ContentLoader" scope="session"/>
<jsp:setProperty name="ContentLoader" property="*"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Content Loader</title>
</head>
<body>
<h1>Content API: Loader</h1>
<a>Select a CSV file from your computer.<br>
Enter the API key and secret for your account<br>
Click submit when you are ready to load the products!! <br>
</a>
<br>
<form action="index.jsp" method="GET">
API Key: <input type="text" name="api_key">
<br>
API Secret: <input type="text" name="api_secret" />
<br>
Choose CSV File: <input type="file" name="csv_file" />
<br>
<input type="submit" value="Submit To Content API" />
</form>
<br>
This is feedback from the program<br>
**strong text**
You entered<BR>
Name: <%= ContentLoader.getApi_key() %><BR>
Email: <%= ContentLoader.getApi_secret() %><BR>
Age: <%= ContentLoader.getCsv_file() %><BR>
</body>
</html>
When I hit the submit button, I want to pass the 3 strings to the Java application.
(key, secret, and the contents of my csv)
Right now I get "The requested resource is not available" error (HTTP Status 404)
Here is my ContentLoader.java
package com.content;
public class ContentLoader {
private String api_key = "testKey2";
private String api_secret= "testSecret";
private String csv_file = "testFileString";
public ContentLoader() {
// TODO Auto-generated constructor stub
}
public void setApi_key(String api_key) {
this.api_key = api_key;
}
public void setApi_secret(String api_secret) {
this.api_secret = api_secret;
}
public void setCsv_file(String csv_file) {
this.csv_file = csv_file;
}
public String getApi_key() {
return api_key;
}
public String getApi_secret() {
return api_secret;
}
public String getCsv_file() {
return csv_file;
}
}
The ContentLoader.java above is supposed to send and receive strings from the JSP form. When the submit button is hit, I need the 3 strings to pass to Application.java, and the main argument needs to be executed. Right now this is not happening, and I don't understand why. Thanks!!!!
This is my Application.java
import java.io.IOException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class Application implements ServletContextListener{
#Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("Tomcat just started");
}
#Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("Tomcat just stopped");
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.out.println("hi!! Your program is executing");
/**
//Null Credentials
String apiKey = "000";
String apiSecret = "000";
}
}
Web applications doesn't work like that, and Servlet don't need a main method to work, actually it doesn't know how to use it, instead of that you can use http request from your java application (main methode) to call a jsp file that returns 3 paramteres (in xml format or json) and you can pick those parametres and use them in your application as you want.
I am a novice in jsp. i am trying to access values from my java class into my jsp page. i went thru a lot of pages and implemented a lot of stuff and i thing i made it all into a mess.
this is my dao class method
public DisplayDO Display(DisplayDO disDo)throws Exception
{
System.out.println("inside dao display");
Connection conn = null;
try{
conn = DbConnection.getConn();
}
catch(Exception e)
{
e.printStackTrace();
}
Statement statement = null;
try{
statement = conn.createStatement();
}
catch(SQLException e)
{
e.printStackTrace();
}
System.out.println("dbconnection established");
int userid=disDo.getUserid();
try
{
System.out.println("inside dao try");
System.out.println("userid = "+userid);
String str= "Select address_id from user where user_id =910";
//+userid;
PreparedStatement ps= conn.prepareStatement(str) ;
ResultSet rs=ps.executeQuery(str);
int address1=0;
while (rs.next())
{
address1= rs.getInt(("address_id"));
}
int addressid = 0;
addressid = address1;
System.out.println("values of addressid= "+ addressid +"address1= "+ address1);
System.out.println("query execution successfull");
str="select name,street_name,city,gender,reg_date from user,address,registeration where user.address_id="+addressid+" && address.address_id= "+addressid+" && registeration.user_id="+userid+" ;";
rs=ps.executeQuery(str);
UserDO user = new UserDO();
RegDO regDO = new RegDO();
AddressDO addressDO = new AddressDO();
while(rs.next())
{
user.setName(rs.getString("name"));
System.out.println("name= "+rs.getString("name"));
addressDO.setStreetname(rs.getString("street_name"));
System.out.println("street_name= "+rs.getString("street_name"));
addressDO.setStreetname(rs.getString("city"));
System.out.println("city = "+rs.getString("city"));
regDO.setGender(rs.getString("gender"));
System.out.println("gender = "+rs.getString("gender"));
regDO.setReg_date(rs.getString("reg_date"));
System.out.println("reg_date = "+rs.getString("reg_date"));
System.out.println("date using getter"+regDO.getReg_date());
}
}
catch(Exception e)
{
e.setStackTrace(null);
}
return disDo;
}
THis code is working perfectly and i am getting the values in the console..
the following code is my jsp page.
<%#page import="java.lang.String" %>
<%#page import="java.io.*" %>
<%#page import="com.quinoid.e_tender.databean.RegDO"%>
<%#page import="com.quinoid.e_tender.databean.AddressDO"%>
<%#page import="com.quinoid.e_tender.databean.UserDO"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>
<h1>Your Values</h1>
<%
System.out.print("inside display_1");
UserDO user=(UserDO)request.getAttribute("name");
out.println(user);
AddressDO add=(AddressDO)request.getAttribute("add");
RegDO reg=(RegDO)request.getAttribute("reg");
String name,street_name,city,gender,reg_date;
name=(String)request.getAttribute("user");
/*street_name=add.getStreetname();
city=add.getCity();
gender=reg.getGender();
reg_date=reg.getReg_date();
*/%>
<!-- <script type="text/javascript">
/*document.getElementById("name").innerHTML =(String)request.getAttribute("name");
document.getElementById("street_name").innerHTML = add.getStreetname();
document.getElementById("city").innerHTML = add.getCity();
document.getElementById("gender").innerHTML = reg.getGender();
document.getElementById("reg_date").innerHTML = reg.Reg_date(); */
</script> -->
<form name="innerHTML" method ="post">
<table border="1">
<tr>
<th> Name </th>
<th>Street Name</th>
<th> City </th>
<th> Gender </th>
<th>Registration date</th>
</tr>
<tr>
<td id=name> </td>
<td id=street_name> </td>
<td id=city> </td>
<td id=gender> </td>
<td id=reg_dae> </td>
</tr>
</table>
</form>
</body>
</html>
Iam trying to display the values of "name","street_name","city","gender","reg_date" in the table and failed miserably..
This is the result in my console
the servlet is in user display
In display method
userid= 910
inside dao display
dbconnection established
inside dao try
userid = 910
values of addressid= 118address1= 118
query execution successfull
name= anjana
street_name= nagar
city = tvm
gender = F
reg_date = 1990-08-15
date using getter1990-08-15
exiting display method
inside display_1
inside display_1
do help.. thanks in advance..
Set this attribute in 'request' in your servlet before forwarding to the jsp page.
UserDO user=(UserDO)request.getAttribute("name");
out.println(user);
AddressDO add=(AddressDO)request.getAttribute("add");
RegDO reg=(RegDO)request.getAttribute("reg");
String name,street_name,city,gender,reg_date;
name=(String)request.getAttribute("user");
set these values as
request.setAttribute("name",userDo); //UserDo instance.
request.setAttribute("add",addressDo);//AddressDO instance. and so on...
And then forward it
request.getRequestDispatcher("xxxx").forward(request,response);//xxxx is jsp page you are forwarding.
And get the value in jsp using
<%=xxx%>//xxx is the reference as **name**, **city**..
try with following code,
document.getElementById("street_name").innerHTML = '<%=add.getStreetname()%>';
document.getElementById("city").innerHTML = '<%=add.getCity()%>';
document.getElementById("gender").innerHTML = '<%=reg.getGender()%>';
document.getElementById("reg_date").innerHTML = '<%=reg.Reg_date()%>';
You must set your attributes to the request object and than forward the servlet class to JSP, where you can getAttribute from the Request object as it is an implicit object in the JSP.
But when getAttribute is called you must cast it to appropriate Object type.
And Make sure you are not using Redirect mechanism, otherwise your Request object will be null because it is a new object for JSP. Only in Forward Mechanism the request object is copied to the new request object on JSP.
You can use the examples available on Net and as well
Pradeep Kr Kaushal example.
I have written this to just let you inform about Forward and Redirect mechanism effects on Request object.
You are not calling you dao class Display method anywhere.
In your dao class, change the method like so (method names in java start with a lowercase letter by convention):
public DisplayDo display() throws Exception { ...
At the end of the method, after populating them from the ResultSet, initialize a DisplayDo object and set the userDo, addressDo and regDo objects:
DisplayDO displayDo = new DisplayDO();
displayDo.setRegDo(regDO);
displayDo.setAddressDi(addressDO);
displayDo.setUserDo(userDO);
In your jsp, add the import for your dao class (assuming it is called DisplayDao):
<%#page import="com.quinoid.e_tender.dao.DisplayDao"%>
Add this to your jsp to create a new DisplayDao and access its display() method:
<% DisplayDao displayDao = new DisplayDao();
DisplayDo displayDo = displayDao.display();
UserDO userDo = displayDo.getUserDo();
...
%>
You can then output values like this:
<td id="name"><%= userDo.getName() %></td>
I have a Person model attribute that contains a list of emails.
I've created some JavaScript code that deletes elements from an HTML list of emails. This is pure JavaScript client side code, no AJAX call.
After submitting, I don't understand why I get all the emails in the corresponding #Controller method, even the ones that were deleted in the HTML.
Can anyone please explain?
JSP
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<link rel="stylesheet" href="<c:url value="/styles/resume.css"/>" type="text/css"></link>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"></link>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="/resume/js/jquery.editable-1.0.1.js"></script>
<title>Resumes manager</title>
<script>
$(document).ready(function() {
$('.trash').click(function() {
$(this.parentNode).remove();
});
});
</script>
</head>
<body>
<h1>Personal data</h1>
<form:form modelAttribute="person" action="/resume/person/edit/save" id="personForm" method="post" >
<table>
<tr>
<td>Email addresses:</td>
<td colspan="4">
<ol id="emails">
<c:forEach items="${person.emails}" varStatus="status">
<li><form:hidden path="emails[${status.index}].order" class="emailsDisplayOrder"></form:hidden><form:input path="emails[${status.index}].label"></form:input><form:input type="email" path="emails[${status.index}].value"></form:input><input type="image" src="/resume/images/trash.png" class="trash" value="${status.index}"></input></li>
</c:forEach>
</ol>
</td>
</tr>
</table>
</form:form>
</body>
</html>
Controller
#Controller
#SessionAttributes(types={Person.class}, value={"person"})
public class PersonController {
private final static String PERSON_VIEW_NAME = "person-form";
private ResumeManager resumeManager;
#Autowired()
public PersonController(ResumeManager resume) {
this.resumeManager = resume;
}
#InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
#RequestMapping(value="/person/edit/save")
public String save(#ModelAttribute(value="person") Person p, BindingResult result, SessionStatus status) {
new PersonValidator().validate(p, result);
Collections.sort(p.getEmails()); //this collection still contains client-side dropped objects
this.resumeManager.savePerson(p);
return PERSON_VIEW_NAME;
}
}
Explanation
When you load a page with <form:form modelAttribute="person" ...>, there are two cases :
case 1 : if person doesn't exist, it creates an empty Person
case 2 : if person already exists, it uses it
In all cases, when a page is loaded, there is an existing person.
When you submit a form, Spring MVC updates this existing person only with the submitted information.
So in case 1, if you submit email 1, 2, 3 and 4, Spring MVC will add 4 emails to the empty person. No problem for you in this case.
But in case 2 (for example when you edit an existing person in session), if you submit email 1 and 2, but person has already 4 emails, then Spring MVC will just replace email 1 and 2. Email 3 and 4 still exist.
A possible solution
Probably not the best one, but it should work.
Add a remove boolean to the Email class :
...
public class Email {
...
private boolean remove; // Set this flag to true to indicate that
// you want to remove the person.
...
}
In the save method of your controller, remove the emails that have remove set to true.
Finally, in your JSP, add this hidden field :
<form:hidden path="emails[${status.index}].remove" />
And tell your Javascript to set the input value to true when the user clicks to delete the email.
Alternate solution to Jerome Dalbert one
Jerome's solution should work (thanks again for clear answer and solution), but I didn't want to modify business model.
So here is the way I found out: mark HTML elements to remove using java-script and actually remove it using ajax calls at form submit (I initially avoided ajax to keep model unchanged until user submits, but this solutions preserves that requirement).
JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<link rel="stylesheet" href="<c:url value="/styles/resume.css"/>" type="text/css"></link>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"></link>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="/resume/js/jquery.editable-1.0.1.js"></script>
<title>Resumes manager</title>
<script>
$('.sortable').sortable({
update: function(event,ui) {
var liElements = this.getElementsByTagName('li');
$(liElements).each(function(i, liElement) {
var orderElements = liElement.getElementsByClassName('order');
$(orderElements).each(function (j, orderElement) {
orderElement.value = i;
});
});
}
});
$('.trashable').click(function() {
$(this.parentNode.childNodes).each(function(index, element) {
if(element.src.match(/trash.png/) != null) {
element.src = '/resume/images/back.png';
this.parentNode.className = 'trashed';
} else if(element.src.match(/back.png/) != null) {
element.src = '/resume/images/trash.png';
this.parentNode.className = '';
} else {
element.disabled = !element.disabled;
}
});
});
function trash(element) {
var sfx = element.alt;
var lnk = ('/resume/person/edit/').concat(sfx);
$.ajax({
url: lnk
});
}
$('#personForm').submit(function() {
var trashed = $(this).find('.trashed');
$(trashed).each(function(index, element) {
var img = $(element).find('.trashable');
var tmp = $(img)[0];
trash(tmp);
});
});
});
</script>
</head>
<body>
<h1>Personal data</h1>
<form:form modelAttribute="person" action="/resume/person/edit/save" id="personForm" method="post" >
<table>
<tr>
<td>Email addresses:</td>
<td colspan="4">
<ol class="sortable">
<c:forEach items="${person.emails}" varStatus="status">
<li><form:hidden path="emails[${status.index}].order" class="order"></form:hidden><form:input path="emails[${status.index}].label"></form:input><form:input type="email" path="emails[${status.index}].value"></form:input><img src="/resume/images/trash.png" class="trashable" alt="dropEmail/${person.emails[status.index].id}"></img></li>
</c:forEach>
</ol>
</td>
</tr>
<tr><td colspan="5"><form:button name="save" value="${person.id}">${person.id == 0 ? 'save' : 'update'}</form:button></td></tr>
</table>
</form:form>
</body>
</html>
Controller:
#Controller
#SessionAttributes(types={Person.class}, value={"person"})
public class PersonController {
private final static String PERSON_VIEW_NAME = "person-form";
private ResumeManager resumeManager;
#Autowired()
public PersonController(ResumeManager resume) {
this.resumeManager = resume;
}
#InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
#RequestMapping(value="/person/edit/{id}")
public String edit(#PathVariable("id") long personId, Model model) {
Person p = this.resumeManager.getPersonById(personId);
if(p != null) {
model.addAttribute("person", p);
return PERSON_VIEW_NAME;
} else {
return "redirect:/";
}
}
#RequestMapping(value="/person/edit/save")
public String save(#ModelAttribute(value="person") Person p, BindingResult result, SessionStatus status) {
new PersonValidator().validate(p, result);
Collections.sort(p.getEmails());
this.resumeManager.savePerson(p);
return PERSON_VIEW_NAME;
}
#RequestMapping(value="/person/edit/dropEmail/{id}")
#ResponseBody
public void dropEmail(#ModelAttribute(value="person") Person p, #PathVariable("id") long id) {
int i = 0;
for(Email e : p.getEmails()) {
if(e.getId() == id) {
p.getEmails().remove(i);
break;
}
i++;
}
}
}
Iam new in Jax-rs.I have doubt to passing a data from html page into webresource method.In the html page contains fruitid & fruitname.How to convert these two attributes into Java object i.e.,FruitBean.May be we can use jaxb implemenation.But i don't know further steps to implemation in between html page & web resource method.
Please check the below code snippet for fruitbean
#XmlRootElement(name="fruitbean")
public class FruitBean {
private long id;
private String name;
#XmlAttribute
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#XmlAttribute
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And web resource method passing pararmenter as FruitBean object.check the below method.
#POST
#Path("loadObject1")
#Consumes(MediaType.APPLICATION_XML)
public void loadObject1(FruitBean bean){
System.out.println("Fruit ID" + bean.getId() + " Name" + bean.getName());
}
Even I already tried to search on this issue.But i can't understand.Please help me.
Update :-
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test Jax-RS Object</title>
</head>
<body>
<form action="services/fruitstore/loadObject1" method="POST" enctype="application/x-www-form-urlencoded">
<table>
<tr>
<td>ID:</td>
<td><input type="text" name="id"></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td><input type="submit" Value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
#POST
#Path("loadObject1")
#Consumes(MediaType.APPLICATION_JSON)
public void loadObject1(String bean){
FruitBean bean = new com.google.gson.Gson().fromJson(bean, FruitBean.class);
System.out.println("Fruit ID" + bean.getId() + " Name" + bean.getName());
}
from servers send POST request with data JSON.stringify(fruitBean)
for example send request using jQuery/ajax
var fruitBean
fruitBean.id = 1
fruitBean.name = 'name'
$.ajax({
type: 'POST',
url: 'context-path/loadObject1',
data : JSON.stringify(fruitBean)
});
I have no answer on your question. But as I have find binding between JaxB bean and HTTP-request is not implemented yet in Jersey RESTful Web services - it has just someone hack (but without JaxB)
And that is more-or-less advanced related ability in RESTEasy JAX-RS