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
Related
I'm building a simple web service with spring and thymeleaf. That's the code for now:
Controller:
package com.Basi.CheBBellaEmittente.Pages.Control;
#Controller
public class SimpleController {
#GetMapping("/nuovo-utente")
public String viewInserisciUtente(Model model){
model.addAttribute("nuovoUtente", new Utente());
return "nuovo-utente";
}
#PostMapping("/nuovo-utente")
public void memorizzaUtente(#ModelAttribute Utente utente){
System.out.println(utente.getId());
}
}
Model:
package com.Basi.CheBBellaEmittente.Pages.Model;
public class Utente {
private String id;
private String citta=null;
private String genere;
private String data_nascita=null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCitta() {
return citta;
}
public void setCitta(String citta) {
this.citta = citta;
}
public String getGenere() {
return genere;
}
public void setGenere(String genere) {
this.genere = genere;
}
public String getData_nascita() {
return data_nascita;
}
public void setData_nascita(String data_nascita) {
this.data_nascita = data_nascita;
}
}
html page:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Inserisci un nuovo utente</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="#{/nuovo-utente}" th:object="${com.Basi.CheBBellaEmittente.Pages.Model.Utente}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>Città : <input type="text" th:field="*{citta}" /></p>
<p>Genere: <input type="text" th:field="*{genere}" /></p>
<p>Data nascita: <input type="text" th:field="*{data_nascita}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
and the error:
2018-09-21 16:51:40.668 ERROR 3132 --- [nio-8080-exec-1] org.thymeleaf.TemplateEngine : [THYMELEAF][http-nio-8080-exec-1] Exception processing template "nuovo-utente": Exception evaluating SpringEL expression: "com.Basi.CheBBellaEmittente.Pages.Model.Utente" (template: "nuovo-utente" - line 9, col 51)
So, what can I do to handle this situation? I don't know what's wrong with this, is a very simple code. Can you give me some advice? I'm supposing is some fold packages issue but I can't understand what.
Since your model attribute is named nuovoUtente -- model.addAttribute("nuovoUtente", new Utente());, that's what you should be using as your th:object.
<form action="#" th:action="#{/nuovo-utente}" th:object="${nuovoUtente}" method="post">
An expression like this: ${com.Basi.CheBBellaEmittente.Pages.Model.Utente} will be interpreted as: com.getBasi().getCheBBellaEmittente().getPages().getModel().getUtente() -- which doesn't make sense.
In your controller you set the name of your model attribute to nuovoUtente so you have to do the next on the html:
<form action="#" th:action="#{/nuovo-utente}" th:object="${nuovoUtente}" method="post">
You want to create and submit a form. On the #GetMapping and #PostMapping you have to set different urls.
For example:
#GetMapping(/nuevo-utente-form) and #PostMapping(/nuevo-utente)
In the nuevo-utetente-form.html you write the code of the form, and in nuevo-utente.html you write the code for accept the form.
th:object="${com.Basi.CheBBellaEmittente.Pages.Model.Utente}"
it should point to actual object instance that you pass in your view model, not its class, so probably
th:object="${utente}"
is what it should be.
I have this simple code: This is my controller class where i redirecting to a page
#Controller
public class SimpleController {
#GetMapping("/nuovo-utente")
public String viewInserisciUtente(Model model){
model.addAttribute("nuovoUtente", new Utente());
return "nuovo-utente";
}
#PostMapping("/nuovo-utente")
public void memorizzaUtente(#ModelAttribute Utente utente){
System.out.println(utente.getId());
}
}
This is model class.
public class Utente {
private String id=null;
private String citta=null;
private String genere=null;
private String data_nascita=null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCitta() {
return citta;
}
public void setCitta(String citta) {
this.citta = citta;
}
public String getGenere() {
return genere;
}
public void setGenere(String genere) {
this.genere = genere;
}
public String getData_nascita() {
return data_nascita;
}
public void setData_nascita(String data_nascita) {
this.data_nascita = data_nascita;
}
}
and My html page with thymeleaf is like :
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Inserisci un nuovo utente</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="#{/nuovo-utente}" th:object="${nuovoUtente}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>Città : <input type="text" th:field="*{citta}" /></p>
<p>Genere: <input type="text" th:field="*{genere}" /></p>
<p>Data nascita: <input type="text" th:field="*{data_nascita}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
So, as I said into the title, this simple code for a form give me error when I try to submit the form by post request. The error is the above:
Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "nuovo-utente" - line 10, col 32)
What can you say to me? Some help will be appreciate
You have to use diferent html and urls. One to create the form and another one to submit the form. You are using the same url.
First of all in your html page change
<html xmlns:th="http://www.thymeleaf.org">
to
<html xmlns:th="http://www.w3.org/1999/xhtml">
And write your controller class like
#PostMapping("/nuovo-utente")
public String memorizzaUtente(#ModelAttribute("nuovoUtente") Utente utente) {
System.out.println(utente.getId());
return "any page";
}
}
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).
This question already has answers here:
What causes "java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute"?
(7 answers)
Closed 6 years ago.
Here is form.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Student</title>
</head>
<body>
<form:form action="addStudent" commandName="addStudent" method="post">
<table>
<tr>
<td><form:label path="name">Name:</form:label></td> <td><form:input path="name"/></td>
</tr>
<tr>
<td><form:label path="email">Email:</form:label></td> <td><form:input path="email"/></td>
</tr>
<tr>
<td><form:label path="age">Age:</form:label></td> <td><form:input path="age"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"></td>
</tr>
</table>
</form:form>
</body>
</html>
Here is controller method
#RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String addStudent(#ModelAttribute("addStudent") Student student) {
System.out.println("Saving Info...");
System.out.println("Name: "+student.getName());
System.out.println("Email: "+student.getEmail());
System.out.println("Age: "+student.getAge());
return "form";
}
Here is Student model
public class Student {
private String name;
private String email;
private int age;
private int id;
public Student() {
super();
}
}
I guess there is no need for web.xml or dispatcher-servlet.xml . Every thing is correctly binded, I mean commandName is right in jsp. ModelAttribute is correct in controller then why contol is not reaching controller? :(
Please help. I have already wasted half of the day on this.
PS:I am new to Spring and stackoverflow.
EDIT:
after suggestions, my code look like this:
controller method:
public String addStudent(#ModelAttribute("student") Student student, BindingResult result) {
jsp form:
<form:form action="addStudent" commandName="student" method="post">
EDIT:
resolved it myself
added this method for modelattibute
#ModelAttribute("student")
public Student getForm() {
return new Student();
}
As long as the commandName and modelAttribute String are the same that's fine.
likewise im a newbie to Spring and stuff..
but I'm guessing it cant find the correct request mapping since you have /addStudent in the request mapping and just addStudent in the form action. that is fine if the form is in context root.
could you try checking that out?
Also please add a BindingResult object in the arg list
public String addStudent(#ModelAttribute("addStudent") Student student, BindingResult result)
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.