struts2相关知识

来源:互联网 发布:linux vi命令修改 编辑:程序博客网 时间:2024/05/29 18:06
struts2要点概括:
1.下载Struts:
http://struts.apache.org/download.cgi
下载Full Distribution(struts2的完整版) 
2.步骤:
2.1 导入Struts2所需的jar包,在struts2-blank.war下即可。
2.2 在web.xml文件中配置核心filter。
<filter>
<filter-name>struts2</filter-name>
<filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/* </url-pattern> 
</filter-mapping>
2.3 Action配置:
1.传参:
包括属性传参和对象传参,一般都要生成其相应的get和set方法。struts2会利用类的放射机制自动为其赋值,一般都要写上其默认的不带参数的构造方法。
注意其中属性要与表单中的name属性一一对应。对象也是一样。如果是对象则用user.name ,user.age来调用。




2.action配置:
继承com.opensymphony.xwork2.ActionSupport类
配置action文件:一般使用通配符配置。(约定优于配置的原则)"*_*原理"
<!-- 使用通配符配置Action中的方法 -->

<action name="*action" method="{1}" 
class="com.roben.actionGetParam.MyExtendsAction">
<result>/hello.jsp</result>
</action>


<!-- 使用通配符配置Action -->
<action name="*action" class="com.roben.actionGetParam.{1}Action">
<result>/hello.jsp</result>
</action>


<!-- 使用通配符配置Action视图 -->
<action name="*action" class="com.roben.actionGetParam.{1}Action">
<result>/{1}.jsp</result>
</action>
3.在Action中接收请求参数值的方式:一般都采用IOC控制反转方式
1.使用action类的属性接收用户输入:
1.属性get/set方法
2.无参构造方法、全参构造方法





    2.使用领域对象模型接收用户输入
包括属性传参和对象传参,一般都要生成其相应的get和set方法。struts2会利用类的放射机制自动为其赋值,一般都要写上其默认的不带参数的构造方法。
注意其中属性要与表单中的name属性一一对应。对象也是一样。如果是对象则用user.name ,user.age来调用。
4.在 Action配置文件sturts.xml中result元素的type属性:
dispatcher 默认为请求转发,一般转向jsp页面
redirect 重定向,会丢失所有的请求参数、请求属性
redirectAction重定向到一个新的Action,前Action参数、属性会丢失。
chain 请求转发到另一个Action(Action链)
velocity 使用velocity模板输出结果
freemaker 用freemaker模板引擎呈现视图
plaintext 用于显示某个页面的源代码的结果类型
stream 向浏览器返回一个InputStream(一般用于文件下载)
补充说明:从客户端访问action时一次request只有一个值栈。
 而服务器中所有的action共用一个值栈。所以,当想一个action跳转到
 另一个action时不用传参数,因为共用一个值栈。但是如果是redirectAction
 前一个action中的属性则会丢失。如果需要传参,则需手动传参。具体怎么传参,参照
 struts2文档。重定向是避免表单重复提交的一个解决办法。
5.struts2访问web元素:
1.非IOC方式:(直接访问)
 ActionContext.getContext().getApplication();
 ActionContext.getContext().getSession();
 ActionContext.getContext().getParameters();
 
 
  HttpServletRequest request=ServletActionContext.getRequest();
  HttpSession session=request.getSession();
       ServletContext application=ServletActionContext.getServletContext();


2.IOC方式:控制反转:注入
继承3个接口:RequestAware,SessionAware,ApplicationAware
public class LoginAction implements  Action,RequestAware,SessionAware,ApplicationAware {
public Map request ;         // 将通过ioc的方式注入,注意是Map类型
public Map session;
public Map application;
public User user;


public String execute() throws Exception {
  request.put(“user”,user);//将user对象放到request作用域中
  session.put(“user”,user);//将user对象放到session作用域中
  application.put(“user”,user);//将user对象放到application作用域中
}


//request,session.application对象对应的 Set/get方法


6.struts2标签:
<%@taglib  prefix="s"  uri="/struts-tags" %>
    OGNL表达式:Struts默认的表达式语言是OGNL,使用符号为:#
在Struts2中打开访问静态方法 (struts.xml中增加如下代码)
<constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>


OGNL不支持多个root对象,而struts2能够支持多个root对象,它对OGNL做了扩展。
在Struts2中,一个请求在最终到达Action的方法之前,Action对象本身会被压入ValueStack(实际上就是放到ValueStack的CompoundRoot中),所以Action对象是CompoundRoot中的一个元素
<s:property value="name"/> 取出action中的name属性,双引号中的即为ognl表达式
访问StackContext里的命名对象需要在对象名之前添加#号前缀
当访问OGNL的StackContext里“根”对象属性时,可以省略对象名
在JSP页面中可通过<s:debug />标签来查看着两个对象
标签:
<s:property  value=“username”  default=“姓名” />
<s:set  value=“user.name”  name=“xxx”/>
<s:action  name=“actionName”  …. /> ……</s:action>在action标签的标签体中可以嵌套param标签,向action传递参数
<s: date  name=“#now”  … />






7.OGNL访问内置对象(context中的对象):
parameters对象:    #parameters.name或#parameters[‘name’]
request对象:       #request.name或#request[‘name’]
session对象:       #session.name或#session[‘name’]
application对象:   #application.name或#application[‘name’]




8.国际化:
1.创建资源文件:创建对应国家地区的资源文件,把资源文件保存在src路径下
formInfo_en_US.properties
username=username
userpassword=password
submitName=submit

2.加载资源文件:把资源文件加载到应用系统以供系统使用
在struts.xml文件中配置常量(value=资源文件baseName)
<constant name="struts.custom.i18n.resources“ value=“formInfo" />


3.访问国际化消息:根据不同国家地区显示不同资源文字信息
JSP页面访问:使用<s:text…/>标签,该标签可以指定一个name属性,该属性指定了国际化资源文件中的key
<s:text name="username"></s:text>
Action中访问:使用继承ActionSupport类的getText方法,该方法接受一个name参数,name参数指定了国际化资源文件中的key
request.setAttribute("info", getText("username"));
9.Struts2 类型转换:
Struts2可以自动完成大部分常用的类型转换,因此,在实际开发过程中,开发人员无需自己进行类型转换。以下是Struts2已经实现的转换器: 
预定义类型:例如int、long、float、double、char、boolean等 
日期类型:使用当前区域(Locale)的短格式转换,即DateFormat.getInstance(DateFormat.SHORT) 
集合类型:将request.getParameterValues(String arg)返回的字符串数据进行封装 
数组类型: 默认情况下,数组元素是字符串类型的封装
自定义类型转换器:
创建一个类继承DefaultTypeConverter类并重写convertValue(Map context,Object value,Class toType)方法即可 
注册类型转换器:
注册全局类型转换器:
全局类型转换器文件名:xwork-conversion.properties
文件内容(需被转换的类型=转换器类路径):com.domain.User=com.struts2.converter.UserConverter
位置:项目的src目录下
10.Struts2 输入校验:
3、编写 字段校验规则文件
文件命名:创建一个AtionName-validation.xml文件
RegisterAction-validation.xml
文件位置:和当前RegisterAction同级目录
文件内容:包括文件头(DTD)和文件体
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" 
"http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
<validators>
     <field name="username">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>username should not be blank!</message>
    </field-validator>
<field-validator type="stringlength">
<param name="minLength">6</param>
<param name="maxLength">10</param>
<message>username should between ${minLength} and  ${maxLength}
</message>
</field-validator>
     </field>


     <field name="password">
  <field-validator type="requiredstring">
<message>password should not be blank!</message>
</field-validator>
<field-validator type="stringlength">
<param name="minLength">6</param>
<param name="maxLength">10</param>
<message>password should between ${minLength} and ${maxLength}
</message>
</field-validator>
     </field>
</validators>
4、配置input结果页面
<result name="input">/register.jsp</result>
5、在结果页面中添加<s:fielderror/>标签显示错误提示
<td style="color:red">
<s:fielderror></s:fielderror>
</td>
6.Struts2提供的手动输入校验有两种方法
Action继承ActionSupport类,重写validate()方法:
public void validate(){
System.out.println("validate~~~~~~~~~~~~~~~~~~~");


if(null == username || username.length() < 6 || username.length() > 10)
{
this.addFieldError("username","username invalid");
}
if(null == password || password.length() < 6 || password.length() > 10)
{
this.addFieldError("password","password invalid");
}
如果校验不通过,则会返回input视图,并把相应的错误信息返回在input页面上。
Action继承ActionSupport类,重写validateXxx()方法
11.Struts2 文件上传和下载:
要使用jakarta框架实现文件上传,必须把表单的method属性设置为post,将enctype设置为:multipart/form-data
1、在Struts2项目中导入jar包(可在源代码中copy)

commons-io-2.0.1.jar  和  commons-fileupload-1.2.2.jar


2、编写文件上传Jsp页面(设置表单属性)
<s:form action="upload" theme="simple" method="post"    enctype="multipart/form-data">
username: <s:textfield name=“username“></s:textfield>
<br>
file1: <s:file name="file"></s:file>
<br> 
<s:submit value=" submit "></s:submit>  
</s:form>


3、创建文件上传Action
private File pic;
private String picFileName;
private InputStream fis;


String filename=student.getStudentId()+"."+picFileName.substring(picFileName.lastIndexOf(".")+1);
Calendar calendar=Calendar.getInstance();
String filepath=calendar.get(Calendar.YEAR)+"/"+calendar.get(Calendar.MONTH)+"/"+calendar.get(Calendar.DATE);
String savePath=Constant.picPath+"/"+filepath;


File file=new File(savePath);
if(!file.exists()){
file.mkdirs();
}
FileOutputStream fos=new FileOutputStream(file.getAbsolutePath()+"/"+filename);
FileInputStream fis=new FileInputStream(pic);
byte[] bytes=new byte[100];
int index;
while((index=fis.read(bytes))!=-1){
fos.write(bytes, 0, index);
}
fos.flush();
fos.close();
fis.close();
stu1.setSrcName(picFileName);
stu1.setPicPath(filepath+"/"+filename);

if(stu1!=null){
HttpSession session=ServletUtil.getSession();
session.setAttribute("student",stu1);
return "studentlog";
}
4、配置文件上传Action
<action name="upload" class="com.test.action.UploadAction">
<result name="success">/uploadResult.jsp</result>
<result name="input">/upload.jsp</result>
<interceptor-ref name="fileUpload">
<param name="maximumSize">409600</param>
<param name="allowedTypes">
image/png,image/gif,image/jpeg
</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>








下载action配置:
<action name="*Action" class="Action.LoginAction" method="{1}">
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="download" type="stream">
<param name="contentDisposition">filename=${srcName}</param>
<param name="inputName">downloadFile</param>
</result>
</action>


action类:
public InputStream  getDownloadFile(){
System.out.println(fis);
return fis;
}
public String download(){
Student stu=(Student)ServletUtil.getSession().getAttribute("student");
File file=new File(Constant.picPath+"/"+stu.getPicPath());
try {
fis=new FileInputStream(file);

} catch (Exception e) {
e.printStackTrace();
}

 // ActionContext.getContext().getValueStack().put("src_name", stu.getSrcName());
ActionContext.getContext().getValueStack().push(stu);
return "download";
}


12.Struts2 拦截器:
 补充:拷贝项目时,直接Ctrl+c ,ctrl+v,访问时记得修改项目属性web/content 修改项目名。
 导入的项目冲突时把原来的jre去掉,换成自己的。
 struts2中的路径问题根据action的路径而不是jsp,统一使用绝对路径。
bathPath
处理中文乱码问题时,修改常量i18n中值,
在配置文件中可以用${r}来读取值栈中的内容。model中永远要提供一个参数为空的
构造方法利用反射构造对象。
{}在ognl中表示一个集合。


















 
 
 
0 0