Struts2总结(一)

2014-11-24 07:23:22 · 作者: · 浏览: 3

Struts2
1. 搭建Struts2的开发环境:
1) 导入相应的jar包;6个
2) 编写struts的配置文件;struts.xml
3) struts2在web中的启动配置;web.xml
2. 第一个struts2应用
3. actin属性的注入message是action中的变量
注入参数的值
4. 编写自定义类型转换器:建立自定义局部类型转换器,处理日期类型,通过继承DefaultTypeConverter,(推荐使用StrutsTypeConverter,它继承了DefaultTypeConverter)实现自己的DateTypeConverter,并且在action所在的包下创建HelloWorldAction3-conversion.properties文件;在文件中编写对应关系:birthday=com.lcq.type.converter.DateTypeConverter
将转换的属性和转换器进行绑定。如果是全局,类型转换器就要将properties文件放置在src的根目录下,同时修改文件的名称为:xwork-conversion.properties,修改里边的内容为:要转换的变量的类型=转换器的名称,
转换器的编写:
[java]
/**
* 建立自定义类型转换器,处理日期类型,通过继承DefaultTypeConverter,实现自己的DateTypeConverter
* @author lcq
*
*/
public class DateTypeConverter extends DefaultTypeConverter {

@Override
public Object convertValue(Map context, Objectvalue,
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 (ParseException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
return super.convertValue(context, value, toType);
}

}


例如定义的action为:
[java]
package com.lcq.action;

import java.util.Date;

public class HelloWorldAction3 {
private Date birthday;

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public String addUI(){

return "success";
}

public String execute(){

return "success";
}

}


5. 访问和添加request/session/application属性,并在页面进行打印输出
//从struts2封装的ActionContext中获取request/session/application

[java]
ActionContext ctx = ActionContext.getContext();
ctx.getApplication().put("app", "application scope");
ctx.getSession().put("session", "sessionscope");
ctx.put("request", "request scope");

jsp中:
[java]
${applicationScope.app }

${sessionScope.session }

${requestScope.request }

6. 得到request/session/application对象:
在action中利用ServletActionContext.getxxxx()方法得到
7. 文件上传实现:
1)上传页面:upload.jsp
[java]



file:


2) xml中的配置
[html]
method="execute">
/WEB-INF/page/uploadMessage.jsp


3)Action中的方法
[java]
public String execute() throws Exception{
//构建真实的存放路径
String realPath = ServletActionContext.getServletContext().getRealPath("/image");
System.out.println(realPath);
if(image != null){
File savefile = new File(new File(realPath),imageFileName);
if(!savefile.getParentFile().exists()){
savefile.getParentFile().mkdirs();
}
FileUtils.copyFile(image, savefile);

ActionContext.getContext().put("message", "上传成功");

}
return "success";
}


4)结果页面输出上传信息
[html]

message }


8. 多文件上传只要修改为:同时在action中将相应的参数变为数组即可

[html]



file1:

file2:

file3:

action中

[java]
private File[] image;// 定义上传文件的文件属性