Create JSON Response in Spring MVC Project

If you finding trouble making json response in your spring project, Please find below simple steps to do that,

Step 01

Add below code snippets in your pom.xml file
<!-- Jackson JSON Mapper -->
 <dependency>
 <groupId>org.codehaus.jackson</groupId>
 <artifactId>jackson-mapper-asl</artifactId>
 <version>1.9.13</version>
 </dependency>
 <dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-core</artifactId>
 <version>2.4.1</version>
 </dependency>
 <dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
 <version>2.4.1.1</version>
 </dependency>

Step 02

Add below code in you spring configuration xml file

 
<!-- Configure to plugin JSON as request and response in method handler --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> 
<property name="messageConverters"> 
<list> 
<ref bean="jsonMessageConverter"/> 
</list> 
</property> 
</bean> 

<!-- Configure bean to convert JSON to POJO and vice versa --> 
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean> 

Step 03:

Below is the simple example of a controller methode which convert SystemUser Java entity class map returns as a json.

@RequestMapping(value="getSystemUser", method=RequestMethod.GET)
 public @ResponseBody Map<String, Object> getSystemUser(@RequestParam("userId") long userId, HttpServletRequest request){
 SystemUser systemUser = systemUserService.getSystemUser(userId);
 return systemUser.toMap();
 }

If you want to refer my SystemUser object , please find it below.

package com.isd.sappu.savari.domains;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@Entity
@Table(name="users")
public class SystemUser implements Serializable{

 private static final long serialVersionUID = 5489679679570043539L;

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private long userId;
 
 private String username;
 
 private String password;
 
 private String firstName;
 
 private String lastName;
 
 private String address;
 
 private String profilePic;
 
 private Date dateOfBirth;
 
 private String mobileNo;
 
 private String workNo;
 
 private String homeNo;
 
 private double latitude;
 
 private double longtitude;
 
 private int accuracy;
 
 private int activeStatus;
 
 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<Favorite> favoriteList;
 
 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<Comment> commentList;
 
 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<Rating> ratingList;
 
 @OneToMany(mappedBy="sender")
 @Cascade(CascadeType.ALL)
 private List<Message> messageSentList;
 
 @OneToMany(mappedBy="receiver")
 @Cascade(CascadeType.ALL)
 private List<Message> messageRecievedList;
 
 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<Product> productList;

 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<SystemUserRole> systemUserRoleList;
 
 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<SearchRequest> searchRequestList;
 
 
 
 public long getUserId() {
 return userId;
 }

 public void setUserId(long userId) {
 this.userId = userId;
 }

 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 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 getAddress() {
 return address;
 }

 public void setAddress(String address) {
 this.address = address;
 }

 public String getProfilePic() {
 return profilePic;
 }

 public void setProfilePic(String profilePic) {
 this.profilePic = profilePic;
 }

 public Date getDateOfBirth() {
 return dateOfBirth;
 }

 public void setDateOfBirth(Date dateOfBirth) {
 this.dateOfBirth = dateOfBirth;
 }

 public String getMobileNo() {
 return mobileNo;
 }

 public void setMobileNo(String mobileNo) {
 this.mobileNo = mobileNo;
 }

 public String getWorkNo() {
 return workNo;
 }

 public void setWorkNo(String workNo) {
 this.workNo = workNo;
 }

 public String getHomeNo() {
 return homeNo;
 }

 public void setHomeNo(String homeNo) {
 this.homeNo = homeNo;
 }

 public List<Favorite> getFavoriteList() {
 return favoriteList;
 }

 public void setFavoriteList(List<Favorite> favoriteList) {
 this.favoriteList = favoriteList;
 }

 public List<Comment> getCommentList() {
 return commentList;
 }

 public void setCommentList(List<Comment> commentList) {
 this.commentList = commentList;
 }

 public List<Rating> getRatingList() {
 return ratingList;
 }

 public void setRatingList(List<Rating> ratingList) {
 this.ratingList = ratingList;
 }

 public List<Message> getMessageSentList() {
 return messageSentList;
 }

 public void setMessageSentList(List<Message> messageSentList) {
 this.messageSentList = messageSentList;
 }

 public List<Message> getMessageRecievedList() {
 return messageRecievedList;
 }

 public void setMessageRecievedList(List<Message> messageRecievedList) {
 this.messageRecievedList = messageRecievedList;
 }

 public List<Product> getProductList() {
 return productList;
 }

 public void setProductList(List<Product> productList) {
 this.productList = productList;
 }

 public List<SystemUserRole> getSystemUserRoleList() {
 return systemUserRoleList;
 }

 public void setSystemUserRoleList(List<SystemUserRole> systemUserRoleList) {
 this.systemUserRoleList = systemUserRoleList;
 }

 public int getActiveStatus() {
 return activeStatus;
 }

 public void setActiveStatus(int activeStatus) {
 this.activeStatus = activeStatus;
 }

 public List<SearchRequest> getSearchRequestList() {
 return searchRequestList;
 }

 public void setSearchRequestList(List<SearchRequest> searchRequestList) {
 this.searchRequestList = searchRequestList;
 }

 public double getLatitude() {
 return latitude;
 }

 public void setLatitude(double latitude) {
 this.latitude = latitude;
 }

 public double getLongtitude() {
 return longtitude;
 }

 public void setLongtitude(double longtitude) {
 this.longtitude = longtitude;
 }

 public int getAccuracy() {
 return accuracy;
 }

 public void setAccuracy(int accuracy) {
 this.accuracy = accuracy;
 }
 
 public Map<String, Object> toMap() {
 Map<String, Object> map = new HashMap<String, Object>();
 map.put("userId", userId);
 map.put("username", username);
 map.put("address", address);
 map.put("mobileNo", mobileNo);
 map.put("latitude", latitude);
 map.put("longtitude", longtitude);
 map.put("accuracy", accuracy);
 map.put("activeStatus", activeStatus);
 return map;
 }
 
}

That’s all, Enjoy your json experience.

Thank you…!!!

Enable File uploading in your Spring application

If you are struggling make file uploading in your spring application, most of the time this may be the cause. We always forgot small things when we configure and setup our project.

Add below code in your application context xml file. This will do the magic you want



<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />


Now you can use CommonsMultipartFile in your controller just like below,


@RequestMapping(value="userprofile", method=RequestMethod.POST)
public String getUserProfile(@RequestParam("inputProfilePic") @Null CommonsMultipartFile profilePicture, HttpServletRequest request){

return "profilepage";

}

That’s all, Enjoy file uploading.

Thanks

Retrieve Geo Location from Your browser

If you web application needs location of the user this is the code you want. But remember this is HTML 5 and won’t work with your old web browsers.

In most cases this gives the correct location of the user depends on the device capabilities. If user uses a mobile device GPS enabled this gives the exact location, but if it’s not it uses ip addresses and other signalling details to detect the location which not be very accurate.



<script type="text/javascript">

function success(pos) {
var crd = pos.coords;

console.log('Your current position is:');
console.log('Latitude : ' + crd.latitude);
console.log('Longitude: ' + crd.longitude);
console.log('More or less ' + crd.accuracy + ' meters.');
};

function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};

var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};

navigator.geolocation.getCurrentPosition(success, error, options);

</script>


Any way that’s all folks, have fun with you location enabled web applications.

Thanks

Make Your Website Mobile Compatible

When you read the title you will be amazed can we make any website mobile compatible…? When we make our website we always consider the mobile web browsers, So we use bootrap, jquery mobile, ..etc to create mobile compatible websites.

Even you create your website compatible to mobile browsers, you will notice in your mobile website view too smaller even you can’t touch a button. The case is in default settings website views in very normal condition, since your mobile resolution is so good than your laptop, the website in mobile browser looks tiny.

Simple task you need to do to make it right. Ad below meta tag to your website header.


<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">

That’s all folks,

Thanks