Image not being insert in spring boot - javascript

I am using spring boot and I have simple form ,where there is upload option to upload the image.
<form>
<div class="col-md-6">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" width="200" height="200" />
</div>
<button type="submit" id="btn-add" class="btn btn-primary btn-lg">Add Employee
</button>
</form>
When I upload the image,then it is changed into base 64 as below codes and it is manipulated in employee object and sent through AJAX post method.But I am getting error in spring boot side:
var imgObject;
$(document).ready(function() {
$("#imgInp").change(function() {
readURL(this);
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').attr('src', e.target.result);
console.log("aaaa");
imgObject = e.target.result;
console.log(imgObject);
}
reader.readAsDataURL(input.files[0]);
}
}
$('#btn-add').on('click', function() {
//stop submit the form, we will post it manually.
event.preventDefault();
console.log("hitted");
fire_ajax_submit();
});
});
function fire_ajax_submit() {
var employee = {
"iNumber": $("#iNumber").val(),
"fullName": $("#fullName").val(),
"joinedDate": $("#joinedDate").val(),
"position": $("#position").val(),
"reportsTo": $("#reportsTo").val(),
"cubicleNo": $("#cubicleNo").val(),
"jobType": $("#jobType").val(),
"imagObject": imgObject
};
console.log(employee);
$.ajax({
url: A_PAGE_CONTEXT_PATH + "/insert-emp",
method: "post",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(employee),
success: function(response) {
console.log(response);
alert("Successfully Saved!");
window.location.reload(true);
},
error: function(response) {
switch (response.status) {
case 409:
alert("error");
}
}
});
}
console.log(employee) is printed as:
The image is converted into base64.
I tried to insert the image using AJAX.So, my Rest Api is:
#RestController
public class EmployeeController {
#Autowired
private EmployeeService empService;
#PostMapping("/insert-emp")
#ResponseBody
public Employee createEmployee(#Valid #RequestBody Employee employee){
return empService.saveEmployee(employee);
}
}
My service class is:
#Service
public class EmployeeService {
#Autowired
private EmployeeRepository empRepository;
public Employee saveEmployee(Employee employee){
if(employee.getId()==0){
empRepository.save(employee);
}
else{
empRepository.save(employee);
}
return employee;
}
My repository class is:
#Repository
public interface EmployeeRepository extends JpaRepository<Employee,Integer> {
}
My model Employee.java class is:
#Entity
#Table(name = "employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotBlank
private String iNumber;
#NotBlank
private String fullName;
// #NotBlank
private String joinedDate;
#NotBlank
private String position;
#NotBlank
private String reportsTo;
#NotBlank
private String cubicleNo;
#NotBlank
private String jobType;
private byte[] imagObject;
public Employee() {
}
//all getters and setters
}
But I am getting error as:
w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `byte[]` from String "image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUEBAUEAwUFBAUGBgUGCA4JCAcHCBEMDQoOFBEVFBMRExMWGB8bFhceFxMTGyUcHiAhIyMjFRomKSYiKR8iIyL/2wBDAQYGBggHCBAJCRAiFhMWIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiL/wAARCAOWBmADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8]...[zUOSGGaKKfQfUUMSuR3NY3iCZ7WC3ky+3zQrBHKk8Hv9cUUUhMzv+Es8gLHLbsz/AN4P2/Kom8aQcj7NLke4ooplW0I9T1wvb20sbTQqZPm8vGTwcUtn4niS3WOaOVpAMMRg5P50UUE9BV8YWZyBDcDnH3V/xq3o2qLfmWP94SCWBfHQngUUUDGXGvwWskiSxSEx9SoH+NRr4hgctiKTAODwP8aKKQupONaiyN6Pg9MAf41Qi1mRb2Z3Zmi34CYHAoop20GbdvfLOrFVYY9ay4NUlW5l8470810C46YYj+lFFICWXUylwrHJiOBtxyDWgZRtVucHtRRTa0H0IzdBAcgmoReozHKtxRRSEthxuFwDtODQJAw70UUC6iH5Tx3prnauTk5oooH0IHnwxXHUAimbgeuaKKroJjzJ+74/WmRnI55zRRUCKMF68txIrqu0OVGOvBP+FXBz04ooprYZXEjNcNEcYA9KsoQqYxx0oopg9z//2Q==": Failed to decode VALUE_STRING as base64 (MIME-NO-LINEFEEDS): Illegal character ':' (code 0x3a) in base64 content; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `byte[]` from String "image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUEBAUEAwUFBAUGBgUGCA4JCAcHCBEMDQoOFBEVFBMRExMWGB8bFhceFxMTGyUcHiAhIyMjFRomKSYiKR8iIyL/2wBDAQYGBggHCBAJCRAiFhMWIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiL/wAARCAOWBmADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8]...[zUOSGGaKKfQfUUMSuR3NY3iCZ7WC3ky+3zQrBHKk8Hv9cUUUhMzv+Es8gLHLbsz/AN4P2/Kom8aQcj7NLke4ooplW0I9T1wvb20sbTQqZPm8vGTwcUtn4niS3WOaOVpAMMRg5P50UUE9BV8YWZyBDcDnH3V/xq3o2qLfmWP94SCWBfHQngUUUDGXGvwWskiSxSEx9SoH+NRr4hgctiKTAODwP8aKKQupONaiyN6Pg9MAf41Qi1mRb2Z3Zmi34CYHAoop20GbdvfLOrFVYY9ay4NUlW5l8470810C46YYj+lFFICWXUylwrHJiOBtxyDWgZRtVucHtRRTa0H0IzdBAcgmoReozHKtxRRSEthxuFwDtODQJAw70UUC6iH5Tx3prnauTk5oooH0IHnwxXHUAimbgeuaKKroJjzJ+74/WmRnI55zRRUCKMF68txIrqu0OVGOvBP+FXBz04ooprYZXEjNcNEcYA9KsoQqYxx0oopg9z//2Q==": Failed to decode VALUE_STRING as base64 (MIME-NO-LINEFEEDS): Illegal character ':' (code 0x3a) in base64 content
at [Source: (PushbackInputStream); line: 1, column: 143] (through reference chain: com.ashwin.vemployee.model.Employee["imagObject"])]
How can I handle this error?

This is not a standard approach. But try it.
#Entity #Table(name = "employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
// Remaining fields
#Transient
private String imageDecode;
}
From UI send your decoded data to this transient variable.
Once after the successful serialization convert that string to byte array[].
byte[] byte = imageDecode.getBytes();
Hope this will work.

The stack trace shows the exact problem. Yes you cannot deserialize the String to byte array. To make your JSON deserialize works you need to create custom deserializer.
Reference:
https://www.baeldung.com/jackson-deserialization

Related

How do I access data returned from a controller invoked by an ajax call in an MVC View

I have an MVC 5 view with the following JavaScript which is getting an error after invoking an action method on a controller:
<script type="text/javascript">
$('#ddlvendors').change(function () {
var descHtml = "";
var vendorId = $(this).val();
$.ajax(
{
type: "POST",
data: { vendorId: vendorId },
url: '#Url.Action("PurchaseOrderVendor")',
datatype: "json",
success: function (aVendorObject) {
alert(aVendorObject.Name);
},
error: function (req, status, error) {
alert(error);
}
});
});
</script>
The controller action method is as follows:
[HttpPost]
public ActionResult PurchaseOrderVendor( int vendorId)
{
Vendor aVendor=VendorServices.GetVendor(vendorId);
return Json(aVendor);
}
The vendor object being returned is as follows:
public class VendorViewModel
{
public int VendorId { get; set; }
public string Name { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string Description { get; set; }
public string ContactName { get; set; }
public string Phone { get; set; }
}
Using the Visual Studio 2017 debugger I can see the vendor data is correctly getting filled on the controller side. If I don't try to access any member data the ajax call completes without an error. However, when I try to access any part coming in as aVendorObject such as aVendorObject.Name I get a browser error saying "Internal Server Error". How can I fix my success handler in the ajax call so I can access members of the Vendor object being returned from the controller?
Thanks in advance.
The LazyLoading feature of EntityFramework 6 did not have the Vendor object available when it was needed. I added a line in the VendorServices class to turn off LazyLoading which fixed the problem. Below is the method where I turn off LazyLoading for this particular VendorService method:
static public Vendor GetVendor(int aVendorId)
{
Vendor vendor;
using (RgmSiteDAL RgmSiteDALCtx = new RgmSiteDAL())
{
//** Now setting LazyLoadingEnabled to false.
RgmSiteDALCtx.Configuration.LazyLoadingEnabled = false;
vendor = RgmSiteDALCtx.Vendor
.Where(v => v.VendorId == aVendorId)
.FirstOrDefault<Vendor>();
}
return vendor;
}
I found out that I can also fix the problem if I include any navigation properties defined with the Vendor entity as in the following:
vendor = RgmSiteDALCtx.Vendor
.Where(v => v.VendorId == aVendorId)
.Include(v => v.PurchaseOrder) //because is in Vendor navigation property
.FirstOrDefault<Vendor>();
For my situation I will stick with the first solution which sets LazyLoadingEnabled to false. This is because the option to generate my entities from my existing database setup my PurchaseOrder table as a navigation property for my Vendor which I believe is incorrect. My Vendor object does not need anything from my PurchaseOrder entity when I query for Vendor information. I will look into removing the PurchaseOrder navigation property from my Vendor entity because I believe it was incorrectly setup by the create entities from database tool in Visual Studio.

Upload multiple files each with additional information in spring

I'm new to spring boot and js and i'm trying to upload multiple files each having additionl information like description etc.
Objects :
public class BookDto {
private String title;
private String author;
private List<PageDto> pageDtoList;
// getters setters
}
public class PageDto {
private String description;
private MultipartFile file;
// getters setters
}
Controller :
public class UploadController{
#PostMapping("/upload")
public ResponseEntity createGenre(#RequestBody BookDto bookDto){
// do something with data
}
}
Html :
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" multiple onclick="postRequest(event)">
<input type="submit" value="Upload" name="submit">
</form>
JS :
function postRequest(event){
event.preventDefault();
var files = [].slice.call(event.target.files);
var pageList = [];
for (var i=0; i<files.length; i++) {
pageList.push(new Page( i + "some description",files[i]));
}
var newBook = new Book();
newbook.pageList = pageList;
book.author = "author1";
book.title = "title1";
$.ajax({
type: "POST",
data: // i don't really know what to put here,
url: "/upload",
success: function (response) {
// success
},
error: function (result) {
// error
}
});
}
function Book(title, author, chapter, pageList){
this.title = title;
this.author = author;
this.pageList = pageList;
}
function Page(description, file) {
this.description = description;
this.file = file;
}
I would like to know if it is possible to upload files as described by the objects or do i have to upload them seperately.
In order to create a book instance from a request, considering you have a route such as :
#PostMapping("/createBook")
public ResponseEntity createBook(#RequestBody BookDto bookDto){
// do something with data
}
you can from client proceed to following :
const book = {
author: "George Orwell",
title: "1984",
pageDtoList: []
};
$.ajax({
type: "POST",
data: book,
url: "/createBook",
success: function (response) {
// success
},
error: function (result) {
// error
}
});
You can then add pages with same logic, but with a file set to null temporary, and upload file after, given a page id.
#PostMapping("/addPageToBook")
public ResponseEntity addPage(#RequestParam("bookid") String bookId,
#RequestBody PageDto pageDto){
// add a page instance to your book
}
And after you can set page content :
#PostMapping("/setPageContent")
public ResponseEntity setPage(#RequestParam("bookid") String bookId,
#RequestParam("pageid") String pageId,
#RequestParam("file") MultipartFile content){
// set content to page, ensure book dto is updated with last page instance
}
You will need to use https://developer.mozilla.org/en-US/docs/Web/API/FormData for AJAX uploading, but maybe (depending on your use case) a simple file input button + submit can be enough.

How to make requestbody controller works?

So actually everything is working well, except the fact that i can't get access to "inscrit" which is supposed to be the one which is sent to have the information user
This is my function in javascript and it does go into success for ajax.
function fbLogin() {
FB.login(function (response) {
if (response.authResponse) {
var inscrit = {
"prenom": response.first_name,
"nom": response.last_name,
"email": response.email
}
$.ajax({
method: 'post',
url: '/hello/facebookconnection',
contentType : 'application/json; charset=utf-8',
data: JSON.stringify(inscrit),
datatype: "json",
success: function() {
window.alert('User data sent');}
,
error: function(){
window.alert('Error in sending ajax data');}
});
} else {
document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
}
}, {scope: 'email'});
}
And this is my java controller (whatever i do, the "inscrit.getEmail()" is always null)
#RequestMapping(value = "/facebookconnection", method = RequestMethod.POST)
#ResponseBody public void createUser(#RequestBody inscrit inscrit, ModelMap model) throws Exception {
//System.out.println(inscrit.getNom());
//System.out.println(inscrit.getPrenom());
System.out.println(inscrit.getEmail());
try {
user.adduser(inscrit);
} catch (Exception e) {
e.printStackTrace();
}
}
This is my inscrit class with all the getter and setter correctly set (i know that there's no problem with it)
#Entity
#Table(name="inscrit")
public class inscrit implements Serializable {
#Id
#Column(name="email")
private String email;
#Column(name="nom")
private String nom;
#Column(name="prenom")
private String prenom;
}
So i would like to know if someone could help me understand why it's not working in my controller (how to do so the data is sent properly from the ajax to the controller) :(
Thx !
EDIT : i did write the answer of that question below. The problem was the fact that response.first_name was really blank... and had to pass through the function userdata() which had the real informations. So that means i don't have any real error in my code, all the informations between the controller and my jsp page works correctly. Be free to use it as an example of how this works
#ResponseBody public void createUser(#RequestParam(value="inscrit") String inscrit) throws Exception {
//System.out.println(inscrit.getNom());
//System.out.println(inscrit.getPrenom());
Inscrit ins = JSON.parseObject(inscrit, Inscrit.class);
System.out.println(ins.getEmail());
try {
user.adduser(ins);
} catch (Exception e) {
e.printStackTrace();
} }
The class of inscrit.java is nonstandard.You should change it to Inscrit.java.
I hope this helps.
I'll answer to my own question since i found the answer, So this is for people who tries to have a facebook api and want to get informations of the profil to put into database.
My error was the fact that i thought response in login was the same asthe UserData(), which is not the case... So that's how i was supposed to do it.
function fbLogin() {
FB.login(function (response) {
if (response.authResponse) {
// Get and display the user profile data
getFbUserData();
} else {
document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
}
}, {scope: 'email'});
}
// Fetch the user profile data from facebook
function getFbUserData(){
FB.api('/me', {locale: 'en_US', fields: 'id,first_name,last_name,email,link,gender,locale,picture'},
function (response) {
/*document.getElementById('fbLink').setAttribute("onclick","fbLogout()");
document.getElementById('fbLink').innerHTML = 'Logout from Facebook';
document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.first_name + '!';
document.getElementById('userData').innerHTML = '<div class="fbprofile"><p><b>FB ID:</b> '+response.id+'</p><p><b>Name:</b> '+response.first_name+' '+response.last_name+'</p><p><b>Email:</b> '+response.email+'</p><p><b>Gender:</b> '+response.gender+'</p><p><b>Locale:</b> '+response.locale+'</p></div><p><b>Picture:</b> <img src="'+response.picture.data.url+'"/></p>';*/
var inscrit = {
"prenom": response.first_name,
"nom": response.last_name,
"password": "1234",
"status": 0,
"email": response.email
}
$.ajax({
method: 'post',
url: '/hello/facebookconnection',
contentType : 'application/json; charset=utf-8',
data: JSON.stringify(inscrit),
datatype: "json",
success: function() {
document.location.href = "accueilmember";
},
error: function(){
window.alert('Error in sending ajax data');}
});
});
}
This is my controller class.This just logs the post request send to the server:(You may modify this if you need something more like adding a Response Body)
#RestController
public class EmailController {
#RequestMapping(value = "/facebookconnection", method = RequestMethod.POST)
public void createUser(#RequestBody inscrit inscrit) throws Exception {
System.out.println(inscrit.getNom());
System.out.println(inscrit.getPrenom());
System.out.println(inscrit.getEmail());
}
This is my inscrit.java class(I personally think naming the class would not affect but better follow standard naming Practices like Inscrit.java)
import java.io.Serializable;
public class inscrit implements Serializable {
private static final long serialVersionUID = -8445943548965154778L;
private String email;
private String prenom;
private String nom;
public inscrit() {
super();
}
public inscrit(String email,String prenom,String nom) {
this.setEmail(email);
this.setPrenom(prenom);
this.setNom(nom);
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
}
I did a post request from Advanced Rest Client and set the payload as
{
"email":"agdfae#gmail.com",
"prenom":"qewrwe",
"nom":"qwer"
}
the results were
qwer
qewrwe
agdfae#gmail.com
You can modify this to suit your own needs.Hope this helps
EDIT:
You will need more two classes in spring boot as below:
ServletInitializer.java
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(PostDataApplication.class);
}
}
PostDataApplication .java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class PostDataApplication {
public static void main(String[] args) {
SpringApplication.run(PostDataApplication.class, args);
}
}
PostDataApplication is the name of the application.
These four classes will do the trick (with pom.xml only no other xml configuration needed since this is springboot).Let me know if you have any problem.

400 bad request while sending data with jquery ajax in spring framework?

I am having some issue submitting json data from jquery ajax. I have googled some similar problems but non of them worked for me.
$.ajax({
type : "POST",
contentType : "application/json",
url : "save-routes",
data : JSON.stringify(routeObject),
dataType : 'json',
timeout : 100000,
success : function(status) {
console.log("SUCCESS ADDING ROUTE DATA");
return status;
},
error : function(e) {
console.log("ERROR WHILE ADDING ROUTE DATA");
return false;
},
done : function(e) {
console.log("DONE");
//return true;
}
});
routeObejct Json format:
{name:"value", data:["value1","value2"...]}
spring controller:
#JsonView(Views.Public.class)
#RequestMapping(value = "/save-routes", method = RequestMethod.POST)
public #ResponseBody boolean loadRoutes(#RequestBody Route route) {
//codes
return status;
}
I keep getting this error:
POST http://localhost:8181/SYBusWebApp/save-route 400 Bad Request 6ms
Route Class:
public class Route {
#JsonView(Views.Public.class)
private String name;
#JsonView(Views.Public.class)
private ArrayList<stop> routeStops;
private String updatedRouteName;
private ArrayList<String> addedRouteStopNames;
//getters and setters
}
Stop Class:
public class Stop {
#JsonView(Views.Public.class)
private String name;
#JsonView(Views.Public.class)
private float latitude;
#JsonView(Views.Public.class)
private float longitude;
private String updatedName;
//getters and setters
}
It seems your Route object is not matching your JSON payload.
{name:"value", data:["value1","value2"...]}
In your case I would expect a nested collection of Stop objects within your JSON payload for routeStops:
{
name:"value",
routeStops:[
{
"name":"test",
"latitude": 3.124
},
....
],
...
}

How to send multiple parameters Ajax request with Jquery in Spring MVC Application.?

Here is my relevant codes.my out put is like this.
I need to send region and tsrId as parameters to query.
here is my code
jsp
Here is my ajax request with jquery
<script type="text/javascript">
$(document).ready(function() {
var region = document.getElementById('region').value;
var tsrId = document.getElementById('tsrId').value;
$('#tsrId').autocomplete({
serviceUrl: 'getTsrId.html',
data: ({queryData : {region:region,tsrId:tsrId}}),
//delimiter: ",",
transformResult: function(response) {
return {suggestions: $.map($.parseJSON(response), function(item) {return { value: item.name, data: item.id };
})};}});});
</script>
here is the HTML form
<td>Region</td>
<td><input type="text" name="region" id="region"><div class="autocomplete-suggestions"></div></td>
<td>TSR ID</td>
<td><input type="text" name="tsrId" id="tsrId" maxlength="8"><div class="autocomplete-suggestions2"></div></td>
here is my controller
#RequestMapping(value = "/getTsrId", method = RequestMethod.GET)
public #ResponseBody List<TSRMaster> getTsrId(#RequestParam String tagName,#RequestBody QueryData queryData) {
List<TSRMaster> tsrMasterList=new ArrayList<TSRMaster>();
tsrMasterList=gpsdao.getTsrIdList(queryData.getRegion(),queryData.getTsrId());
return tsrMasterList;
}
here is my bean class for requestMapping
public class QueryData {
private String region;
private String tsrId;
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getTsrId() {
return tsrId;
}
public void setTsrId(String tsrId) {
this.tsrId = tsrId;
}
}
Please help me to sort out this issue..is there any other alternative solution, please mention that path below
thanks.
The only way I have been able to make this work so far is to call JSON.stringify() on the client, which turns a JavaScript Object into a JSON String. (To be cross browser compatible you would need json2.js)
Then you send this as a String parameter to Spring and parse it there using the Jackson library.
Sample Code:
Java Script
data: ({queryData : JSON.stringify({region:region,tsrId:tsrId}})),
Java
RequestMapping(value = "/getTsrId", method = RequestMethod.GET)
public #ResponseBody List<TSRMaster> getTsrId(#RequestParam String tagName,#RequestParam String queryData) {
ObjectMapper myMapper = new ObjectMapper();
QueryData myQueryData = myMapper.readValue(queryData, QueryData.class);
List<TSRMaster> tsrMasterList=new ArrayList<TSRMaster>();
tsrMasterList=gpsdao.getTsrIdList(myQueryData.getRegion(),queryData.getTsrId());
return tsrMasterList;
}
You can use Jackson framework for JSON java transformation. Then you can use following method to send data to the controller from the view.
Add jackson jars to the project.
jackson-core-2.0.5
jackson-databind-2.0.5
jackson-annotation-2.0.5
Add following code to WebApplicationContext.xml
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
</bean>
Ajax call
$.ajax({
url: getTsrId.html,
type: 'GET',
data: "region=" + region + "&tsrId=" + tsrId,
dataType: "json",
success: function(response){
//response here
}
});
Controller
#RequestMapping(value = "/getTsrId", method = RequestMethod.GET,produces="application/json")
public #ResponseBody List<TSRMaster> getTsrId(
#ModelAttribute(value = "queryData") QueryData queryData) {
List<TSRMaster> tsrMasterList = new ArrayList<TSRMaster>();
tsrMasterList = gpsdao.getTsrIdList(queryData.getRegion(),queryData.getTsrId());
return tsrMasterList;
}

Categories