Monday 20 April 2015

Struts2 : Return JSON response

In this tutorial, you are going to learn how to return JSON response using struts2 json plugin.

Step 1: Create new dynamic web project in eclipse.

Give project name as “struts_tutorial” and press next.


Press next and tick the check box “Generate web.xml deployment descriptor” and press finish.

Project structure looks like below.

Step 2: Convert project to maven project.

Right click on the project -> go to configure -> Convert to Maven Project


Give Group Id, Artifact Id as “struts_tutorial” and press finish.


Now, project structure looks like below.

Step 3: Open pom.xml and update maven dependencies for struts2 and struts2 json plugin.

pom.xml looks like below.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>struts_tutorial</groupId>
 <artifactId>struts_tutorial</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>war</packaging>
 <properties>
  <struts_version>2.3.20</struts_version>
 </properties>


 <build>
  <sourceDirectory>src</sourceDirectory>
  <plugins>
   <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>1.6</source>
     <target>1.6</target>
    </configuration>
   </plugin>
   <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.4</version>
    <configuration>
     <warSourceDirectory>WebContent</warSourceDirectory>
     <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
   </plugin>
  </plugins>
 </build>

 <dependencies>
  <dependency>
   <groupId>org.apache.struts</groupId>
   <artifactId>struts2-core</artifactId>
   <version>${struts_version}</version>
  </dependency>
  <dependency>
   <groupId>org.apache.struts</groupId>
   <artifactId>struts2-json-plugin</artifactId>
   <version>${struts_version}</version>
  </dependency>
 </dependencies>

</project>

Step 4: In struts2 environment, we should handover the requests to struts2. We do this by configuring web.xml.

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>struts_tutorial</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>


As you observe web.xml, we are forwarding all the requests to struts2 environment by using filter mapping. So now it is struts2 responsibility to process this request.

Step 5: Create Action class “EmployeeAction.java”, under the package “com.sample”.

package com.sample;

import com.opensymphony.xwork2.Action;

public class EmployeeAction {

 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;
 }

 public String execute() {
  return Action.SUCCESS;
 }
}

Step 6: It is time to create 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, so 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.

To output the JSON data, you need to declare a package which extends the “json-default“, and result type as “json“.

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">
        <action name="hello" class="com.sample.EmployeeAction">
            <result type="json" />
        </action>
    </package>
</struts>

Step 7 : Run the application and hit the following URL.


Total project structure looks like below.

Exclude some properties from json response
If you want, you can exclude some properties from json response.


To exclude properties “firstName” and “id” update struts.xml like below.
<action name="hello" class="com.sample.EmployeeAction">
         <result type="json">
                  <param name="excludeProperties">
                           firstName, id
                  </param>
         </result>
</action>


Update struts.xml like below.

<!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">
  <action name="hello" class="com.sample.EmployeeAction">
   <result type="json">
    <param name="excludeProperties">
     firstName, id
    </param>
   </result>
  </action>
 </package>
</struts>


Run the following URL again,

You will get only lastName is response.

{"lastName":"Gurram"}

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment