Spring MVC + jsp: How to receive a list of items in controllers? - html

The requirement is letting users to upload a list of tickets with something like:
#RequestMapping(value="/tickets", method=RequestMethod.POST)
public void uploadTickets(
#RequestBody List<Ticket> tickets) {
// Do something with the list of tickets
}
I know how to upload a single ticket. I just need to create a html form with three fields (section, row, seat) and a submit button. Then spring will automatically convert the uploaded form to a Ticket object. But I am not sure how to upload a list of Tickets with Spring controllers. Any help? Thanks!

This depends on your configuration. Assuming a normal spring configuration.
You normally upload a single ticket with a json request
{ "section":"", "seat":"", "row":"" }
To get the list of tickets, just use a json array.
[
{ "section":"", "seat":"", "row":"" },
.......,
{ "section":"", "seat":"", "row":"" }
]
To get the data into this format, it of course depends on the front end. You might need to do some javascript on the frontend to get it into this format.

you can just put it in model object and get the data from the model object as given below example
#RequestMapping(value="/tickets", method=RequestMethod.POST)
public String uploadTickets(Map<String, Object> model) {
Ticket t = new Ticket();
model.put("ticket", t);
return "page";//return page or redirect.
}

Related

Reusing the same Domain Object in For Get and POST

Assuming I have a student Object
public class Student{
private long id;
private string name;
private List<string> courses
}
In a typical Get request, to get a student I send the Student object to the client.
In the case of a PUT request to modify the Student object by adding or removing a course or a POST request to create a Student record, I only need to receive from the client the student.id and the list of courses.
My question is, Can I send back the same Student object from the client in the PUT or POST request without including the name or maybe have name=null?
Or should I create a separate domain object that will be sent by the client for example:
public class StudentReponse
{
private long id;
private List<string> courses;
}
I guess my generic question is, should we separate the Request and response objects in Rest API? or for code re usability try to use the same domain objects for both directions?
should we separate the Request and response objects in Rest API?
Yes - it allows to evolve both the request and response independently.
If you follow REST practices when a create is issued, you should return 201 - created and the ID of the newly created object.
If the client requires details about it, the client can use the ID + GET to get the full resource representation.
Also consider not exposing the domain objects directly through REST.
For example having a domain entity object - it will probably have some fields related to persistence layer like database Id, createdOn, createdBy - etc. Those fields should not be sent to the client. Use a simple StudentDto (StudentResponse, StudentResponseDto whatever you want to call it) representation, which holds only those fields, which are of interest to the client.
Keeping domain and response objects separate also gives you the ability to evolve them separately or change the data representation.
Imagine you have a JPA Entity and you use both JPA and Jackson annotations in the same class - it's very messy and hard to read and maintain.
Update:
If you're using the same object to be modified by the client and sent back to the server, I guess you could reuse it and model it like this:
get
#GetMapping("/students/{id}")
public StudentDto getStudent(#PathVariable long id) {
return studentService.get(id);
}
update (replace)
#PutMapping("/students/{id}/")
public ResponseEntity updateStudent(#PathVariable long id, #RequestBody StudentDto student) {
return new ResponseEntity(studentService.replaceStudent(id, student), HttpStatus.OK);
}
OR
update (partial update)
#PostMapping("/students/{id}/")
public ResponseEntity updateStudent(#PathVariable long id, #RequestBody StudentDto student) {
return new ResponseEntity(studentService.updateStudent(id, student), HttpStatus.OK);
}

How to create angularjs springboot application that stores data to a mysql database. using json

I'm kinda stuck on this topic.
This is what i already found out.
A good tutorial was :
Using MySQL in Spring Boot via Spring Data JPA and Hibernate
http://blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/
I also found some information how to make single page application with hsqldb.
But i really want to create something that permanent saves the users data to the database using mysql.
But in order to use angular http i need json. Can i convert the urls like
/create?email=[email]&name=[name]
To json how should i proceed. Does anyone knows good tutorials on this. Or are there better way's to proceed.
The simplest/handy way to consuming JSON with Spring Boot is using a Java class that resembles your JSON (https://stackoverflow.com/a/6019761).
So, you can follow the tutorial you linked, then use a controller like this one to handle JSONs:
#RestController
public class UserController {
#RequestMapping(
value = "/user/create",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> createUser(#RequestBody User user) {
try {
// Handle the User object here
userDao.save(user);
}
catch (Exception ex) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.OK);
}
// ...
}
Receiving a JSON like this (at the url /user/create):
{email: "john#doe.com", name: "John Doe"}
An user will be saved in your database.
Responding with JSON
Moreover, if you want to send a response as JSON from your controller you should create a java object then send it back as response, within the ResponseEntity object.
For example, suppose to have this class:
public class SuccessDto {
private String success;
public SuccessDto(String success) {
this.success = success;
}
}
You can change your controller in this way:
public ResponseEntity<SuccessDto> createUser(#RequestBody User user) {
// ...
return new ResponseEntity<>(
new SuccessDto("true"),
HttpStatus.OK
);
}
and you will have this JSON as response
{success: "true"}
if you have already managed to use it with HSQLDB, it's juste a matter of database properties (like the JDBC URL) and schema initialization.
Can you provide the code sample of the controller, how you save the data (via a Repository or a simple DAO ?) and the application.properties

passing json data of webapi method from controller to view

I have data in my apicontroller in following way-
public class OutletPOCController : ApiController
{
OutletPOCContext db = new OutletPOCContext();
[System.Web.Http.ActionName("GetTabText")]
public TabTextModel GetTabText(int bizId)
{
var outlet = db.Info.Where(t => t.BizId == bizId).SingleOrDefault();
return new TabTextModel
{
HomeTab = outlet.BizHomeTabText,
AboutTab = outlet.BizAboutTabText,
TimingsTab = outlet.BizTimingsTabText,
};
}
And now i want to retrieve this data into my view. How shall i create view for this controller and pass the above data? What will be my action method? I am new to webapi and json. Any help is appreciable! Thanks in advance!
The API controller dosent really have views in the sense that you create a cshtml page that takes care of how you display your data. The purpose of the ApiController is simply to return data in the format that you want to consume it.
Basically the API exposes raw data to the web, you consume it in some way, and then display it..
I use something similar to this to load data dynamically into a web page.
Just a simple web api that returns data to the client.
public class APIController : ApiController
{
[HttpGet]
[HttpPost] // allow both post and get requests
public IEnumerable<String> GetData()
{
return new List<string>() { "test1", "test2" };
}
}
When you browse to the API method above it returns this xml data
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>test1</string>
<string>test2</string>
</ArrayOfstring>
Which I get using Jquery and do what I please with (http://api.jquery.com/jQuery.get/):
$.get("/api/GetData", function(data) {
alert("Data Loaded: " + data);
});
Examples of XML parsing with JS/Jquery:
http://tech.pro/tutorial/877/xml-parsing-with-jquery
http://www.kawa.net/works/js/jkl/parsexml-e.html
If you are simply looking to get data into a regular view and work with it there without going through javascript I wouldent use a webapi, but instead get the data in the controller and send it to the view for displaying (ASP MVC4 - Pass List to view via view model).
You can also check out the ViewBag container for passing random odd data to the view http://goo.gl/03JTR
On the off chance you really do want to render your data in a view, check this out: Web API - Rendering Razor view by default?

Spring json #ResponseBody - return a named variable

I have a Spring controller method that is correctly returning a collection of objects in the JSON to the client:
#RequestMapping(value="/admin/rawreads/unknowntags", method=RequestMethod.GET)
public #ResponseBody Collection<RawRead> getRawReadsWithUnknownTag() {
....
}
I'm trying to integrate a jQuery addon/plugin called DataTables. DataTables can handle the asynchronous request to fetch data and populate a table in the page for me, however it requires the data to be return in an array with a specific name "aaData" rather than the current format of :
[{"oid":149452,"date":1233076733000,"readerId":"811210008","recordNo":226,"tagCode":"0103A003C0","reader":null,"guard":null,"checkpoint":null},{"oid":149453,"date":1233076734000,"readerId":"8112100 .... etc]
Suggested return format for DataTables from the DataTable docs:
{
"sEcho": 1,
"iTotalRecords": "n",
"iTotalDisplayRecords": "n",
"aaData": [
[object1][object2].... etc
]
}
How can I change my Java method to return data in the format DataTables needs - a named array?
EDIT:
Tried putting vars into a HashMap serverside, gets a bit closer to what I need:
{"iTotalDisplayRecords":3050,"iTotalRecords":3050,"aaData":
[{"oid":149452,"date":1233076733000, ...<snip>},{...}]
}
Make a separate class in the correct format for data tables, having fields for sEcho, itotalrecords, ittotaldisplayrecords and then an array called aaData.
Then return this class via jason and that is then in your suggested format.
class TableDTO
{
int sEcho;
int iTotalRecords;
int itotalDisplayRecords;
array[] aaData;
}
Obviously assign data to these fields and proper accessors etc!
You must write one more TotalDisplayRecords class and it must incluse array oid class. After that, you return TotalDisplayRecords object.

spring3mvcportlet populate JSON dojo select

I am new to Spring mvc3 portlet and dojo. I am trying to populate select dropdown with JSON data when jsp is loaded. I want to use dojo and give ajax call to controller and return JSON when jsp is loaded. Any tips will be helpful.
#Controller
#RequestMapping("/yourController")
public class YourController
{
#RequestMapping(value="/combo/{id}", method=ReqestNethod.GET)
public String getDropDownData(#ParamValue("id") long id)
{
List<Combo> combos = commonDao.getCombos(id);
String json = JsonUtil.toJson(combos); // or whichever way you use
return json;
}
}
Send requests from dojo to this url
<your-context-path>/yourController/combo/1
where 1 is your combo id.
I haven't checked the syntax here.. Wrote it blind. You might get compilation errors.
I get data in below format
How do I populate dojoType="xwt.widget.form.FilteringSelect"
{"ValuesDTO": {"items": [{},{"default": {"size": 5},"int": 10,"string": "Product1","string": "Product1 ","string": "product3","string": "product4","string": "product5"}]}}
I am sending dat in bean--->DTO--->List