calling rest api in spring - json

I am having rest method in spring controller like below:
#RequestMapping(value="/register/{userName}" ,method=RequestMethod.GET)
#ResponseBody
public String getUserName(HttpServletRequest request,#PathVariable String userName ){
System.out.println("User Name : "+userName);
return "available";
}
In jquery I have writeen ajax call like:
$(document).ready(function(){
$('#userName').blur(function(){
var methodURL = "http://localhost:8085/ums/register/"+$('#userName').val();
$.ajax({
type : "get",
URL : methodURL,
data : $('#userName').val(),
success : function(data){
alert(data);
$('#available').show();
}
})
});
});
In web.xml I have:
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
In spring-servlet.xml I have the view resolver like below:
<context:component-scan base-package="com.users.controller" />
<context:annotation-config />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1"/>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="text/xml" />
<entry key="htm" value="text/html" />
</map>
</property>
<property name="ignoreAcceptHeader" value="true" />
<!-- <property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />-->
<property name="defaultContentType" value="text/html" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="2" />
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
When I am running this in server, it is not going to controller.
Please let me know the problem with this code.
Please can any one help on this.
Regards,
Shruti

Since you have the #RequestMapping(value="register/{userName}" on your method definition, your jquery call must follow the same syntax.
var methodURL = "http://localhost:8085/users/register/"+$('#userName').val()+".html";
But you have also a problem in your RequestMapping value, it should start with /
#RequestMapping(value="/register/{userName}"
Also I doubt that you need the ".html" at the end

Add this line to your spring-servlet.xml. It will enable the Web MVC specific annotations like #Controller and #RequestMapping
<mvc:annotation-driven />
Example of an annotated controller
Assuming the url with context is http://localhost:8080/webapp and you want an api call like url /users/register/johnDoe. (johnDoe being the username)
You controller class would look something like the following.
#Controller
#RequestMapping(value="/users")
class UserController {
#ResponseBody
#RequestMapping(value="/register/{username}", method=RequestMethod.GET)
public String registerUser(#PathVariable String username) {
return username;
}
}

Please find my solution for calling REST web-services in Spring Framework.
/**
* REST API Implementation Using REST Controller
* */
#RestController
public class RestReqCntrl {
#Autowired
private UserService userService;
#Autowired
private PayrollService payrollService;
//-------------------Create a User--------------------------------------------------------
#RequestMapping(value = "/registerUser", method = RequestMethod.POST)
public ResponseEntity<User> registerUser(#RequestBody User user, UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating User " + user.getFirstName());
boolean flag = userService.registerUser(user);
if (flag)
{
user.setStatusCode(1);
user.setStatusDesc("PASS");
}else{
user.setStatusCode(0);
user.setStatusDesc("FAIL");
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerUser").buildAndExpand(user.getId()).toUri());
return new ResponseEntity<User>(user,headers, HttpStatus.CREATED);
}
//-------------------Authenticating the User--------------------------------------------------------
#RequestMapping(value = "/authuser", method = RequestMethod.POST)
public ResponseEntity<User> authuser(#RequestBody User user,UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating User " + user.getFirstName());
boolean flag = userService.authUser(user);
if (flag)
{
user.setStatusCode(1);
user.setStatusDesc("PASS");
}else{
user.setStatusCode(0);
user.setStatusDesc("FAIL");
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/authuser").buildAndExpand(user.getFirstName()).toUri());
return new ResponseEntity<User>(user,headers, HttpStatus.ACCEPTED);
}
//-------------------Create a Company--------------------------------------------------------
#RequestMapping(value = "/registerCompany", method = RequestMethod.POST)
public ResponseEntity<String> registerCompany(#RequestBody ComypanyDTO comypanyDTO, UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating comypanyDTO " + comypanyDTO.getCmpName());
String result ="";
boolean flag = payrollService.registerCompany(comypanyDTO);
if (flag)
{
result="Pass";
}else{
result="Fail";
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
}
//-------------------Create a Employee--------------------------------------------------------
#RequestMapping(value = "/registerEmployee", method = RequestMethod.POST)
public ResponseEntity<String> registerEmployee(#RequestBody EmployeeDTO employeeDTO, UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating registerCompany " + employeeDTO.getEmpCode());
String result ="";
boolean flag = payrollService.registerEmpbyComp(employeeDTO);
if (flag)
{
result="Pass";
}else{
result="Fail";
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
}
//-------------------Get Company Deatils--------------------------------------------------------
#RequestMapping(value = "/getCompanies", method = RequestMethod.GET)
public ResponseEntity<List<ComypanyDTO> > getCompanies(UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("getCompanies getCompanies ");
List<ComypanyDTO> comypanyDTOs =null;
comypanyDTOs = payrollService.getCompanies();
//Setting the Respective Employees
for(ComypanyDTO dto :comypanyDTOs){
dto.setEmployeeDTOs(payrollService.getEmployes(dto.getCompanyId()));
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand("LISt").toUri());
return new ResponseEntity<List<ComypanyDTO>>(comypanyDTOs,headers, HttpStatus.ACCEPTED);
}
}
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name="USER_TABLE")
public class User implements Serializable {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String firstName;
private String lastName;
private String email;
private String userId;
private String password;
private String userType;
private String address;
#Transient
private int statusCode;
#Transient
private String statusDesc;
public User(){
}
public User(String firstName, String lastName, String email, String userId, String password, String userType,
String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.userId = userId;
this.password = password;
this.userType = userType;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* #return the userType
*/
public String getUserType() {
return userType;
}
/**
* #param userType the userType to set
*/
public void setUserType(String userType) {
this.userType = userType;
}
/**
* #return the address
*/
public String getAddress() {
return address;
}
/**
* #param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* #return the statusCode
*/
public int getStatusCode() {
return statusCode;
}
/**
* #param statusCode the statusCode to set
*/
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
/**
* #return the statusDesc
*/
public String getStatusDesc() {
return statusDesc;
}
/**
* #param statusDesc the statusDesc to set
*/
public void setStatusDesc(String statusDesc) {
this.statusDesc = statusDesc;
}
}

Related

Jackson #JsonIgnore Annotation - Relationship Values Don't get Returned

I have a mysql db from which i have generated the TransferObject Using Hibernate. There is a one to many relationship beteween city and patients, city and doctors, specialty and doctors. However i don't get any returned values when querying the database from those one to many relationships.
When i test RestFul End Points i get:
/doctors/all
[{"id":1,"email":"papa#papa.com","fatherName":"πατέρας","firstName":"όνομα","lastName":"επίθετο","telephone":"2821074737"},{"id":2,"email":"lala#gmail.com","fatherName":"dfjs","firstName":"Ιωσήφ","lastName":"Βαρουξάκης","telephone":"8583848824"},{"id":3,"email":"","fatherName":"","firstName":"Χαράλαμπος","lastName":"Πρωτοπαπαδάκης","telephone":"4343454345"},{"id":4,"email":"","fatherName":"","firstName":"Ελευθέριος","lastName":"Παπαδάκης","telephone":"2821084834"},{"id":5,"email":"","fatherName":"","firstName":"Παναγιώτης","lastName":"Τζεράκης","telephone":"28210848383"},{"id":6,"email":"","fatherName":"","firstName":"Κων/νος","lastName":"Κωνσταντινίδης","telephone":"2821084838"},{"id":7,"email":"","fatherName":"","firstName":"Παναγιώτης","lastName":"Ψιστάκης","telephone":"2810838383"},{"id":8,"email":"","fatherName":"Εμμανουήλ","firstName":"Θεανώ","lastName":"Πατακάκη","telephone":"2821048438"},{"id":9,"email":"","fatherName":"","firstName":"Μαρία","lastName":"Καφούση","telephone":"2810848283"},{"id":10,"email":"","fatherName":"","firstName":"Μανούσος","lastName":"Χριστοδουλάκης","telephone":"2810848383"},{"id":11,"email":"saf#fdsa.gr","fatherName":"αφδσ","firstName":"φδσα","lastName":"σφδ","telephone":"2323233223"},{"id":12,"email":"","fatherName":"φεδσαφ","firstName":"φδσαφδσα","lastName":"φδσαφγσφαδ","telephone":"3333333333"},{"id":13,"email":"mixtou#gmail.co","fatherName":"Dimitrios","firstName":"Toutoudakis","lastName":"Mixail","telephone":"6948571893"}]
/patients/all
[{"id":1,"birthday":"1975-08-19","email":"mixtou#gmail.com","fatherName":"Δημήτριος","firstName":"Μιχαήλ","lastName":"Τουτουδάκης","telephone":"6948571893","sex":true},{"id":2,"birthday":"1942-06-10","email":"lla#gmail.com","fatherName":"Μιχαήλ","firstName":"Δημήτριος","lastName":"Τουτουδάκης","telephone":"7364927473","sex":true},{"id":3,"birthday":"1975-05-06","email":"lala#gmail.com","fatherName":"Μιχαήλ","firstName":"Μιχαήλ","lastName":"Μαραγκάκης","telephone":"8484848484","sex":false},{"id":4,"birthday":"1957-08-14","email":"lasdjf#lkdafs.gr","fatherName":"Τεστ","firstName":"Μηνάς","lastName":"Παπαδάκης","telephone":"8484842747","sex":false},{"id":5,"birthday":"2018-03-26","email":"","fatherName":"","firstName":"Στέφανος","lastName":"Μαριόλος","telephone":"4838583845","sex":true},{"id":6,"birthday":"2018-03-20","email":"jkdas#gjal.com","fatherName":"Μ..κας","firstName":"Κων/νος","lastName":"Μπλαζάκης","telephone":"2347878763","sex":false},{"id":7,"birthday":"2018-03-08","email":"ajs#gjla;.gr","fatherName":"pateras","firstName":"f;ldas","lastName":"akdfsj","telephone":"445354345453","sex":true},{"id":8,"birthday":"2018-03-12","email":"lala#gam.gr","fatherName":"Εμμανουήλ","firstName":"Ιωάννης","lastName":"Μαλανδράκης","telephone":"4343434343","sex":false},{"id":9,"birthday":"1980-05-12","email":"antonis#gmai.com","fatherName":"Δεν Ξέρω","firstName":"Αντώνιος","lastName":"Ιγγλεζάκης","telephone":"28210848484","sex":false},{"id":10,"birthday":"2018-04-19","email":"test#etes.gr","fatherName":"test","firstName":"test`","lastName":"tet","telephone":"2345674424","sex":false},{"id":11,"birthday":"1984-02-13","email":"lala#gmail.com","fatherName":"Δημήτριος","firstName":"Ιωάννης","lastName":"Μαλανδράκης","telephone":"1223323344","sex":false},{"id":12,"birthday":"2018-05-16","email":"lala#gmail.com","fatherName":"Τεεε","firstName":"Τέστης","lastName":"Τεστάκης","telephone":"84848484823","sex":false},{"id":13,"birthday":"2018-06-05","email":"lala#gmail.com","fatherName":"test","firstName":"test","lastName":"test","telephone":"2821022222","sex":true}]
/cities/all
[{"id":4,"name":"Αγ. Νικόλαος"},{"id":3,"name":"Ηράκλειο"},{"id":2,"name":"Ρέθυμνο"},{"id":5,"name":"Ρόδος"},{"id":1,"name":"Χανιά"}]
/specialties/all
[{"id":1,"name":"Αγγειοχειρουργική"},{"id":2,"name":"Αιματολογία"},{"id":3,"name":"Ακτινοδιαγνωστική"},{"id":4,"name":"Ακτινοθεραπευτική"},{"id":5,"name":"Αλλεργιολογία"},{"id":6,"name":"Αναισθησιολογία"},{"id":7,"name":"Γαστρεντερολογία"},{"id":8,"name":"Γενική Ιατρική"},{"id":9,"name":"Δερματολογία"},{"id":10,"name":"Ενδοκρινολογία"},{"id":12,"name":"Ιατρική Εργασίας"},{"id":13,"name":"Ιατροδικαστική"},{"id":14,"name":"Καρδιολογία"},{"id":15,"name":"Κυτταρολογία"},{"id":16,"name":"Μαιευτική Γυναικολογία"},{"id":11,"name":"Μικροβιολογία"},{"id":17,"name":"Νευρολογία"},{"id":18,"name":"Νευροχειρουργική"},{"id":19,"name":"Νεφρολογία"},{"id":20,"name":"Ορθοπαιδική"},{"id":21,"name":"Ουρολογία"},{"id":22,"name":"Οφθαλμολογία"},{"id":23,"name":"Παθολογία"},{"id":24,"name":"Παθολογική Ανατομική"},{"id":25,"name":"Παθολογική Ογκολογία"},{"id":26,"name":"Παιδιατρική"},{"id":27,"name":"Παιδοψυχιατρική"},{"id":28,"name":"Πλαστική Χειρουργική"},{"id":29,"name":"Πνευμονολογία - Φυματιολογία"},{"id":30,"name":"Πυρηνική Ιατρική"},{"id":31,"name":"Ρευματολογία"},{"id":39,"name":"Στοματική & Γναθοπροσωπική Χειρουργική"},{"id":32,"name":"Φυσική Ιατρική και Αποκατάσταση"},{"id":33,"name":"Χειρουργική"},{"id":36,"name":"Χειρουργική Β΄"},{"id":34,"name":"Χειρουργική Θώρακος"},{"id":35,"name":"Χειρουργική Παίδων"},{"id":37,"name":"Ψυχιατρική"},{"id":38,"name":"ΩΡΛ"}]
Everything works ok with one exception. The city and specialty relationship. I get no city or specialty data in replies.
Below is my implementation
My persistence.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.1">
<persistence-unit name="PersistenceUnit">
<!--<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>-->
<class>gr.histopath.platform.model.TransferObjects.BodyPart</class>
<class>gr.histopath.platform.model.TransferObjects.City</class>
<class>gr.histopath.platform.model.TransferObjects.Clinic</class>
<class>gr.histopath.platform.model.TransferObjects.Doctor</class>
<class>gr.histopath.platform.model.TransferObjects.Incident</class>
<class>gr.histopath.platform.model.TransferObjects.Patient</class>
<class>gr.histopath.platform.model.TransferObjects.SigningDoctor</class> <class>gr.histopath.platform.model.TransferObjects.Specialty</class>
<class>gr.histopath.platform.model.TransferObjects.User</class>
<properties>
<!--<property name="hibernate.hbm2ddl.auto" value="create"/>-->
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/histopath.gr?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=Europe/Athens"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="histopathUser"/>
<!--<property name="hibernate.connection.username" value="root"/>-->
<property name="hibernate.connection.password" value="h1s+0p#+h"/>
<!--<property name="hibernate.connection.password" value="Malak1es"/>-->
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hbm2ddl.auto" value="update"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.connection.provider_class" value="org.hibernate.c3p0.internal.C3P0ConnectionProvider"/>
<property name="hibernate.connection.CharSet" value="utf8"/>
<property name="hibernate.connection.characterEncoding" value="utf8"/>
<property name="hibernate.connection.useUnicode" value="true"/>
<property name="connection.pool_size" value="1"/>
<!--<property name="hibernate.search.default.directory_provider" value="filesystem"/>-->
<!-- hibernate c3p0 connection pooling configuration -->
<property name="hibernate.c3p0.acquire_increment" value="1"/>
<property name="hibernate.c3p0.idle_test_period" value="60"/> <!-- seconds -->
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.timeout" value="0"/> <!-- seconds -->
<property name="hibernate.c3p0.acquireRetryAttempts" value="1"/>
<property name="hibernate.c3p0.acquireRetryDelay" value="250"/>
</properties>
</persistence-unit>
</persistence>
The Transfer Objects are:
City.java
package gr.histopath.platform.model.TransferObjects;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.Collection;
import java.util.Objects;
#Entity
public class City {
private int id;
private String name;
private Collection<Doctor> doctors;
private Collection<Patient> patients;
#Id
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
City city = (City) o;
return id == city.id &&
Objects.equals(name, city.name);
}
#Override
public int hashCode() {
return Objects.hash(id, name);
}
#OneToMany(mappedBy = "city")
#JsonIgnore
public Collection<Doctor> getDoctors() {
return doctors;
}
public void setDoctors(Collection<Doctor> doctorsById) {
this.doctors = doctorsById;
}
#OneToMany(mappedBy = "city")
#JsonIgnore
public Collection<Patient> getPatients() {
return patients;
}
public void setPatients(Collection<Patient> patientsById) {
this.patients = patientsById;
}
}
Doctor.java
package gr.histopath.platform.model.TransferObjects;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.Collection;
import java.util.Objects;
#Entity
public class Doctor {
private int id;
private String email;
private String fatherName;
private String firstName;
private String lastName;
private String telephone;
private City city;
private Specialty specialty;
private Collection<Incident> incidents;
#Id
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Basic
#Column(name = "fatherName")
public String getFatherName() {
return fatherName;
}
public void setFatherName(String fatherName) {
this.fatherName = fatherName;
}
#Basic
#Column(name = "firstName")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Basic
#Column(name = "lastName")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Basic
#Column(name = "telephone")
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Doctor doctor = (Doctor) o;
return id == doctor.id &&
Objects.equals(email, doctor.email) &&
Objects.equals(fatherName, doctor.fatherName) &&
Objects.equals(firstName, doctor.firstName) &&
Objects.equals(lastName, doctor.lastName) &&
Objects.equals(telephone, doctor.telephone);
}
#Override
public int hashCode() {
return Objects.hash(id, email, fatherName, firstName, lastName, telephone, city, specialty);
}
#ManyToOne
#JoinColumn(name = "city_id", referencedColumnName = "id")
#JsonIgnore
public City getCity() {
return city;
}
public void setCity(City cityByCityId) {
this.city = cityByCityId;
}
#ManyToOne
#JoinColumn(name = "specialty_id", referencedColumnName = "id")
#JsonIgnore
public Specialty getSpecialty() {
return specialty;
}
public void setSpecialty(Specialty specialtyBySpecialtyId) {
this.specialty = specialtyBySpecialtyId;
}
#OneToMany(mappedBy = "doctor")
#JsonIgnore
public Collection<Incident> getIncidents() {
return incidents;
}
public void setIncidents(Collection<Incident> incidentsById) {
this.incidents = incidentsById;
}
}
Patient.java
package gr.histopath.platform.model.TransferObjects;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.sql.Date;
import java.util.Collection;
import java.util.Objects;
#Entity
public class Patient {
private int id;
private Date birthday;
private String email;
private String fatherName;
private String firstName;
private String lastName;
private String telephone;
private Boolean sex;
private Collection<Incident> incidents;
private City city;
#Id
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "birthday")
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
#Basic
#Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Basic
#Column(name = "fatherName")
public String getFatherName() {
return fatherName;
}
public void setFatherName(String fatherName) {
this.fatherName = fatherName;
}
#Basic
#Column(name = "firstName")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Basic
#Column(name = "lastName")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Basic
#Column(name = "telephone")
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
#Basic
#Column(name = "sex")
public Boolean getSex() {
return sex;
}
public void setSex(Boolean sex) {
this.sex = sex;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Patient patient = (Patient) o;
return id == patient.id &&
Objects.equals(birthday, patient.birthday) &&
Objects.equals(email, patient.email) &&
Objects.equals(fatherName, patient.fatherName) &&
Objects.equals(firstName, patient.firstName) &&
Objects.equals(lastName, patient.lastName) &&
Objects.equals(telephone, patient.telephone) &&
Objects.equals(sex, patient.sex) &&
Objects.equals(incidents, patient.incidents) &&
Objects.equals(city, patient.city);
}
#Override
public int hashCode() {
return Objects.hash(id, birthday, email, fatherName, firstName, lastName, telephone, sex, incidents, city);
}
#OneToMany(mappedBy = "patient")
#JsonIgnore
public Collection<Incident> getIncidents() {
return incidents;
}
public void setIncidents(Collection<Incident> incidentsById) {
this.incidents = incidentsById;
}
#ManyToOne
#JsonIgnore
#JoinColumn(name = "city_id", referencedColumnName = "id")
public City getCity() {
return city;
}
public void setCity(City cityByCityId) {
this.city = cityByCityId;
}
}
Specialty.java
package gr.histopath.platform.model.TransferObjects;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.Collection;
import java.util.Objects;
#Entity
public class Specialty {
private int id;
private String name;
private Collection<Doctor> doctors;
#Id
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Specialty specialty = (Specialty) o;
return id == specialty.id &&
Objects.equals(name, specialty.name);
}
#Override
public int hashCode() {
return Objects.hash(id, name);
}
#OneToMany(mappedBy = "specialty")
#JsonIgnore
public Collection<Doctor> getDoctors() {
return doctors;
}
public void setDoctors(Collection<Doctor> doctorsById) {
this.doctors = doctorsById;
}
}
Any Ideas why values don't get returned?? Values exist in database, i can see them in mysql workbench or by simply querying the whole table. Do i forget to do something?? I think my error will be ridiculous
It was caused by #JsonIgnore annotation. In my above example i have put it in both sides of the relationships (Both in #ManyToOne and #OneToMany).
The problem was solved by removing it from #ManyToOne side and leaving it only at #OneToMany side.
Good you solved your problem. I was reading your question and can't resist from commenting.
You should revisit your domain model (relationships). With current domain model, eventually you will face performance issue along with others.
If possible then remove one-to-many relationships between Specialty to Doctor; Patient to Incident; Doctor to Incident and City to Doctor, Patient.
Instead make Spcialty, Doctor, Patient and City as Master Entities (lifecycle won't depend on other entities. And keep following relationships:
Doctor to Specialty: many to one
Incident to Patient, Doctor: both many to one
Doctor to City: many to one
Patient to City: many to one
No one to many relationship is required.
Now if you want to fetch all the doctors in a city then do something like findAllByCity(City city).
When you create an Incident then you just need to pick Doctor and Patient and save the Incident. No need to cascade from Doctor and Patient side.
Final point: use secondary cache. It will share the performance burden with database.

Spring REST jackson not marshalling on POST request

Im using spring 4 and have added jackson-databind so I can get the request/reponse object marshalled.. It works when I return the object from a GET request, but the POST request object is not being populated.. It is NOT null so it is being instantiated
I have tried it using an HttpEntity for the method param to see if I was getting the JSON object and it was in the body of the entity. I could then manually marshal it..
I'm trying to figure out what is missing or mis-configured to have jackson
This is the method where the object is instantiated but not populated. Im using Spring 4 and the controller is annotated with #RestController which combines #Controller and #ResponseBody
#RequestMapping(value="/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getUser(User user) {
log.debug("got user: " + user.getId());
return new ResponseEntity<>(HttpStatus.OK);
}
Here is the JSON:
{
"id": 12,
"lastName": "Test",
"firstName": "Me"
}
This is the user object:
public class User {
private int id;
private String lastName;
private String firstName;
public User(){}
public User(int id, String lname, String fname) {
this.id = id;
this.lastName = lname;
this.firstName = fname;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
I also have the jackson mapper defined in my context file. Although the docs stated this didn't have to be done. It did work without it
<beans:bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jsonMessageConverter"/>
</beans:list>
</beans:property>
</beans:bean>
<beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>
Try to use #RequestBody annotation in your method call
#RequestMapping(value="/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody ResponseEntity <?> getUser(#RequestBody final User user){
You are missing an annotation call #RequestBody in your method and if I'm not wrong you'll need to add #ResponseBody too.
#RequestMapping(value="/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody ResponseEntity<?> getUser(#RequestBody User user) {
log.debug("got user: " + user.getId());
return new ResponseEntity<>(HttpStatus.OK);
}
The responsed provided were correct. I did need to add the #RequestBody to the method..I mis-read the docs.. it is only the #ResponseBody and #Controller that are added using #RestController. With that I do not need to add the #ResponseBody to the return object

Spring MVC with jdbc "table is not mapped"

So I´m trying to make an application with all http request get, put, post, delete.I'm making first a login with mysql and spring 3. So here I got this:
login.jsp:
<form:form id="myForm" method="post"
class="bs-example form-horizontal" commandName="UsersLogin">
signup.jsp
<form:form id="myForm" method="post"
class="bs-example form-horizontal" commandName="Users">
persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="{http://java.sun.com/xml/ns/persistence} {http://java.sun.com/xml/ns/persistence_2_0.xsd}"
version="2.0">
<persistence-unit name="punit">
</persistence-unit>
</persistence>
Here is my jpaContext.xml:
<context:annotation-config />
<jpa:repositories base-package="com.portuzona.repository" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="punit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<entry key="hibernate.hbm2ddl.auto" value="validate" />
<entry key="hibernate.format_sql" value="true" />
</map>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/portuzona?autoReconnect=true&createDatabaseIfNotExist=true&" />
<property name="username" value="root" />
<property name="password" value="1234" />
</bean>
</beans>
com.portuzona.model
Users model:
#Entity
#Table(name="users")
public class Users {
#Id
#GeneratedValue
private Long id;
#NotEmpty
#Size(min=4, max=20)
private String userName;
#NotEmpty
private String firstName;
#NotEmpty
private String lastName;
#NotEmpty
#Size(min=4, max=8)
private String password;
#NotEmpty
private String status;
#NotEmpty
#Email
private String emailAddress;
#NotNull
#Past
#DateTimeFormat(pattern="MM/dd/yyyy")
private Date dateOfBirth;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
USersLogin model:
public class UsersLogin {
#NotEmpty
#Size(min=4, max=20)
private String userName;
#NotEmpty
#Size(min=4, max=8)
private String password;
public String getPassword() {
return password;
}
public String getUserName() {
return userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
com.portuzona.service
public interface UsersService {
Users save(Users users);
boolean findByLogin(String userName, String password);
boolean findByUserName(String userName);
}
Implementation:
#Service("UsersService")
public class UsersServiceImpl implements UsersService {
#Autowired
private UsersRepository usersRepository;
#Transactional
public Users save(Users users) {
return usersRepository.save(users);
}
public boolean findByLogin(String userName, String password) {
Users stud = usersRepository.findByUserName(userName);
if(stud != null && stud.getPassword().equals(password)) {
return true;
}
return false;
}
public boolean findByUserName(String userName) {
Users use = usersRepository.findByUserName(userName);
if(use != null) {
return true;
}
return false;
}
}
com.portuzona.repository
#Repository("UsersRepository")
public interface UsersRepository extends JpaRepository<Users, Long> {
#Query("SELECT s FROM users s WHERE s.userName = :userName")
Users findByUserName(#Param("userName") String userName);
}
com.portuzona.controller
#Controller
#SessionAttributes("users")
public class UsersController {
#Autowired
private UsersService userService;
#RequestMapping(value="/signup", method=RequestMethod.GET)
public String signup(Model model) {
Users users = new Users();
model.addAttribute("users", users);
return "signup";
}
#RequestMapping(value="/signup", method=RequestMethod.POST)
public String signup(#Valid #ModelAttribute("users") Users users, BindingResult result, Model model) {
if(result.hasErrors()) {
return "signup";
} else if(userService.findByUserName(users.getUserName())) {
model.addAttribute("message", "User Name exists. Try another user name");
return "signup";
} else {
userService.save(users);
model.addAttribute("message", "Saved users details");
return "redirect:login.html";
}
}
#RequestMapping(value="/login", method=RequestMethod.GET)
public String login(Model model) {
UsersLogin usersLogin = new UsersLogin();
model.addAttribute("UsersLogin", usersLogin);
return "login";
}
#RequestMapping(value="/login", method=RequestMethod.POST)
public String login(#Valid #ModelAttribute("UsersLogin") UsersLogin usersLogin, BindingResult result) {
if (result.hasErrors()) {
return "login";
} else {
boolean found = userService.findByLogin(usersLogin.getUserName(), usersLogin.getPassword());
if (found) {
return "success";
} else {
return "failure";
}
}
}
}
I got this error when trying to access to /login or /signup where I have my .jsp with my forms:
sep 24, 2015 11:14:35 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet usersHibernateServlet
org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [SELECT s FROM users s WHERE s.userName = :userName]
I have been with this for two days, looking for answers here but no kind of good results from my side... just gives me the same error, any idea?

JAXRS client - Deserialization Issue with Pojo

Helo Everyone. I am new to jersey and Jackson and finding it really difficult to deserialize a JSOn response from my REST service on client side. I am pretty sure that I am still not grasping the Object mapper and JSON provider APIs that well. Any help or guidance is appreciated in advance. Here is my source code.
Source Code
POJO Class
#XmlRootElement(name = "user")
public class User implements Serializable{
private String firstName;
private String lastName;
private String email;
private String userID;
public User() {
}
public User(String firstName, String lastName, String email, String userID) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.userID = userID;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
}
Client Code
package com.example.service.client;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.jackson.JacksonFeature;
import com.example.service.bean.User;
import com.example.service.client.mapper.MyMessageBodyReader;
import com.example.service.client.mapper.MyObjectMapperProvider;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
public class GetJSONResponse {
public static void main(String[] args) {
// TODO Auto-generated method stub
JacksonJaxbJsonProvider provider1 = new JacksonJaxbJsonProvider();
Client c = ClientBuilder.newClient()register(provider1);//.register(mapper);
WebTarget target = c.target("http://localhost:8080/RestfulWebserviceExample").path("/jaxrs/user/Nishit");
Response resp = target.request(MediaType.APPLICATION_JSON).get();
System.out.println(resp.getStatus());
String user1 = resp.readEntity(String.class);
System.out.println(user1);
User user = target.request(MediaType.APPLICATION_JSON).get(User.class);
System.out.println("User : " + user.getUserID());
}
}
`
The first 2 sysout generates an output as
200
{"user":{"firstName":"Nishit","lastName":"Ladha","email":"ladha#us.ibm.com","userID":"nishiz"}}
But when i tries to directly get the User object from response, I get an error as
Exception in thread "main" javax.ws.rs.client.ResponseProcessingException: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "user" (class com.example.service.bean.User), not marked as ignorable (4 known properties: "lastName", "firstName", "email", "userID"])
at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream#10163d6; line: 1, column: 10] (through reference chain: com.example.service.bean.User["user"])
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:806)
at org.glassfish.jersey.client.JerseyInvocation.access$700(JerseyInvocation.java:92)
at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:700)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:696)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:420)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:316)
at com.example.service.client.GetJSONResponse.main(GetJSONResponse.java:40)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "user" (class com.example.service.bean.User), not marked as ignorable (4 known properties: "lastName", "firstName", "email", "userID"])
It will be really kind if anyone of you can guide me how to resolve this.
I am not using Maven as I first wanted to try without Maven
I am not sure why my rest service is wrapping the response. Here is the code :
Service Method
#GET
#Path("/{username}")
#Produces(MediaType.APPLICATION_JSON)
public User helloWorld(#PathParam("username") String name){
User user = new User();
user.setFirstName("Nishit");
user.setLastName("Ladha");
user.setUserID("nishiz");
user.setEmail("ladha#us.ibm.com");
return user;
}
Web.xml##
<servlet>
<description>JAX-RS Tools Generated - Do not modify</description>
<servlet-name>JAX-RS Servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
com.example.service,
com.fasterxml.jackson.jaxrs.json
</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
Man, look, you are trying to bind unexistent field User.
If you want to properly parse this json
{"user":{"firstName":"Nishit","lastName":"Ladha","email":"ladha#us.ibm.com","userID":"nishiz"}}
You need to have similar to this class
public class UserWrapper implements Serializable{
private User user;
// Constructors
// Getters, and setters
// HashCode and equals
}
Then this client code will work:
public class GetJSONResponse {
public static void main(String[] args) {
// TODO Auto-generated method stub
JacksonJaxbJsonProvider provider1 = new JacksonJaxbJsonProvider();
Client c = ClientBuilder.newClient()register(provider1);//.register(mapper);
WebTarget target = c.target("http://localhost:8080/RestfulWebserviceExample").path("/jaxrs/user/Nishit");
Response resp = target.request(MediaType.APPLICATION_JSON).get();
System.out.println(resp.getStatus());
String user1 = resp.readEntity(String.class);
System.out.println(user1);
UserWrapper userWrapper = target.request(MediaType.APPLICATION_JSON).get(UserWrapper.class);
}
}
If you have any questions - just ask.Hope your code will work.

Spring Restful Service JSON with POST using Jodatime DATETIME returning http status 415

$ curl -i -X POST -H "Content-Type:application/json" -H "Accept:application/json" http://localhost:8080/myapp/login -d '{"username":"someuser","password":"0","deviceId":"5","deviceTime":"2014-12-12 11:55:05.987"}'
Returning HttpStatus 415
Server side log showing exception with
TRACE HandlerMethod - Error resolving argument [0] [type=com.npt.ws.model.MobileUserLoginRequest]
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported
dispatcher-servlet.xml containing
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd">
<!-- Activates mapping of #Controller -->
<context:component-scan base-package="com.npt.ws.web">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- Activates #Autowired for Controllers -->
<context:annotation-config proxy-target-class="true"/>
<!--Jackson - objectMapper format date setting -->
<bean id="objectMapper"
class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
p:indentOutput="true" p:simpleDateFormat="yyyy-MM-dd HH:mm:ss.SSS">
</bean>
<!--Jackson - registerModule JodaModule -->
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"
p:targetObject-ref="objectMapper" p:targetMethod="registerModule">
<property name="arguments">
<list>
<bean class="com.fasterxml.jackson.datatype.joda.JodaModule" />
</list>
</property>
</bean>
<!-- Spring MVC: setting objectMapper in converter MappingJackson2HttpMessageConverter-->
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
LoginRequest class
import java.sql.Timestamp;
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.joda.time.DateTime;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.npt.ws.utils.CustomDateDeSerializer;
import com.npt.ws.utils.CustomDateSerializer;
public class MobileUserLoginRequest {
private String username;
private String password;
private String deviceId;
private String deviceName;
private String devicePhoneNum;
private String serviceCarrierId;
private String deviceType;
private String deviceOS;
private String browserName;
private String browserVersion;
private String deviceModel;
private String appVersion;
private DateTime deviceTime;
private Double lattitude;
private Double longitude;
private String devicePowerStatus;
private Integer deviceBatteryRemaining;
private Integer appRAMUsed;
private Integer deviceAvailableRAM;
private Integer deviceSDAvailableSpace;
private String ipAddress;
private String locationAPI;
private String locationAPIAccuracy;
public MobileUserLoginRequest() {
super();
}
public MobileUserLoginRequest(String username, String password,
String deviceId) {
super();
this.username = username;
this.password = password;
this.deviceId = deviceId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getDevicePhoneNum() {
return devicePhoneNum;
}
public void setDevicePhoneNum(String devicePhoneNum) {
this.devicePhoneNum = devicePhoneNum;
}
public String getServiceCarrierId() {
return serviceCarrierId;
}
public void setServiceCarrierId(String serviceCarrierId) {
this.serviceCarrierId = serviceCarrierId;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public String getDeviceOS() {
return deviceOS;
}
public void setDeviceOS(String deviceOS) {
this.deviceOS = deviceOS;
}
public String getBrowserName() {
return browserName;
}
public void setBrowserName(String browserName) {
this.browserName = browserName;
}
public String getBrowserVersion() {
return browserVersion;
}
public void setBrowserVersion(String browserVersion) {
this.browserVersion = browserVersion;
}
public String getDeviceModel() {
return deviceModel;
}
public void setDeviceModel(String deviceModel) {
this.deviceModel = deviceModel;
}
public String getAppVersion() {
return appVersion;
}
public void setAppVersion(String appVersion) {
this.appVersion = appVersion;
}
//#JsonSerialize(using = CustomDateSerializer.class)
public DateTime getDeviceTime() {
return deviceTime;
}
//#JsonDeserialize(using = CustomDateDeSerializer.class)
public void setDeviceTime(DateTime deviceTime) {
this.deviceTime = deviceTime;
}
public void setDeviceTime(Timestamp deviceTime) {
this.deviceTime = new DateTime(deviceTime.getTime());
}
public Double getLattitude() {
return lattitude;
}
public void setLattitude(Double lattitude) {
this.lattitude = lattitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public String getDevicePowerStatus() {
return devicePowerStatus;
}
public void setDevicePowerStatus(String devicePowerStatus) {
this.devicePowerStatus = devicePowerStatus;
}
public Integer getDeviceBatteryRemaining() {
return deviceBatteryRemaining;
}
public void setDeviceBatteryRemaining(Integer deviceBatteryRemaining) {
this.deviceBatteryRemaining = deviceBatteryRemaining;
}
public Integer getAppRAMUsed() {
return appRAMUsed;
}
public void setAppRAMUsed(Integer appRAMUsed) {
this.appRAMUsed = appRAMUsed;
}
public Integer getDeviceAvailableRAM() {
return deviceAvailableRAM;
}
public void setDeviceAvailableRAM(Integer deviceAvailableRAM) {
this.deviceAvailableRAM = deviceAvailableRAM;
}
public Integer getDeviceSDAvailableSpace() {
return deviceSDAvailableSpace;
}
public void setDeviceSDAvailableSpace(Integer deviceSDAvailableSpace) {
this.deviceSDAvailableSpace = deviceSDAvailableSpace;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getLocationAPI() {
return locationAPI;
}
public void setLocationAPI(String locationAPI) {
this.locationAPI = locationAPI;
}
public String getLocationAPIAccuracy() {
return locationAPIAccuracy;
}
public void setLocationAPIAccuracy(String locationAPIAccuracy) {
this.locationAPIAccuracy = locationAPIAccuracy;
}
}
Controller containing
#RequestMapping(value="/login", method=RequestMethod.POST,
consumes="application/json", produces="application/json"
)
public #ResponseBody MobileUserLoginResponse authenticateUser(#RequestBody final MobileUserLoginRequest loginRequest,HttpServletRequest req, HttpServletResponse res, HttpSession session) {
try {
MobileUserLoginResponse loginResponse = mobileAppLoginManager.authenticateUser(loginRequest);
return loginResponse;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Use the enum, MediaType.APPLICATION_JSON_VALUE when declaring consumes and produces.