Restful web service using #formparam to produce xml file(marshalling) - rest

I have a basic html form with a text box and a submit button
I am interested in creating a restful web service wherein I will be exposing a method
of MY EJB(from a working search based application) to retrieve values from the database..
I will be using the value entered in the text box as a where clause of SQL query in the EJB method of my application.
I am new to restful service.
I want to generate a xml file on click of the submit button
Any suggestions..?
The IDE I am using is net beans.

If you want to retrieve data, a simple GET request should be enough.
HTML form
<form action="/path/to/the/resource" method="GET">
<input type="text" name="query" id="query"/>
<input type="submit" value="Submit Query/>
</form>
JAX-RS Resource
#Path("/path/to/the/resource")
public class MyResource {
#GET
#Produces("application/xml")
public Response query(#QueryParam("query") String query) {
// retrieve values from the database using the query
MyJaxbAnnotatedDataClass result = ...;
return Response.ok(result).build();
}
}
JAXB annotated class
#XmlRootElement
public class MyJaxbAnnotatedDataClass {
// many fields, getters, setters with JAXB annotations
}

Related

Consume RESTful Service from form post

I've built a RESTful service with Spring (java annotation based configuration) which I can execute successfully via Curl. I'm trying to submit files via a HTML Form too, however that's not working.
#RequestMapping(path = "/upload", method = RequestMethod.POST)
public String handleFileUpload(#RequestPart(value = "file") MultipartFile file,
RedirectAttributes redirectAttributes) {
logger.info("POST '/upload'");
storageService.store(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
return "redirect:/";
}
And I'm submitting a file via Curl as follows:
curl -i -H "Content-Type: multipart/*; boundary=------------BOUNDARY--" -X POST --noproxy localhost, localhost:8080/upload -F "file=#test.txt"
Even though my form submission has an input of type file, with the name file, I get this error via a HTML form
org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present
From what I've been investigating, it would seem as if the controller would expect a Model Attribute when the file is submitted via HTML Form, so what could be a good practice to resolve this? Include a controller parameter for a Model Attribute, which would be checked for null value (to distinguish between html form or other submission methods), or would a sort of Proxy controller between the HTML Form and the RESTful service be better?
The service looks good. It works fine for me on both CURL and HTML form submit.
Here is my form. Please try using this.
<html>
<head>
<title>Post Tool</title>
</head>
<body>
<h1>Sample Requests</h1>
<h2>Upload Document</h2>
<form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data">
Choose a file : <input type="file" name="file" multiple/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
After more research I got to know that the commons multi part resolver doesn't fare well with the new versions of spring boot. It struggles obtaining POST parameters from forms.
One solution is to use the StandardServletMultipartResolver implementation of the MultipartResolver interface!

Spring form errors with multiple identical forms on the same page

I am printing an arbitrary number of identical forms on a page using Spring's <form:form tag, and I need a way to distinguish between them, because form errors of one form are now printed on all forms.
Currently all the identical forms are bound to the same, single backing object. That works fine, because a user can only submit one form at a time.
I am using Spring validation to validate form fields. When one of the fields has an error (let's say 'name' is empty) than the error message is printed under the 'name' field of all forms.
Obviously, I need some way to allow Spring to distinguish between the forms, but how?
Some example code:
This Spring webflow definition creates a ClientFormBacking object to back the client forms. And it submits a form POST to the bindAndValidate method, which calls the validator.
<webflow:var name="clientFormBacking" class="com.example.ClientFormBacking"/>
<webflow:view-state id="list" view="clients" model="clientFormBacking">
<webflow:on-entry>
<webflow:evaluate expression="contextParameterManager.findAll()" result="flowScope.clients"/>
</webflow:on-entry>
<webflow:transition on="update-client" to="list">
<webflow:evaluate expression="clientBinder.bindAndValidate(flowRequestContext)"/>
<webflow:evaluate expression="clientService.saveOrUpdate(flowScope.clientsPageBacking)"/>
</webflow:transition>
</webflow:view-state>
Print an arbitrary number of identical forms with a name field and name error field in JSP:
<c:forEach items="${clients} var="client">
<form:form commandName="clientFormbacking">
<form:input path='name' value='${client.name}'/>
<form:errors path="name" cssClass="input-error" />
</form:form>
</c:forEach>
The validator that rejects the 'name' field:
ClientValidator implements Validator {
public void validate(Object target, Errors errors) {
// Problem here! There are multiple <form:errors path='name'/> tags....
errors.rejectValue("name", "validation.error.name.empty");
}
}

How implement class to have tag form:date by extends InputTag with Spring

I want to use the tag "form:date" on a spring form
<form:form id="saveAction" commandName="commandName" action="/save" method="post">
<form:errors path="name" cssClass="error"/>
<form:date path="name" cssStyle="input date" cssErrorClass="inputError"/>
</form>
How can I create and implement a class who extends org.springframework.web.servlet.tags.form.InputTag to can use form:date to generate a input type="date".
I use Spring web mvc 2.5.5.
What is the purpose for this when lots of css classes that seamlessly converts an input as a date for you?

Spring #ModelAttribute doesn't care about commandName

JSP:
<form:form commandName="editWeather" method="post" action="../edit">
<!-- Input fields -->
<input type="submit" value="Submit">
</form:form>
And this is how I get the model in Spring:
#ModelAttribute("DONTGIVEADAMN") Weather weather
And I can still use the weather to do my operations and it works great, for example:
weatherService.editWeather(weather);
My question is...Why does this work?
Model attribute name doesn't matter when binding data received from a form (because names of form fields correspond to the names of fields of the model object), it matters only when rendering a form.
I particular, when model attribute name in your POST handler method doesn't match the commandName in the form, you will be able to receive the data, but won't be able to redisplay a form with validation errors.
its matching the class type (or interface), not the name of the variable/parameter; and the specified request mapping/method signature must be correct.

Using a file form field with a Java servlet

I am tring to retrieve a filename or the file itself for use in a java servlet (from a web form).
I have a file form field:
<form enctype="multipart/form-data" method="post" action="SaveDictionary.do">
<label>
<input type="file" name="dictionary_file" id="dictionary_file" />
<br />
</label>
<label>
<br />
<input type="submit" name="saveDic" id="saveDic" value="Save Dictionary" />
</label>
</form>
I wanto then process it in my servlet, what do I do to process this - for a normal text field I would use something like
String myValue = (String) request.getParameter("parameter_name");
Assuming I have this class, what do I put in the doPost() method to get either the file path or the actual file contents.
#SuppressWarnings("serial")
public class SaveDictionary extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
// I can't work out what goes here, the same
// String myValue = (String) request.getParameter("parameter_name"); doesn't work
response.sendRedirect("dictionary.jsp");
}
}
Multipart/form-data encoded requests are not supported by the default servlet API. You basically need to parse the request body yourself based on the HttpServletRequest#getInputStream(). But that's a precious and tedious work. You don't want to do that if you're already asking this question here at SO. Fortunately there's already a robust, thoroughly developed and maintained API out for that, the Apache Commons FileUpload API. It's in fact easy to use. You can find examples in their User Guide and tips&tricks in their FAQ.
You can also wrap it in a Filter which does all the parsing work and puts all the parameters back in the request, so that it's all transparent in the servlet code and you can continue using HttpServletRequest#getParameter() and consorts the usual way. Uploaded files can then be obtained as request attributes. Here's a basic example.
Hope this helps.