Struts returns json and strutsactionjson through action

Source: Internet
Author: User

Struts returns json and strutsactionjson through action

In fact, it is quite simple for struts2 to return json through action, but it is always forgotten, so it is simply written on the blog. Okay. Start.

First, introduce necessary jar packages:

  Struts2-json-plugin-2.3.24.jar

Then, let's write a simple action.

package com.mz.action;import com.mz.entity.User;import com.opensymphony.xwork2.ActionSupport;public class JsonAction extends ActionSupport{        private User user;    public String execute() {        user = new User();        user.setId(123);        user.setUsername("Irasel");        return SUCCESS;    }    public User getUser() {        return user;    }    public void setUser(User user) {        this.user = user;    }        }

 

Is a very simple action, assign values to the user object, return the value, and return success.

The User class has two attributes, one id and one username, and the corresponding get and set methods.

Configuration files:

<! -- Configure an action that returns a json string --> <package name = "resultJson" namespace = "/" extends = "json-default"> <action name = "resultJson" class =" com. mz. action. jsonAction "> <result name =" success "type =" json "> <! -- Root is part of the ognl expression and cannot be replaced --> <param name = "root"> user </param> </result> </action> </package>

 

Here, root is an attribute of the ognl expression,Cannot be changed! Cannot be changed! Cannot be changed!(Three important events)

Start tomcat and access: http: // localhost: 8080/spring-struts/resultJson (the path here may be different)

:

 

In this case, the json object is successfully returned at the front end. OK!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.