Struts2学习(四)
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>
1、<global-exception-mappings>全局的异常映射,里面的result只能引用全局的result
2、测试案例
<%@ 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> <global-results> 和 <global-exception-mappings> :</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 方法一致就行,必须要有setter方法,getter方法可以省略,这样才可以从jsp中的URL接收到来自页面的参数throw。不然throw默认是false。
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
- 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、Serlet实现上传和下载和展示图片测试案例
下载
package ecut.response; import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths; import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; @WebServlet( "/image/down" )
public class DownloadImageServlet extends HttpServlet { private static final long serialVersionUID = 448136179136896451L; @Override
protected void service(HttpServletRequest request , HttpServletResponse response )
throws ServletException, IOException { request.setCharacterEncoding( "UTF-8" ); response.setCharacterEncoding( "UTF-8" ); //下载文件名称
String filename = "Koala.jpg" ; //保存文件名称
String name = "考拉.jpg" ; Path source = Paths.get( "D:/" , filename ); response.setHeader( "content-type" , "image/jpeg" ); // 响应报头 content-disposition 用来设置 响应正文中的二进制数据是 在浏览器显示 还是 由浏览器下载
name = URLEncoder.encode( name , "UTF-8" ); // 如果文件名中含有汉字,则需要对汉字进行编码 System.out.println( "编码后:" + name ); response.setHeader( "content-disposition" , "attachment;filename='" + name + "'" ); // 获得可以向客户端发送二进制数据的字节输出流
ServletOutputStream out = response.getOutputStream();
// 将 source 中的内容 "复制" 到 out 对应的输出流,实际上就完成了输出操作
Files.copy( source, out ) ; } }
展示
package ecut.response; import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths; import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; @WebServlet( "/image/show" )
public class ShowImageServlet extends HttpServlet { private static final long serialVersionUID = 1376233444161496825L; @Override
protected void service(HttpServletRequest request , HttpServletResponse response )
throws ServletException, IOException {
request.setCharacterEncoding( "UTF-8" );
response.setCharacterEncoding( "UTF-8" ); response.setHeader( "content-type" , "image/jpeg" ); // 响应报头 content-disposition 用来设置 响应正文中的二进制数据是 在浏览器显示 还是 由浏览器下载
response.setHeader( "content-disposition" , "inline" );
//Path接口表示一个目录或一个文件对应的路径(它可以定位本地系统中的一个文件或目录)
//Paths类是一个工具类,其中定义了两个静态方法,专门用来返回Path对象:
//static Path get(String first, String... more)转换的路径字符串,或一个字符串序列,当加入形成一个路径字符串, Path。
Path source = Paths.get( "D:/Koala.jpg" );
//FileInputStream in = new FileInputStream( "D:/Koala.jpg" ); // 获得可以向客户端发送二进制数据的字节输出流
ServletOutputStream out = response.getOutputStream();
// nio将 source 中的内容 "复制" 到 out 对应的输出流,实际上就完成了输出操作
Files.copy( source, out ) ; /*
byte[] bytes = new byte[32] ;
int n ;
while( ( n = in.read( bytes ) ) != -1 ){
out.write( bytes , 0 , n );
}
*/ } }
4、Struts2利用 result-type为stream实现下载和展示图片测试案例
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=考拉.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">D:/</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">D:/</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>
JSP中可以通过${requestScope.name}获取到值,也可以直接${name}按照page-request-session-application 的顺序去查找,因此JSP中的name和Action中一致。在URL中没有指定name的时候Action中的name会给jsp中的name进行赋值,则name必须有getter。如果指定了,要从jsp中的URL接收到来自页面的参数name,则name必须要有setter方法。
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 filename; // 被下载的文件的名称 private String name; // 保存文件的名称 private InputStream inputStream; @Override
public String execute() throws Exception { filename = "Koala.jpg"; // inputStream = new FileInputStream( "D:/"" + name ) ; Path path = Paths.get(storePath, filename);
inputStream = Files.newInputStream(path);
if (name != null) {
name = URLEncoder.encode(name, "UTF-8");
}else{
name = filename;
} return SUCCESS;
} public String getStorePath() {
return storePath;
} public void setStorePath(String storePath) {
this.storePath = storePath;
} public String getFilename() {
return filename;
} public void setFilename(String filename) {
this.filename = filename;
} public InputStream getInputStream() {
return inputStream;
} public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}
Struts2学习(四)的更多相关文章
- Struts2学习四----------动态方法调用
© 版权声明:本文为博主原创文章,转载请注明出处 Struts2动态方法调用 - 默认:默认执行方法中的execute方法,若指定类中没有该方法,默认返回success <package nam ...
- (转)SpringMVC学习(四)——Spring、MyBatis和SpringMVC的整合
http://blog.csdn.net/yerenyuan_pku/article/details/72231763 之前我整合了Spring和MyBatis这两个框架,不会的可以看我的文章MyBa ...
- Java后台处理框架之struts2学习总结
Java后台处理框架之struts2学习总结 最近我在网上了解到,在实际的开发项目中struts2的使用率在不断降低,取而代之的是springMVC.可能有很多的朋友看到这里就会说,那还不如不学str ...
- [原创]java WEB学习笔记75:Struts2 学习之路-- 总结 和 目录
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- [原创]java WEB学习笔记66:Struts2 学习之路--Struts的CRUD操作( 查看 / 删除/ 添加) 使用 paramsPrepareParamsStack 重构代码 ,PrepareInterceptor拦截器,paramsPrepareParamsStack 拦截器栈
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- TweenMax动画库学习(四)
目录 TweenMax动画库学习(一) TweenMax动画库学习(二) TweenMax动画库学习(三) Tw ...
- Struts2第四天
Struts2第四天 昨天: 自定义的拦截器:继续methodFilterInterceptor,可以指定哪些方法需要拦截或者不拦截. Intercepters(配置拦截器),intercepter( ...
- Struts2学习笔记⑧
今天是Struts2学习笔记的最后一篇文章了.用什么做结尾呢,这两天其实还学了很多东西,没有记录下,今天就查漏补缺一下. 文件上传与下载.FreeMarker以及昨天没做完的例子 文件上传与下载 文件 ...
- Struts2学习笔记①
Struts2 学习笔记① 所有的程序学习都从Hello World开始,今天先跟着书做一个HW的示例. Struts2是一套MVC框架,使用起来非常方便,接触到现在觉得最麻烦的地方是配置文件.我的一 ...
- Struts2学习笔记NO.1------结合Hibernate完成查询商品类别简单案例(工具IDEA)
Struts2学习笔记一结合Hibernate完成查询商品类别简单案例(工具IDEA) 1.jar包准备 Hibernate+Struts2 jar包 struts的jar比较多,可以从Struts官 ...
随机推荐
- Spring - MVC - 修改 Java 类后, 触发重启
1. 概述 学习 Spring MVC 下, 如何可控的触发重启 2. 背景 学习 Spring 场景 有些时候, 改完类, 需要重启 之前有听说, Spring MVC 可以自动重启 于是想, 尝试 ...
- 【C语言】在有序数组中插入一个数,保证它依然有序
#include<stdio.h> int main() { ] = { ,,,,,, }; int key, i, j; printf("请输入一个数\n"); sc ...
- CentOS7安装jdk教程
引言Oracle JDK和OpenJDK的简单介绍Oracle JDK是基于Java标准版规范实现的,以二进制产品的形式发布.它支持多种操作系统,如Windows,Linux,Solaris,MacO ...
- P & R 11
要做好floorplan需要掌握哪些知识跟技能? 首先熟悉data flow对摆floorplan 有好处,对于减少chip的congestion 是有帮助的,但是也不是必需的,尤其是EDA工具快速发 ...
- Linux上FTP部署:基于mariadb管理虚拟用户
FTP原理 FTP 采用 Internet 标准文件传输协议 FTP 的用户界面, 向用户提供了一组用来管理计算机之间文件传输的应用程序.图1 FTP 的基本模型 FTP 是基于客户---服务器(C/ ...
- java 限制每隔15分钟才允许执行一次程序
由于公司订餐平台,有个用户催单业务,每当用户点击催单按钮时,商家就会收到消息提示,如果用户频繁的发起催单请求,这样商家就会不停的收到消息提醒,所以想限制用户至少每隔15分钟才可以催单一次 我采取了以下 ...
- redis-py相关
一 redis客户端命令 cmd进入redis客户端管理程序路径xx:\windows redis\redis-2.4.0-win32-win64\64bit 执行:redis-cli.exe -h ...
- mysql学习笔记(二:中的auto_increment 理解
1.auto_increment 理解1 auto_increment是用于主键自动增长的,从1开始增长,当你把第一条记录删除时,再插入第二跳数据时,主键值是2,不是1. 例如: create tab ...
- springmvc实现文件下载
springmvc实现文件下载 使用springmvc实现文件下载有两种方式,都需要设置response的Content-Disposition为attachment;filename=test2.p ...
- Windows 搭建WAMP+Mantis
下载WAMP http://www.wampserver.com/ 安装直接下一步就行 安装完启动后,显示下面的logo 在浏览器输入 127.0.0.1/phpmyadmin 设置数据库(默认 ...