Wednesday 25 May 2016

Struts2: Map json data to model object

By using struts2-json-plugin, you can bind json data to model object. In this post, I am going to show you how to send json data as part od post request and bind it to model object.

Step 1: Create new dynamic web project ‘struts2_json’ in eclipse.
File -> new -> Other, select Dynamic Web Project.

Step 2: Mavenize the project. Right click on the project -> Configure -> Convert To Maven project.

Step 3: Update pom.xml for maven dependencies.

pom.xml
<dependencies>

 <dependency>
  <groupId>org.apache.struts</groupId>
  <artifactId>struts2-json-plugin</artifactId>
  <version>2.3.20</version>
 </dependency>


 <dependency>
  <groupId>org.apache.struts</groupId>
  <artifactId>struts2-core</artifactId>
  <version>2.3.20</version>
 </dependency>

</dependencies>

Step 4: Create a package, com.sample. Define Employee.java like below.

Employee.java
package com.sample;

public class Employee {
 private String firstName;
 private String lastName;
 private int 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 int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [firstName=").append(firstName)
    .append(", lastName=").append(lastName).append(", id=")
    .append(id).append("]");
  return builder.toString();
 }

}

Step 5: Create package com.sample.service. Define EmployeeService like below.


EmployeeService.java
package com.sample.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sample.Employee;

public class EmployeeService {
 private static final Map<Integer, Employee> employees = new HashMap<>();

 static {
  Employee emp1 = new Employee();
  Employee emp2 = new Employee();

  emp1.setId(1);
  emp1.setFirstName("Hari Krishna");
  emp1.setLastName("Gurram");

  emp2.setId(2);
  emp2.setFirstName("Sudhir");
  emp2.setLastName("Samp");

  employees.put(1, emp1);
  employees.put(2, emp2);
 }

 public static Employee getEmployee(int id) {
  return employees.get(id);
 }

 public static void addEmployee(Employee emp) {
  int id = emp.getId();
  employees.put(id, emp);
 }

 public static List<Employee> getEmployees() {
  return new ArrayList<>(employees.values());
 }

 public static void printAllEmployees() {
  getEmployees().forEach(System.out::println);
 }
}


Step 6: Create package com.sample.controller. Define EmployeeController like below.

EmployeeController.java

package com.sample.controller;

import com.opensymphony.xwork2.ModelDriven;
import com.sample.Employee;
import com.sample.service.EmployeeService;

public class EmployeeController implements ModelDriven<Employee> {
 Employee emp = new Employee();

 public String addEmployee() {
  EmployeeService.addEmployee(emp);
  EmployeeService.printAllEmployees();
  return "success";
 }

 @Override
 public Employee getModel() {
  return emp;
 }
}

Step 7: Update web.xml like below.
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 <display-name>struts2_json</display-name>
 <welcome-file-list>
  <welcome-file>index.html</welcome-file>
  <welcome-file>index.htm</welcome-file>
  <welcome-file>index.jsp</welcome-file>
  <welcome-file>default.html</welcome-file>
  <welcome-file>default.htm</welcome-file>
  <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>
 <display-name>Struts2 Demo App</display-name>
 
 <filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
 </filter>
 
 <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
</web-app>

Step 8: It is time to define struts.xml. Since Struts 2 requires struts.xml to be present in classes folder. So create struts.xml file under the WebContent/WEB-INF/classes folder. Eclipse does not create the "classes" folder by default, you need to do this yourself. To do this, right click on the WEB-INF folder in the project explorer and select New > Folder.

Create struts.xml file inside classes.

struts.xml

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
 <package name="default" extends="json-default">

  <interceptors>
   <interceptor-stack name="jsonStack">
    <interceptor-ref name="defaultStack">
     <param name="exception.logEnabled">true</param>
     <param name="exception.logLevel">ERROR</param>
     <param name="params.excludeParams">dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,parameters\...*</param>
    </interceptor-ref>
    <interceptor-ref name="json">
     <param name="enableSMD">true</param>
    </interceptor-ref>
   </interceptor-stack>
  </interceptors>
  
  <action name="addEmployee" class = "com.sample.controller.EmployeeController" method = "addEmployee">
   <interceptor-ref name="jsonStack"></interceptor-ref>
   <result type="json" />
  </action>
 </package>
</struts>

My package extends json-default package.
<package name="default" extends="json-default">

You can extends more than one package.
<package name="default" extends="struts-default, tiles-default, json-default">

I defined new interceptor stack "jsonStack" and added it to my action addEmployee. jsonStack interceptor is used to map json data to model object.

Run the application on server.

Hit the url http://localhost:8080/struts2_json/addEmployee by setting content type to “application/json”, pass following data.
{"firstName":"Senthil","id":32143,"lastName":"Kumaran"}

You can see following output in console.

Employee [firstName=Hari Krishna, lastName=Gurram, id=1]
Employee [firstName=Sudhir, lastName=Samp, id=2]
Employee [firstName=Senthil, lastName=Kumaran, id=32143]

First two employees are already existed in employees map, third one is newly added. I used Advanced Rest client plugin to send post data.





Previous                                                 Next                                                 Home

No comments:

Post a Comment