20160501--struts2入门2
一、Action名称的搜索顺序
<package name="itcast" namespace="/test" extends="struts-default">
<action name="helloworld" class="cn.itcast.action.HelloWorldAction" method="execute" >
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>
</package
<action name="helloworld" class="cn.itcast.action.HelloWorldAction">
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>
<result type="redirect">/view.jsp?id=${id}</result>
<result type="redirectAction">helloworld</result>
<result type="redirectAction">
<param name="actionName">helloworld</param>
<param name="namespace">/test</param>
</result>
<result name="source" type="plainText ">
<param name="location">/xxx.jsp</param>
<param name="charSet">UTF-8</param><!-- 指定读取文件的编码 -->
</result>
<package ....>
<global-results>
<result name="message">/message.jsp</result>
</global-results>
</package>
我的代码保留:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts>
<!-- 全局包,供继承使用,各个包访问全视图-->
<package name="base" extends="struts-default">
<global-results>
<result name="message">/WEB-INF/page/message.jsp</result>
</global-results>
</package> <package name="dzq" namespace="/test" extends="struts-default">
<!-- 全局视图配置, 包内访问 -->
<global-results>
<result name="message">/WEB-INF/page/message.jsp</result>
</global-results> <!-- 在action中返回视图,包内访问 -->
<action name="manager" class="com.dzq.action.HelloWorldAction"
method="add">
</action> <action name="helloworld" class="com.dzq.action.HelloWorldAction"
method="execute">
<!-- 默认是服务器请求转发 -->
<result name="success">/WEB-INF/page/hello.jsp</result>
</action> <!-- action的各项默认值 ,不指定属性,使用默认值 -->
<action name="addUI">
<result>/WEB-INF/page/employeeAdd.jsp</result>
</action> <!-- 浏览器重定向 指定type属性 -->
<!-- <action name="redirect"> <result type="redirect">/employeeAdd.jsp?username=${username}</result>
</action> --> <!-- 带参数的请求重定向 使用ognl表达式${} 参数有中文,在Action中URLEncoder对中文进行编码 -->
<action name="list" class="com.dzq.action.HelloWorldAction"
method="execute">
<result name="success" type="redirect">/employeeAdd.jsp?username=${username}
</result>
</action> <!-- 请求重定向到同一个包下的Action,eg: list ,两次重定向 -->
<action name="redirectAction">
<result type="redirectAction">list</result>
</action> <!-- 请求重定向到不同包下的Action,使用属性param,为属性注入值eg:hello -->
<action name="redirectAction1">
<result type="redirectAction">
<param name="actionName">hello</param>
<param name="namespace">/test1</param>
</result>
</action> <!-- 显示视图的源代码,指定type值为plainText <action name="plainText"> <result type="plainText">/index.jsp</result>
</action> -->
<!-- 显示视图的源代码,源代码中有中文,需要用param为其指定属性,指定type值为plainText -->
<action name="plainText">
<result type="plainText">
<param name="location">/index.jsp</param>
<param name="charSet">UTF-8</param><!-- 指定读取文件的编码 -->
</result>
</action>
</package> <package name="other" namespace="/test1" extends="base">
<action name="hello">
<result>/WEB-INF/page/hello.jsp</result>
</action>
<!-- 在action中返回视图,包外访问 -->
<action name="manager1" class="com.dzq.action.HelloWorldAction"
method="add">
</action>
</package> </struts>
四、 为Action的属性注入值
public class HelloWorldAction{
private String savePath; public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
......
}
<package name="itcast" namespace="/test" extends="struts-default">
<action name="helloworld" class="cn.itcast.action.HelloWorldAction" >
<param name="savePath">/images</param>
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>
</package>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.action.extension" value="do"/>
</struts>
<constant name="struts.action.extension" value="do,go"/>
六、细说常量定义
<struts>
<constant name="struts.action.extension" value="do"/>
</struts>
struts.action.extension=do
<!-- 指定默认编码集,作用于HttpServletRequest的setCharacterEncoding方法 和freemarker 、velocity的输出 -->
<constant name="struts.i18n.encoding" value="UTF-8"/>
<!-- 该属性指定需要Struts 2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。
如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。 -->
<constant name="struts.action.extension" value="do"/>
<!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 -->
<constant name="struts.serve.static.browserCache" value="false"/>
<!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->
<constant name="struts.configuration.xml.reload" value="true"/>
<!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->
<constant name="struts.devMode" value="true" />
<!-- 默认的视图主题 -->
<constant name="struts.ui.theme" value="simple" />
<!– 与spring集成时,指定由spring负责action对象的创建 -->
<constant name="struts.objectFactory" value="spring" />
<!–该属性设置Struts 2是否支持动态方法调用,该属性的默认值是true。如果需要关闭动态方法调用,则可设置该属性为false。 -->
<constant name="struts.enable.DynamicMethodInvocation" value="false"/>
<!--上传文件的大小限制-->
<constant name="struts.multipart.maxSize" value=“10701096"/>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="struts-user.xml"/>
<include file="struts-order.xml"/>
</struts>
九、使用通配符定义action
<package name="itcast" namespace="/test" extends="struts-default">
<action name="helloworld_*" class="cn.itcast.action.HelloWorldAction" method="{1}">
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>
</package>
public class HelloWorldAction{
private String message;
....
public String execute() throws Exception{
this.message = "我的第一个struts2应用";
return "success";
} public String other() throws Exception{
this.message = "第二个方法";
return "success";
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- 指定访问后缀 -->
<constant name="struts.action.extension" value="do,action"/>
<package name="department" namespace="/test/department" extends="struts-default">
<action name="helloworld" class="com.dzq.action.HelloWorldAction"
method="execute">
<param name="savepath">department</param>
<!-- 默认是服务器请求转发 -->
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
<!--使用通配符访问 -->
<action name="list_*" class="com.dzq.action.HelloWorldAction" method="{1}">
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>
<!-- 包含其他配置文件
<include file="department.xml"/>
<include file="employee.xml"/>
-->
</struts>
十、接收请求参数
public class ProductAction {
private Integer id;
public void setId(Integer id) {//struts2通过反射技术调用与请求参数同名的属性的setter方法来获取请求参数值
this.id = id;
}
public Integer getId() {return id;}
}
public class ProductAction {
private Product product;
public void setProduct(Product product) { this.product = product; }
public Product getProduct() {return product;}
}
public void doFilter(...){
HttpServletRequest req = (HttpServletRequest) request;
req.setCharacterEncoding("UTF-8");//应根据你使用的编码替换UTF-8
filterchain.doFilter(request, response);
}
我的代码保留:
package com.dzq.domian; public class Person {
private int id;
private String name; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} }
Person
package com.dzq.action; import java.util.Date; import com.dzq.domian.Person; public class HelloWorldAction { private int id;
private String name;
private Date birthday;
private Person person; public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
System.out.println(birthday);
this.birthday = birthday;
} public Person getPerson() {
return person;
} public void setPerson(Person person) {
this.person = person;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String addUI() {
return "success";
} public String execute() throws Exception {
return "success";
} }
HelloWorldAction
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- 指定访问后缀 -->
<constant name="struts.action.extension" value="do,action"/>
<package name="department" namespace="/test/department" extends="struts-default">
<action name="helloworld" class="com.dzq.action.HelloWorldAction"
method="execute">
<param name="savepath">department</param>
<!-- 默认是服务器请求转发 -->
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
<!--使用通配符访问 -->
<action name="list_*" class="com.dzq.action.HelloWorldAction" method="{1}">
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>
</struts>
struts.xml
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/test/department/list_addUI.do" method="post">
id:<input type="text" name="person.id"/><br>
name:<input type="text" name="person.name">
<input type="submit" value="提交"/>
</form>
</body>
</html>
index.jsp
十一、自定义类型转换器
import java.util.Date;
public class HelloWorldAction {
private Date createtime; public Date getCreatetime() {
return createtime;
} public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
}
public class DateConverter extends DefaultTypeConverter {
@Override public Object convertValue(Map context, Object value, Class toType) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
try {
if(toType == Date.class){//当字符串向Date类型转换时
String[] params = (String[]) value;// Request.getParameterValues()
return dateFormat.parse(params[0]);
}else if(toType == String.class){//当Date转换成字符串时
Date date = (Date) value;
return dateFormat.format(date);
}
} catch (ParseException e) {}
return null;
}
}
public String scope() throws Exception{
ActionContext ctx = ActionContext.getContext();
ctx.getApplication().put("app", "应用范围");//往ServletContext里放入app
ctx.getSession().put("ses", "session范围");//往session里放入ses
ctx.put("req", "request范围");//往request里放入req
return "scope";
}
<body>
${applicationScope.app} <br>
${sessionScope.ses}<br>
${requestScope.req}<br>
</body>
public String rsa() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();
ServletContext servletContext = ServletActionContext.getServletContext();
request.getSession()
HttpServletResponse response = ServletActionContext.getResponse();
return "scope";
}
public class HelloWorldAction implements ServletRequestAware, ServletResponseAware, ServletContextAware{
private HttpServletRequest request;
private ServletContext servletContext;
private HttpServletResponse response;
public void setServletRequest(HttpServletRequest req) {
this.request=req;
}
public void setServletResponse(HttpServletResponse res) {
this.response=res;
}
public void setServletContext(ServletContext ser) {
this.servletContext=ser;
}
}
我的代码保留:
package com.dzq.type.converter; import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map; import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter; public class DateTypeConverter extends DefaultTypeConverter { @Override
public Object convertValue(Map<String, Object> context, Object value,
Class toType) {
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");
try {
if(toType==Date.class){
String [] params=(String[]) value;
return dateFormat.parse(params[0]);
}else if(toType==String.class){
Date date=(Date) value;
return dateFormat.format(date);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package com.dzq.action; import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext; public class HelloWorldAction {
public String execute () {
ActionContext ctx = ActionContext.getContext();
ctx.getApplication().put("app", "应用范围");//往ServletContext里放入app
ctx.getSession().put("ses", "session范围");//往session里放入ses
ctx.put("req", "request范围");//往request里放入req
return "message";
} public String rsa() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();
ServletContext servletContext = ServletActionContext.getServletContext();
request.setAttribute("hello", "request域");
request.getSession().setAttribute("hello", "session域");
servletContext.setAttribute("hello", "application域");
return "message";
} }
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- 指定访问后缀 -->
<constant name="struts.action.extension" value="do,action"/>
<package name="department" namespace="/test/department" extends="struts-default">
<action name="helloworld" class="com.dzq.action.HelloWorldAction"
method="execute">
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
<!--使用通配符访问 -->
<action name="list_*" class="com.dzq.action.HelloWorldAction" method="{1}">
<result name="message">/WEB-INF/page/message.jsp</result>
</action>
</package>
</struts>
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">
<input type="file" name="uploadImage">
</form>
public class HelloWorldAction{
private File uploadImage;//得到上传的文件
private String uploadImageContentType;//得到文件的类型
private String uploadImageFileName;//得到文件的名称
//这里略省了属性的getter/setter方法
public String upload() throws Exception{
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
File file = new File(realpath);
if(!file.exists()) file.mkdirs();
FileUtils.copyFile(uploadImage, new File(file, uploadImageFileName));
return "success";
}
}
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">
<input type="file" name="uploadImages">
<input type="file" name="uploadImages">
</form>
public class HelloWorldAction{
private File[] uploadImages;//得到上传的文件
private String[] uploadImagesContentType;//得到文件的类型
private String[] uploadImagesFileName;//得到文件的名称
//这里略省了属性的getter/setter方法
public String upload() throws Exception{
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
File file = new File(realpath);
if(!file.exists()) file.mkdirs();
for(int i=0 ;i<uploadImages.length; i++){ File uploadImage = uploadImages[i];
FileUtils.copyFile(uploadImage, new File(file, uploadImagesFileName[i]));
}
return "success";
}}
我的代码保留:
package com.dzq.action; import java.io.File; import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext; public class FileUploadAction {
private File image;
private String imageFileName;
private File[] image1;
private String []image1FileName; public String getImageFileName() {
return imageFileName;
} public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
} public File getImage() {
return image;
} public void setImage(File image) {
this.image = image;
} public File[] getImage1() {
return image1;
} public void setImage1(File[] image1) {
this.image1 = image1;
} public String[] getImage1FileName() {
return image1FileName;
} public void setImage1FileName(String[] image1Filename) {
this.image1FileName = image1Filename;
} public String execute() throws Exception{
String savepath=ServletActionContext.getServletContext().getRealPath("/images");
System.out.println(savepath);
if(image!=null){
File savefile=new File(new File(savepath),imageFileName);
if(!savefile.getParentFile().exists()){
savefile.getParentFile().mkdirs();
}
FileUtils.copyFile(image,savefile);
ActionContext.getContext().put("message", "上传成功");
}
return "upload";
} public String manyexecute() throws Exception{
String savepath=ServletActionContext.getServletContext().getRealPath("/images");
System.out.println(savepath);
if(image1!=null){
File savedir=new File(savepath);
if(!savedir.getParentFile().exists()){
savedir.getParentFile().mkdirs();
}
for(int i=0;i<image1.length;i++){
File savefile=new File(savedir,image1FileName[i]);
FileUtils.copyFile(image1[i],savefile); }
ActionContext.getContext().put("message", "上传成功");
}
return "upload1";
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- 指定访问后缀 -->
<constant name="struts.action.extension" value="do,action"/>
<!-- 设置文件上传大小限制 -->
<constant name="struts.multipart.maxSize" value="10701096"/>
<package name="department" namespace="/test/department" extends="struts-default">
<action name="helloworld" class="com.dzq.action.HelloWorldAction"
method="execute">
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
<!--使用通配符访问 -->
<action name="list_*" class="com.dzq.action.HelloWorldAction" method="{1}">
<result name="message">/WEB-INF/page/message.jsp</result>
</action>
<action name="upload" class="com.dzq.action.FileUploadAction" method="execute">
<result name="upload">/WEB-INF/page/message.jsp</result>
</action>
<action name="upload1" class="com.dzq.action.FileUploadAction" method="manyexecute">
<result name="upload1">/WEB-INF/page/message.jsp</result>
</action>
</package>
</struts>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%-- <form action="${pageContext.request.contextPath }/test/department/list_addUI.do" method="post">
id:<input type="text" name="person.id"/><br>
name:<input type="text" name="person.name"> <input type="submit" value="提交"/>
</form> --%>
<%-- <form
action="${pageContext.request.contextPath }/test/department/upload.do"
method="post" enctype="multipart/form-data">
<input type="file" name="image" /> <input type="submit" value="上传" />
</form> --%> <form
action="${pageContext.request.contextPath }/test/department/upload1.do"
method="post" enctype="multipart/form-data">
<input type="file" name="image1" /> <br>
<input type="file" name="image1" /><br>
<input type="file" name="image1" /><br>
<input type="submit" value="上传" />
</form>
</body>
</html>
20160501--struts2入门2的更多相关文章
- Struts2 入门
一.Struts2入门案例 ①引入jar包 ②在src下创建struts.xml配置文件 <?xml version="1.0" encoding="UTF-8&q ...
- Struts2入门3 深入学习
Struts2入门3 深入学习 处理结果和异常 前言: Struts学习的差不多了,还有最后的一点就收官了就是结果处理和异常处理.前面学习Struts主要围绕就是Action以及struts.xml配 ...
- Struts2入门2 Struts2深入
Struts2入门2 Struts2深入 链接: http://pan.baidu.com/s/1rdCDh 密码: sm5h 前言: 前面学习那一节,搞得我是在是太痛苦了.因为在Web项目中确实不知 ...
- Struts2入门1 Struts2基础知识
Struts2入门1 Struts2基础知识 20131130 代码下载: 链接: http://pan.baidu.com/s/11mYG1 密码: aua5 前言: 之前学习了Spring和Hib ...
- struts2入门程序
struts2入门程序 1.示例 搭建编程环境就先不说了,这里假设已经搭建好了编程环境,并且下好了strut2的jar包,接下来程序. 1.1 新建web项目 点击File->New->D ...
- struts2框架(1)---struts2入门
struts2框架 如果你之前在MVC模式的时候一直都是通过servlet,获取和返回数据,那么现在开始学习struts2框架, Struts是一个实现MVC设计模式的优秀的框架.它的许多优点我就不说 ...
- [java]struts2入门
摘要 本文是struts2入门,配置教程.如何在IntelJ Idea中进行手动配置.在使用idea新建struts2web项目的时候,在下载jar包的过程中,下载失败,没办法就直接手动进行下载jar ...
- ---web模型 --mvc和模型--struts2 入门
关于web模型: 早期的web 应用主要是静态页丽的浏览〈如新闻的制监),随着Internet的发展,web应用也变得越来越复杂,不仅要 和数据库进行交互 ,还要和用户进行交互,由此衍生了各种服务器端 ...
- Struts2入门示例(Myeclipse)
1.新建Web项目在lib导入struts-2.3.37核心基础jar包 2.在WebRoot新建2个JSP demo1.jsp <%@ page language="java&quo ...
- Struts2入门(六)——国际化
一.前言 1.1.国际化简介 国际化是指应用程序在运行的时候,根据客户端请求来自的国家地区.语言的不同而显示不同的界面(简单说就是根据你的地区显示相关地区的语言,如果你现在在英国,那么显示的语言就是英 ...
随机推荐
- Sharepoint数据库存储过程
转:http://dugan.bokee.com/630497.html Databases Table Stored Procedures(数据库表存储过程) Globals Table Store ...
- 基于DDD的现代ASP.NET开发框架--ABP系列之2、ABP入门教程
基于DDD的现代ASP.NET开发框架--ABP系列之2.ABP入门教程 ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)”的简称. ASP.NET Boi ...
- MVC Action 返回类型[转]
一. ASP.NET MVC 1.0 Result 几何? Action的返回值类型到底有几个?咱们来数数看. ASP.NET MVC 1.0 目前一共提供了以下十几种Action返回 ...
- 如何判断 Android 应用的 Apk 签名是否一致?
可以比对apk签名的fingerprint. 假定安装了JDK,如果想查HelloWorld.apk所使用的签名的fingerprint,可以这样做: 1. 查找apk里的rsa文件 (Windows ...
- selenium 处理日期控件
今天遇到日期控件无法处理的问题,在北京-air的帮助下,看了下这篇blog http://www.cnblogs.com/Fskjb/archive/2011/10/27/2227111.html 根 ...
- Microsoft SQL Server,错误:2;SQL Server配置管理器(本地)—远程过程调用失败
本机是先安装sqlserver2008,后安装vs2012 在安装sqlserver2008后,运行sqlserver2008正常,接着安装vs2012,再运行sqlserver2008,问题出现了, ...
- uDig介绍
一 安装配置Java平台此步骤不必多说,如果您是Java开发者可以跳过.如果您的机器上没有Java平台,那么请到http://java.sun.com下载jdk,当下最新的版本是1.6.安装jdk,请 ...
- 最新Blog
应该会长期稳定的 https://b.intmainreturn0.com/
- 解决libpython2.6.so.1.0: cannot open shared object file
文章解决的问题:安装nginx中需要Python2.6的支持,下面介绍如何安装Python2.6,并建立lib的连接. 问题展示:error while loading shared librarie ...
- jQuery获取鼠标移动方向
<!doctype html> <html> <head> <meta http-equiv="Content-Type&q ...