1. 程式人生 > >Struts2學習(四)

Struts2學習(四)

ade 定向 std lan nio sha symphony als ini

struts-defualt.xml指定的result的類型

1、struts-defualt.xml 文件的 181 行 開始定義了:

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

2、所有的 <result> 默認的名稱 ( name ) 都是 success ,默認的 類型 ( type ) 都是 dispatcher
3、dispatcher 等同於 RequestDispatcher 中的 forward 操作 ,redirect 等同於 HttpServletResponse 中的 sendRedirect 操作

4、當 type = "redirect" 時,可以指定任意的位置

 <result type="redirect">http://www.google.com</result>

redirectAction 類似於 redirect , 與 redirect 不同的是它專門重定向到 <action>

<result name="success" type="redirectAction">
  <param name="namespace">/customer</param>
  <param name="actionName">page/success/register</param>
</result>
全局的 result 1、<global-results>在這裏所寫的 result 屬於當前包 的全局 result,當前包 的所有<action>可以訪問 2、action標簽呢的result屬於局部的result,僅僅當前的 <action> 可以訪問 控制異常

1、<global-exception-mappings>全局的異常映射,裏面的result只能引用全局的result
2、測試案例 index.jsp
<%@ page language = "java" pageEncoding = "UTF-8" %>
<%@ page contentType = "text/html; charset= UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Apache Struts</title> <style type="text/css"> .container { width: 90% ; margin: 10px auto ; box-shadow: 0px 0px 5px 4px #dedede ; padding: 5px 5px ; } ul .required { color : blue ; } ul li { font-size: 16px ; padding: 5px 5px ; } </style> </head> <body>      <div class="container"> <h4> &lt;global-results&gt; 和 &lt;global-exception-mappings&gt; :</h4> <a href="${ pageContext.request.contextPath }/throw/hello?throw=true" >發生異常</a> <a href="${ pageContext.request.contextPath }/throw/hello?throw=false" >不發生異常</a> </div> </body> </html>

struts.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
  <package name="throw" namespace="/throw" extends="struts-default">

        <global-results>
            <!-- 在這裏所寫的 result 屬於當前包 的全局 result -->
            <result name="index" type="redirect">/results/index.jsp</result>
            <result name="exception" type="dispatcher">/results/catch.jsp</result>
        </global-results>
        <!-- 全局的exception只能引用全局的result -->
        <global-exception-mappings>
            <exception-mapping exception="java.lang.RuntimeException"
                result="exception" />
        </global-exception-mappings>

        <action name="hello" class="ecut.results.action.HelloAction">
            <!-- 僅僅當前的 <action> 可以訪問,屬於局部的 result -->
            <result name="success" type="dispatcher">/results/hello.jsp</result>
        </action>

    </package>
</struts>

Action類

package ecut.results.action;

import com.opensymphony.xwork2.Action;

public class HelloAction implements Action {
    
    private boolean t ;

    @Override
    public String execute() throws Exception {
        System.out.println(t);
        if( t ) {
            throw new RuntimeException( "出錯了" );
        }
        return SUCCESS;
    }
    //jsp中的屬性名要和get方法保持一致
    public boolean getThrow(){
        return this.t ;
    }
    
    public void setThrow( boolean t ) {
        this.t = t ;
    }

}

jsp中的屬性名只需要和getter setter 方法一致就行

catch.jsp

<%@ page language = "java" pageEncoding = "UTF-8" %>
<%@ page contentType = "text/html; charset= UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>catch</title> </head> <body> <h1>catch</h1> </body> </html>

hello.jsp

<%@ page language = "java" pageEncoding = "UTF-8" %>
<%@ page contentType = "text/html; charset= UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>hello</title> </head> <body> <h1>Hello</h1> </body> </html>

struts-plugin.xml中定義的result-type

1、struts-defualt.xml的json-default包中定義的result-type

<result-types>
  <result-type name="json" class="org.apache.struts2.json.JSONResult"/>
  <result-type name="jsonActionRedirect" class="org.apache.struts2.json.JSONActionRedirectResult"/>
</result-types>

2、struts2-json-plugin測試案例

添加需要的jar包,下載鏈接https://files.cnblogs.com/files/AmyZheng/jckson%E4%BE%9D%E8%B5%96%E5%8C%85.rar

普通方法將object轉換json代碼如下:

package ecut.results.action;

import java.io.IOException;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;

import ecut.results.entity.Customer;

public class test {
    public static void main(String[] args) throws IOException {
        Customer c = new Customer();
        c.setPassword("123456");
        c.setConfirm("123456");
        c.setUsername("Amy");
        ObjectMapper  mapper = new ObjectMapper ();
        String json = mapper.writeValueAsString(c);
        System.out.println(json);
        Customer customer = mapper.readValue(json, Customer.class);
        System.out.println(customer.getUsername()+","+customer.getPassword());
        
        Map<?,?> map = mapper.readValue(json, Map.class);
        for(Map.Entry<?, ?> entry: map.entrySet()){
            System.out.println(entry.getKey()+":"+ entry.getValue());
        }
    }
}

利用Struts2插件將json進行轉換,代碼如下:

index.jsp

<%@ page language = "java" pageEncoding = "UTF-8" %>
<%@ page contentType = "text/html; charset= UTF-8"%>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Apache Struts</title> <style type="text/css"> .container { width: 90% ; margin: 10px auto ; box-shadow: 0px 0px 5px 4px #dedede ; padding: 5px 5px ; } ul .required { color : blue ; } ul li { font-size: 16px ; padding: 5px 5px ; } </style> </head> <body>   <div class="container"> <h4> 使用 json 類型 :</h4> <a href="${ pageContext.request.contextPath }/json/customer" >Java Bean</a> <a href="${ pageContext.request.contextPath }/json/map" >Map</a> </div> </body> </html>

struts.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
   <!-- JSON : JavaScript Object Notation -->
    <!-- json-default繼承了struts-default並擴展了他 -->
    <package name="json" namespace="/json" extends="json-default">

        <default-class-ref class="ecut.results.action.JsonAction" />

        <action name="customer" method="bean">
            <result name="success" type="json">
                <!-- 指定 root 參數,可以確定 只將哪個屬性 轉換為 JSON 格式 -->
                <param name="root">customer</param>
            </result>
        </action>

        <action name="map" method="map">
            <result name="success" type="json">
                <param name="root">map</param>
            </result>
        </action>

    </package>
</struts>

指定 root 參數,可以確定 只將哪個屬性 轉換為 JSON 格式

Action類

package ecut.results.action;

import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.Action;
import ecut.results.entity.Customer;

public class JsonAction implements Action {

    private Customer customer;

    private Map<String, Integer> map;

    @Override
    public String execute() throws Exception {
        return SUCCESS;
    }

    public String map() throws Exception {

        map = new HashMap<>();

        map.put("各種粉", 4);
        map.put("藜蒿炒臘肉", 5);
        map.put("瓦罐湯", 3);
        return SUCCESS;
    }

    public String bean() throws Exception {

        customer = new Customer();

        customer.setUsername("張三豐");
        customer.setPassword("hello2017");

        return SUCCESS;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public Map<String, Integer> getMap() {
        return map;
    }

    public void setMap(Map<String, Integer> map) {
        this.map = map;
    }

}

添加json註解,是密碼和確認密碼不要進行序列化

result-type為stream

1、通過result的type=“stream”來處理。 2、參數說明:
  • contentType:指定文件類型,默認為text/plain即純文本.(更多類型可查詢tomcat安裝目錄下的conf目錄的web.xml文件,例如application/vnd.ms-excel:Excel下載;application/octet-stream:文件下載),此處用image/jpeg:得到驗證碼圖片。
  • inputName:指定action中inputStream類型的屬性名稱,需要getter方法。
  • contentDisposition:指定文件下載的處理方式,包括內聯(inline)和附件(attachment)兩種方式,而附件方式會彈出文件保存對話框,
  • 否則瀏覽器會嘗試直接顯示文件。取值為:attachment;filename="${fileName}",表示文件下載的時候取名為通過EL表達式進行獲取;如果只有
  • filename="${fileName}"如同inline;filename="${fileName}",瀏覽器會嘗試在線打開它;如果未指定filename屬性則以瀏覽器的頁面名作為文件名。
  • bufferSize:輸出時緩沖區的大小設置為 attachment 將會告訴瀏覽器下載該文件,filename 指定下載文件保有存時的文件名,若未指定將會是以瀏覽的頁面名作為文件名,如以 download.action 作為文件名。這裏使用的是動態文件名,${fileName}。它將通過 Action 的 getFileName() 獲得文件名。也就是說Action裏面要有一個getFileName ()的方法。

3、上傳和展示圖片測試案例

index.jsp

<%@ page language = "java" pageEncoding = "UTF-8" %>
<%@ page contentType = "text/html; charset= UTF-8"%>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Apache Struts</title> <style type="text/css"> .container { width: 90% ; margin: 10px auto ; box-shadow: 0px 0px 5px 4px #dedede ; padding: 5px 5px ; } ul .required { color : blue ; } ul li { font-size: 16px ; padding: 5px 5px ; } </style> </head> <body> <div class="container"> <h4> 使用 stream 類型 :</h4> <a href="${ pageContext.request.contextPath }/stream/show" >顯示</a> <a href="${ pageContext.request.contextPath }/stream/down" >下載</a> <!-- 可以在 URL 中傳遞被下載的文件名,Action 中的 name 屬性負責接收 --> <a href="${ pageContext.request.contextPath }/stream/down?name=study.jpg" >下載</a> </div> </body> </html>

struts.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
<package name="stream" namespace="/stream" extends="struts-default">

        <default-class-ref class="ecut.results.action.ImageAction" />

        <action name="show">
            <param name="storePath">C:/Users/Administrator/Pictures</param>
            <result name="success" type="stream">
                <!-- inputName 屬性用來指定 從哪個輸入流中讀取 文件 , 默認名稱是 inputStream ( InputStream 
                    類型 ) -->
                <param name="inputName">inputStream</param>
                <param name="contentType">image/jpeg</param>
                <param name="contentDisposition">inline</param>
            </result>
        </action>

        <action name="down">
            <param name="storePath">C:/Users/Administrator/Pictures</param>
            <result name="success" type="stream">
                <param name="inputName">inputStream</param>
                <param name="contentType">image/jpeg</param>
                <param name="contentDisposition">attachment;filename="${ name }"</param>
            </result>
        </action>
    </package>
</struts>

Action類

package ecut.results.action;

import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.opensymphony.xwork2.Action;

public class ImageAction implements Action {
    
    private String storePath ; // 文件的存儲目錄
    
    private String name ; // 被下載的文件的名稱
    
    private InputStream inputStream ;

    @Override
    public String execute() throws Exception {
        
        name = "學習.jpg" ;
        
        // inputStream = new FileInputStream( "C:/" + name ) ; 
        
        Path path = Paths.get( storePath , name  ) ;
        inputStream = Files.newInputStream( path );
        
        name = URLEncoder.encode( name , "UTF-8" );
        
        return SUCCESS;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStorePath() {
        return storePath;
    }

    public void setStorePath(String storePath) {
        this.storePath = storePath;
    }
    
}

轉載請於明顯處標明出處

https://www.cnblogs.com/AmyZheng/p/9207275.html

Struts2學習(四)