struts一个action对应多个路径和json数据支持

Updated on in 程序人生 with 0 views and 0 comments

action配置多个路径

配置xml

<package name="helloAction" extends="struts-default,json-default"  namespace="/myHello" >
        <action name="helloWorld" class="helloAction">
            <result name="helloPage">/WEB-INF/hello.jsp</result>
            <result name="sayHello" type="json">
                <param name="root">user</param>
            </result>
        </action>
    </package>

在action中定义多个result,如上,第一个路径返回的是页面,第二个路径返回了一个json数据

action配置

action中也要配置对应的方法

import cn.com.wyl.examples.struts.entity.User;
import cn.com.wyl.examples.struts.service.HelloService;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.json.JSONUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component(value = "helloAction")
public class HelloAction extends ActionSupport {

    private User user;

    @Resource
    private HelloService helloService;

    public String sayHello() {
        this.user = new User();
        this.user.setUsername(helloService.sayHello());
        return "sayHello";
    }

    public String helloPage(){
        return "helloPage";
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

public class User {
    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

访问

此时访问的路径格式

/namespace/actionname!方法名.配置的后缀

此处的两个接口访问地址为

/myHello/helloWorld!helloPage.do

/myHello/helloWorld!sayHello.do

json数据支持

引入maven依赖

<properties>
        <struts.verson>2.3.4.1</struts.verson>
    </properties>
   <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-json-plugin</artifactId>
            <version>${struts.verson}</version>
        </dependency>

返回json数据

xml的result中配置param属性,这里返回user

image.png

action中也要有user这个属性

image.png


标题:struts一个action对应多个路径和json数据支持
作者:wenyl
地址:http://www.wenyoulong.com/articles/2021/01/06/1609923456021.html