SSH学习-struts2的result类型

在学习struts2整合spring的过程中,以前result类型只有name属性,后面发现struts-default.xml中定义了10种result类型,在result标签中可以使用type属性来指定是哪种类型,接下来对常用的几种类型做案例进行理解。

result常用类型

result类型参考struts-default.xml中对result的配置,如下所示:

        <result-types>
            <result-type name="chain" class="com.opensymphony.xwork2.ActionChainResult"/>
            <result-type name="dispatcher" class="org.apache.struts2.dispatcher.ServletDispatcherResult" default="true"/>
            <result-type name="freemarker" class="org.apache.struts2.views.freemarker.FreemarkerResult"/>
            <result-type name="httpheader" class="org.apache.struts2.dispatcher.HttpHeaderResult"/>
            <result-type name="redirect" class="org.apache.struts2.dispatcher.ServletRedirectResult"/>
            <result-type name="redirectAction" class="org.apache.struts2.dispatcher.ServletActionRedirectResult"/>
            <result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>
            <result-type name="velocity" class="org.apache.struts2.dispatcher.VelocityResult"/>
            <result-type name="xslt" class="org.apache.struts2.views.xslt.XSLTResult"/>
            <result-type name="plainText" class="org.apache.struts2.dispatcher.PlainTextResult" />
        </result-types>

其中常用的类型就是dispatcher, redirectAction, redirect, stream, json,其具体作用如下:

(1)dispatcher:默认类型,转发

(2)redirectAction:重定向到其他action,语法有两种,参考struts.xml中配置

(3)redirect:重定向URL,也有两种写法,参考struts.xml中配置

(4)stream:用于图片的传输下载,可以参考struts2 API文档进行配置

(5)json:服务器向浏览器发送数据类型

案例说明-dispatcher、redirectAction、redirect

案例以用户提交action请求时,提交num属性的值,不同的数字返回不同的result类型,从而达到测试理解的效果。这里主要讲struts.xml中的配置,以及action对应类的写法,其他的配置省略。

(1)struts.xml中的配置,具体参考注释部分。

  <package name="demo" namespace="/hello" extends="struts-default">
    <!-- 当和Spring整合后,class不需要写全名,使用bean id即可,默认为类名首字母小写 -->
    <action name="helloStruts" class="helloStruts"> 
       <result name="success">
         /WEB-INF/helloStruts.jsp
       </result>
    </action>
  </package>

  <!-- result类型测试 -->
  <package name="result" namespace="/result" extends="struts-default">
    <action name="helloStruts" class="helloStruts">
      <result name="success">
        /WEB-INF/helloStruts.jsp
      </result>      
    </action>       
       <!-- 用户提交不同的数字,实现dispatcher,redirectAction,redirect三种功能 -->
       <action name="sw" class="switchAction" method="doSwitch">
         <!-- 返回1,实现转发 -->
         <result name="1" type="dispatcher">
           /WEB-INF/helloStruts.jsp
         </result>
         <!-- 返回2,实现重定向到其他action -->
         <!-- 转发到内部的action -->
         <result name="2" type="redirectAction">
           helloStruts
         </result>
         <!-- 转发到其他的action -->
         <result name="3" type="redirectAction">
           <param name="namespace">/hello</param>
           <param name="actionName">helloStruts</param>
         </result>
         <!-- 转发到URL -->
         <result name="4" type="redirect">
           https://www.cnblogs.com/youngchaolin/
         </result>
       </action>      
       
  </package>

(2)控制器类switchAction中代码,用num属性来接受用户提交的数字。

package Controller;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

/**
 * 用户从浏览器提交不同的数字,得到不同的result处理结果
 * @author yangchaolin
 *
 */
@Controller("switchAction")
@Scope("prototype")
public class switchAction {
    
    //属性,用于接受用户提交的数字
    private int num;

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }
    
    //具体自定义执行方法
    //方法里写参数会报错,不写参数就OK
    public String doSwitch() {
          String numStr=Integer.toString(num);
          System.out.println("用户提交的数字为:"+numStr);
          return numStr;
    }

}

测试结果-dispatcher、redirectAction、redirect

(1)num提交数字1

当用户提交1,执行的result为转发,直接跳转到jsp页面并显示结果。

(2)num提交数字2

当用户提交2时,会跳转到/result/helloStruts.action请求,此时跳转范围在/result下,为内部跳转action。

 (3)num提交数字3

当用户提交3时,会跳转到/hello/helloStruts.action请求,此时跳转范围在/hello下,为外部跳转action。

(4)num提交数字4

当用户提交4时,会跳转到自己的博客园地址,为重定向到URL,上面只写了一种,另一种跟redirectAction类似,也是需要使用param标签。

         <result type="redirect">
           <param name="location">
             https://www.cnblogs.com/youngchaolin/
           </param>
         </result>

案例分析-stream

result类型为stream时,采用浏览器从服务端获取图片的案例,这里需要参考struts2 API来进行result的配置,如下是API描述,常用的几个参数为:

(1)contentType:发送到浏览器的类型,默认为text/plain

(2)contentLength:对应字节数组的长度

(3)inputName:为action实现类中inputStream属性的名字

(4)bufferSize:传输缓冲大小,默认1024byte ,即1kib

(5)contentDisposition:强制下载时需要配置

这里也配置了struts.xml,另外还有实现类,其他省略。

(1)struts.xml中的配置,其中主要配置好contentType和inputName就可以显示服务端生成的图片,其中inputName对应的参数值image,需要action实现类中属性InputStream的变量名一致,如果还需要强制下载,就需要配置contentDisposition。

       <!-- result类型指定为stream,浏览器向服务端请求一张图片,并显示在网页 -->
       <action name="image" class="imageAction">
         <result name="success" type="stream">
           <param name="contentType">image/png</param>
           <param name="inputName">image</param>
           <param name="contentDisposition">attachment;filename="test.png"</param>
           <param name="bufferSize">1024</param>
         </result>
       </action>

(2)控制器imageAction中的写法,其中在服务端生成图片,并将图片内容转换成字节数组,然后利用字节数组作为参数初始化InputStream。

package Controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

/**
 * 服务端给浏览器发送图片
 * @author yangchaolin
 *
 */
@Controller("imageAction")
@Scope("prototype")
public class imageAction {
    
    //属性
    //属性名需要和struts.xml配置文件中inputName属性值一致
    InputStream image;

    //浏览器从服务器获取图片需要设置get方法,使用工具一般两个都配置了
    public InputStream getImage() {
        return image;
    }

    public void setImage(InputStream image) {
        this.image = image;
    }
    
    //具体执行方法
    public String execute() throws IOException {
        //准备画布
        BufferedImage img=new BufferedImage(200,200,BufferedImage.TYPE_INT_RGB);
        //准备画笔
        Graphics2D g=img.createGraphics();
        //画图
        g.setColor(Color.CYAN);
        Font font=new Font("微软雅黑",Font.BOLD,20);
        g.setFont(font);
        g.drawString("Hello Struts2", 30, 100);        
        //将图片转换成字节数组
        ByteArrayOutputStream out=new ByteArrayOutputStream();
        ImageIO.write(img, "png", out);
        byte[] imgByte=out.toByteArray();
        //将字节数组作为参数,传入inputStream构造方法
        image=new ByteArrayInputStream(imgByte);
        return "success";
    }

}

测试结果-stream

案例分析-json

返回类型为json,测试服务端向浏览器发送数据,这里需要注意的是10种基本类型里没有json,为了result类型可以使用json,需要导入struts2-json-plugin包,此外package里extends属性值,需修改成json-default,且默认的struts-default继承自json-default。

(1)struts.xml中的配置

  <!-- result类型测试 -->
  <package name="result" namespace="/result" extends="json-default"><!-- 如果result类型有json,extends属性值为json-default -->
    <action name="helloStruts" class="helloStruts">
      <result name="success">
        /WEB-INF/helloStruts.jsp
      </result>      
    </action>
       
       <!-- result指定类型为json,有两种发送方式,一种是发送action中的全部属性,一种是发送action中的指定属性 -->
       <!-- 发送全部属性数据 -->
       <action name="test5" class="helloStruts" method="doJson">
         <result type="json"></result>
       </action>
       <!-- 发送用户指定的属性数据 -->
       <action name="test6" class="helloStruts" method="doJson">
         <result type="json">
           <param name="root">age</param>
         </result>
       </action>
  </package>

(2)控制器代码

package Controller;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Controller("helloStruts")
@Scope("prototype")//可以创建多个对象实例,默认为singleton,即单例模式
public class HelloStruts {
    
    //属性
    String message;
    
    //添加一个属性,用户测试json发送数据到浏览器
    String name;
    String age;
    
    
    public String getName() {
        return name;
    }

    //json测试添加的get set方法
    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    //设置set get方法
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
    
    //依赖注入service层实现类
    @Resource(name="helloService")
    public HelloServiceInterface helloService;
    
    //默认execute方法
    public String execute() {
        System.out.println("success");
        message="Hello Struts2+Spring";
        System.out.println(message);
        //调用接口方法
        helloService.hello();
        return "success";
    }
    
    //添加发送json的方法
    public String doJson() {
        message="hello json";
        name="乔峰";
        age="35";
        return "success";
    }

}

测试结果-json

结论

result类型就相当如菜谱名,根据不同的菜谱名可以做出不同的菜,几种常见的result类型,其struts.xml中有对应的配置。

原文地址:https://www.cnblogs.com/youngchaolin/p/10850779.html