Struts2 learning - ajax returns JSON

    Ajax is often used in our development process, so what happens when ajax encounters struts2? Usually the author returns data in json format from the server when using the ajax process. Let's talk about how to return json data through struts2.

    First look at the configuration of action in my struts2 configuration file

<package name="account" extends="struts-default" namespace="/account">
  
    <action name="add" method="addAccount"
            class="org.lian.account.actions.AccountAction" >
        <result type="stream">
	        <param name="contentType">text/html</param>
	        <param name="inputName">inputStream</param>
    	</result>
    </action>
  
  </package>

    Next is Action, Java class design

public class AccountAction extends ActionSupport {

	private InputStream inputStream;

	public InputStream getInputStream() {
		return inputStream;
	}

	public String addAccount() throws IOException {

		Map<String, String> map = new HashMap<String, String>();
		map.put("flag", "Added successfully");
		String result = GsonUtil.getInstance().convertToJson(map);
		inputStream = new ByteArrayInputStream(result.getBytes("UTF-8"));
		return SUCCESS;
	}
}

    Java objects and json strings are converted to each other, using google's gson toolkit, the version used is 2.8.0, the following is the code of my tool class

import com.google.gson.Gson;

public class GsonUtil {

	private static GsonUtil util;

	private GsonUtil() {

	}

	public static GsonUtil getInstance() {

		if (util == null)
			util = new GsonUtil ();
		return useful;

	}

	/**
	 *
	 * @Description EVERYTHING
	 * @param obj
	 * @return
	 * @return String
	 */
	public String convertToJson(Object obj) {
		Gson gson = new Gson ();
		return gson.toJson (obj);
	}

	/**
	 *
	 * @Description EVERYTHING
	 * @param json
	 * @param type
	 * @return
	 * @return T
	 */
	public <T> T parseJson(String json, Class<T> type) {
		Gson gson = new Gson ();
		return gson.fromJson(json, type);
	}

}

     The author has uploaded the gson toolkit, and you can download it yourself if you need it.

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326848051&siteId=291194637