Struts2 重点总结 (1)

来源:互联网 发布:互联主机销售系统源码 编辑:程序博客网 时间:2024/06/05 23:47

搭建Struts2开发环境步骤

1、建立web工程
2、导包
3、创建XXXXXAction类文件
   * 注意:继承ActionSupport,如果不继承,就不能使用struts进行开发
public class HelloWorldAction extends ActionSupport /*implements Action*/ {
public HelloWorldAction(){
System.out.println("这是HelloWorldAction的构造方法");
}
public String execute() throws Exception {
//System.out.println(this.getUsername());
System.out.println("欢迎您访问HelloWorldAction!");
return SUCCESS;
}
}
4、struts.xml配置文件
    * 引入规范:struts2-core-2.1.8.1包下struts-2.1.7.dtd
    * 引入加载的文件属性:struts2-core-2.1.8.1包下org.apache.struts2.default.properties  (用于constent引入)
   <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
  
   <!-- 改变访问的action的后缀,改成.do -->
   <!-- <constant name="struts.action.extension" value="action"></constant>-->
   <!-- 处理国际化加载的资源文件(.properties),
        默认是false:当修改国际化资源文件,不自动加载
            ture:自动加载资源文件 -->
   <!-- <constant name="struts.i18n.reload" value="true"></constant>-->
<!-- 处理struts2的配置文件(.xml)
   默认是false:当修改struts的配置文件,不自动加载 
       ture:当修改完struts.xml文件时,自动加载-->
   <!--<constant name="struts.configuration.xml.reload" value="true"></constant>-->
   
   <!-- struts的开发模式
      默认是false:生产模式
           true:开发模式
         struts.i18n.reload:自动加载
         struts.configuration.xml.reload:自动加载
            -->
   <constant name="struts.devMode" value="true"></constant>
   <!-- 加载其他配置文件 -->
   <include file="cn/itcast/web/a_primer/struts_primer.xml"></include>
</struts>
5、在web.xml文件中,添加过滤器(加载所有的struts的配置文件)
   <!-- 这是struts2的核心过滤器,如果不使用该过滤器,不能使用struts2进行项目开发 -->
  <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>
6、导入相应jsp,测试


Struts2的四大作用域对象的获取

1、在struts.xml文件中添加

   <struts>
<package name="context" namespace="/context" extends="struts-default">
<action name="contextAction_test" class="cn.itcast.web.b_context.ContextAction">
<result name="success">/context/success.jsp</result>
</action>
<action name="contextAction02_test" class="cn.itcast.web.b_context.Context02Action">
<result name="attr">/context/attr.jsp</result>
</action>
</package>
</struts>

2、在XXXXXAction(类)中


   方法一(ContextAction)
     * 使用ServletActionContext获取
    HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("username", "username_request");

HttpServletResponse response = ServletActionContext.getResponse();


Map<String, Object> mapSession = ServletActionContext.getContext().getSession();
mapSession.put("username", "username_session");

ServletContext sc = ServletActionContext.getServletContext();
sc.setAttribute("username", "username_application");
方法二(Context02Action) (开发中常用)
 * 需要实现 implements ServletRequestAware,SessionAware,ServletContextAware    (实现三个接口)
private HttpServletRequest request = null;
private Map<String, Object> session = null;
private ServletContext context = null;

//获取request
public void setServletRequest(HttpServletRequest request) {
this.request = request;

}
//获取session
public void setSession(Map<String, Object> session) {
this.session = session;
}
//获取application
public void setServletContext(ServletContext context) {
this.context = context;

}


struts.xml中的三个作用域

在配置文件struts.xml文件中的3个作用域(指定type参数)

   * 转发,默认是dispatcher
            <result name="success" type="dispatcher">
/resulttype/success.jsp
</result>

   * 重定向,redirect(指定同一资源下,重定向到某一文件)
            <result name="success" type="redirect">
/resulttype/success.jsp
</result>

   * 不同资源下的重定向,redirectAction
     有2个参数需要指定
         <result name="success" type="redirectAction">

                <!-- name="actionName":需要访问的action的路径
    name="namespace":指向另一个Action资源的命名空间 
    如果使用重定向,request作用域将无效-->

<param name="actionName">helloWorldAction</param>
<param name="namespace">/primer</param>
   </result>


Struts2中的通配符

1、操作struts.xml文件
   (1)* 通过method指定类中的方法
          <action name="bookAction" class="cn.itcast.web.d_pattern.BookAction" method="add">
 <result name="add">
/pattern/BookAction.jsp
 </result>
 </action>
   (2)* 通配符实例一
        <action name="*_add" class="cn.itcast.web.d_pattern.BookAction" method="add">
<result name="add">
/pattern/BookAction.jsp
</result>
</action> 
* 通配符实例二
<action name="*_add" class="cn.itcast.web.d_pattern.{1}" method="add">
<result name="add">
/pattern/{1}.jsp
</result>
</action>
* 通配符实例三
<action name="*_*" class="cn.itcast.web.d_pattern.{1}" method="{2}">
<result name="{2}">
/pattern/{1}.jsp
</result>
<result name="delete">
/pattern/success.jsp
</result>
</action>
   (3)* 动态方法调用(作为了解)
        <!-- 是否调用action中的动态方法:true(默认):允许调用(在action中可以!号)
               false:不允许调用调用动态方法 -->
   <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>、
   
   <!-- 动态方法调用 
<a href="${pageContext.request.contextPath}/pattern/BookAction!add.action">图书添加</a><br>
            <a href="${pageContext.request.contextPath}/pattern/BookAction!delete.action">图书删除</a><br>
-->
<!-- <action name="BookAction" class="cn.itcast.web.d_pattern.BookAction">
<result name="add">/pattern/BookAction.jsp</result>
<result name="delete">/pattern/success.jsp</result>
</action>-->
   (4)使用通配符(必须掌握)  开发中最常用
        <action name="BookAction_*" class="cn.itcast.web.d_pattern.BookAction" method="{1}">
<result name="add">/pattern/BookAction.jsp</result>
<result name="delete">/pattern/success.jsp</result>
</action>
   (5)在package中定义全局的转发
        <global-results>
<result name="delete">
/pattern/successGlobal.jsp
</result>
</global-results>


Struts2类型转换

1、类型转换
  (1)定义表单:
        编号:<input type="text" name="id" value="1"><br>
        姓名:<input type="text" name="userName" value=""><br>
  (1)在UserAction中
       使用javabean获取表单中的值,而且支持各种数据类型,如果数据类型不匹配,则抛异常
          (如果,不想抛异常,需要在struts.xml文件指定错误页面)
           <result name="input">/converter/error.jsp</result>
       在页面访问进入Action之前,先执行jvavbean的set()方法将属性值获取到javabean中
   
  (2)定义表单:
        创建日期:<input type="text" name="createTime" value="">格式yyyyMMdd<br>
      
  (2)使用struts2默认的日期类型格式(XXXX-XX-XX),如果想实现(XXXXXXXX)
       需要自定义类型转换器
       局部:ActionClassName-conversion.properties,放置到类路径下
              格式:需要转换的属性名=转换器
             本例中在cn.itcast.web.e_converter建立UserAction-conversion.properties文件
             对应的是UserAction的属性,配置如下:
             createTime=cn.itcast.web.e_converter.DateConverter
       全局:放置到src目录,命名为xwork-conversion.properties
     格式:需要转换的数据类型=转换器
             在本例中,对应所有Action中Date类型都有效
             java.util.Date=cn.itcast.web.e_converter.DateConverter
    
    
       类型转换器:
       public class DateConverter extends DefaultTypeConverter {
/**
* context:OGNL上下文对象(下节课讲)
* Object value:表单中<input type="text" name="createTime" value="">中name的属性值,也是需要转换的值
* Class toType:对应转换的类型
*   * 自定义类型转换器
*     局部配置:在当前目录e_converter中建立ActionClassName-conversion.properties
*                              针对于本例UserAction-conversion.properties
* return :转换后的结果
* */
public Object convertValue(Map context, Object value, Class toType) {
System.out.println("Object value="+value);
System.out.println("Class toType="+toType);
if(value==null){
return null;
}
if(toType==null){
return null;
}
if(toType!=java.util.Date.class){
return null;
}
//需要转换yyyyMMdd
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
if (value instanceof String[]) {
String[] date = (String[]) value;
if(date[0]!=null && !"".equals(date[0].trim())){
try {
return format.parse(date[0].trim());
} catch (ParseException e) {
return null;
}
}
}
return null;
}
}

  (3) 学历id:<input type="text" name="edu.eduid" value=""><br>
        学历名称:<input type="text" name="edu.eduname" value=""><br>
        
  (3)创建类文件Edu,放置eduid和eduname并生成set和get方法
       在UserAction中,声明属性命名为edu,并生成set和get方法
  
  (4) 员工姓名:<input type="text" name="emps[0].name" value=""><br>
        薪水:<input type="text" name="emps[0].salary" value=""><br>
        
        员工姓名:<input type="text" name="emps[1].name" value=""><br>
        薪水:<input type="text" name="emps[1].salary" value=""><br> 
  
  (4)     
        创建类文件Emp,放置name和salary并生成set和get方法
       在UserAction中,声明属性命名为emps的一个集合(Collection、List),并生成set和get方法
       
  (3)(4)做为了解,不常用
  


struts文件上传

         

1、单文件上传

  (1)表单要求:
    <form action="${pageContext.request.contextPath}/upload/uploadAction_saveFile.action"  
          name="form1"  method="post"  enctype="multipart/form-data">
             上传文件名称:<input type="file" name="uploadImage">
           <input type="submit" value="上传">
    </form>
  (2)在UploadAction中添加
        //上传文件名称:<input type="file" name="uploadImage">
//对应表单中的属性,文件以流的形式传递,获取文件
private File uploadImage;

//获取上传文件的类型,格式表单中属性的名称+ContentType,本例uploadImage+ContentType
private String uploadImageContentType;

//获取上传文件的名称,格式表单中属性的名称+FileName,本例uploadImage+FileName
private String uploadImageFileName;
  (3)实现
     public String saveFiles(){
System.out.println("欢迎进入UploadAction...");
//处理文件上传
//需求:将文件上传到WebRoot下upload文件,首先找到upload的目录
ServletContext sc = ServletActionContext.getServletContext();
String path = sc.getRealPath("/file");
File file = new File(path,uploadImageFileName);
//将一个文件拷贝到另一个文件中
try {
FileUtils.copyFile(uploadImage, file);
} catch (IOException e) {
throw new RuntimeException(e);
}
return "success";
}
  (4)控制上传文件的大小、类型、扩展名
      在struts.xml文件中添加:
       全局:设置全局拦截器,放置在<package></package>中,对所有action有效
           <interceptor-stack name="defaultStack">
<interceptor-ref name="defaultStack"></interceptor-ref>
将fileUpload放置到默认栈的后面,当默认栈执行完毕后,再执行
<interceptor-ref name="fileUpload">
<param name="maximumSize">5229339</param>
<param name="allowedTypes">application/pdf,application/vnd.ms-excel</param>
<param name="allowedExtensions">.pdf,.txt</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>  
 局部:放置<action></action>中,指定当前action有效
    <interceptor-ref name="defaultStack">
<!-- 定义文件的大小,默认是2M -->
<param name="fileUpload.maximumSize">1229339</param>
<!-- 定义允许上传的文件类型,如果文件类型定义多个,需要用逗号分开 -->
<param name="fileUpload.allowedTypes">application/pdf,application/vnd.ms-excel,application/vnd.ms-powerpoint</param>
<!-- 定义文件的扩展名,如果存在多个扩展名,用逗号分开 -->
<param name="fileUpload.allowedExtensions">.pdf,.ppt</param>
</interceptor-ref>
限制上传文件大小,默认2M:
  <constant name="struts.multipart.maxSize" value="5229339"></constant>
  (5)实现国际化
      * 在struts.xml文件添加,默认不加载struts.custom.i18n.resources属性,fileupload表示src下的资源文件名称
        如果将资源文件放置到某个目录下,需要在文件的添加相应的目录
         <constant name="struts.custom.i18n.resources" value="fileupload"></constant>
  (6)在error.jsp中可以使用<s:fielderror></s:fielderror>,显示对应的错误信息
       在struts.xml文件中
       <!--input: 如果该类中上传文件失败,可跳转到/upload/error.jsp -->
<result name="input">/upload/error.jsp</result>
 (7)常见的文件类型

文件类型:

excel:application/vnd.ms-excel

word:application/msword

ppt:application/vnd.ms-powerpoint

txt:text/plain

pdf:application/pdf



2、多文件上传

   1、上传的文件用数组进行表示:
   //上传文件名称:<input type="file" name="uploadImages">
//对应表单中的属性,文件以流的形式传递,获取文件
private File[] uploadImages;

//获取上传文件的类型,格式表单中属性的名称+ContentType,本例uploadImages+ContentType
private String [] uploadImagesContentType;

//获取上传文件的名称,格式表单中属性的名称+FileName,本例uploadImages+FileName
private String [] uploadImagesFileName;
2、实现:
  public String saveFiles(){
System.out.println("欢迎进入UploadAction...");
//处理文件上传
//需求:将文件上传到WebRoot下upload文件,首先找到file的目录
ServletContext sc = ServletActionContext.getServletContext();
String path = sc.getRealPath("/file");
for(int i=0;uploadImagesContentType!=null && i<uploadImagesContentType.length;i++){
File file = new File(path,uploadImagesFileName[i]);
try {
//将一个文件拷贝到另一个文件中
FileUtils.copyFile(uploadImages[i], file);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return "success";
}




自定义拦截器


1、拦截器:
           struts2的拦截器分2大类,一类是xwork包下,一类是struts2的包下,无论使用哪个拦截器,都必须实现Interceptor接口
           struts2的拦截器属于单实例

2、自定义拦截器(判断用户是否登录,即从session中获取相应的用户信息)
   实现ActionInvocation接口
    package cn.itcast.web.g_aop;


import java.util.Map;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

@SuppressWarnings("serial")
public class PersonInterceptor implements Interceptor {

public PersonInterceptor(){
System.out.println("PersonInterceptor构造方法....");
}

public void init() {
System.out.println("PersonInterceptor的init方法....");

}

public String intercept(ActionInvocation invocation) throws Exception {
        //利用invocation可以得到很多数据
System.out.println("action="+invocation.getAction());
System.out.println("actionName="+invocation.getProxy().getActionName());
System.out.println("namespace="+invocation.getProxy().getNamespace());
System.out.println("method="+invocation.getProxy().getMethod());
//判断session中是否存在用户信息
//获取session对象
Map<String, Object> mapSession = invocation.getInvocationContext().getSession();
String user = (String) mapSession.get("user");
if(user==null){
return "error";
}
// invocation.invoke():表示执行调用UserAction中save()方法,返回值String就表示save方法返回值
String result = invocation.invoke();
return result;
}

public void destroy() {
System.out.println("PersonInterceptor的destroy方法....");

}
}
3、需要在struts.xml文件添加和配置自定义拦截器
在struts.xml或者相应的action的struts.xml配置中的package中添加配置自定义拦截器,对相应的action起作用
    <!-- 自定义拦截器 -->
<interceptors>
<interceptor name="person" class="cn.itcast.web.g_aop.PersonInterceptor"></interceptor>
<interceptor-stack name="personStack">
<interceptor-ref name="defaultStack"></interceptor-ref>
<!-- 将自定义的拦截器放置到默认栈的后面 -->
<interceptor-ref name="person"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 默认执行的拦截器,即自定义的拦截器 -->
<default-interceptor-ref name="personStack"></default-interceptor-ref>


struts表单验证

表单验证:

1、手工验证

  (1)要想实现对ValidateAction类中的方法进行校验,必须要是继承ActionSupport,因为ActionSupport类中实现了Validateable接口
       接口Validateable中有validate方法,用于对表单进行验证
       /**
* 针对ValidateAction中的某一方法进行校验,不希望所有的方法进行校验
* 只需要将ValidateAction的中的方法名放置到validate方法的后面,并且方法的首字母要大写
* 只对ValidateAction类中的login方法进行校验
* */
public void validateLogin(){
System.out.println("进入登录校验的方法validate");
if(this.username==null || "".equals(username)){
this.addFieldError("username", "用户名不能为空");
}
if(this.psw==null || "".equals(psw)){
this.addFieldError("psw", "密码不能为空");
}
else{
//验证密码在6到12之间,定义正则表达式
String exg = "^[A-Za-z0-9]{6,12}$";
//编译正则表达式
Pattern pattern = Pattern.compile(exg);
//与密码进行匹配
Matcher matcher = pattern.matcher(this.psw);
//如果匹配不成功,说明密码输入有误
if(!matcher.matches()){
this.addFieldError("psw", "输入的密码格式不正确(要求6到12之间)");
}
}
}
(2)在进行表单验证的时候,如果出现异常,需要将错误的信息添加
   this.addFieldError("username", "输入的密码格式不正确(要求6到12之间)");
   最后struts会判断错误集合中是否有值,如果有值,会通过struts.xml文件的配置
   <result name="input">/validate/login.jsp</result>
   指定到登录页面。
   要想将错误信息显示到登录页面,需要在登录页面添加<s:fielderror/>


2、xml文件验证

  (1)在cn.itcast.web.h_validate中建立xml格式文件的配置文件
      xml格式:
        * ValidateAction中的所有方法
            ActionClassName-validation.xml 其中ActionClassName指定的是Action类的名称
            本例:ValidateXmlAction-validation.xml
        
        * ValidateAction中的指定方法
            ActionClassName-ActionName-validation.xml,其中ActionClassName指定的是Action类的名称
                                                       其中ActionName,提交表单的action的路径的名称
            本例:ValidateXmlAction-validateXmlAction_login-validation.xml
     创建xml的验证文件时,需要添加规范
     * 规范在xwork-core-2.1.6.jar中xwork-validator-1.0.3.dtd
       
     * xml文件配置代码:
       
      <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
  "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
  "http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd">
<!-- 使用XML文件对指定Action类做校验 -->
<validators>
<!-- 指定校验的字段名称,对应表单中name的属性值 -->
<field name="username">
<!-- 针对某一字段的验证规则 
struts2将验证规则存放到xwork-2.x.jar中
com.opensymphony.xwork2.validator.validators下的default.xml文件
-->
<!-- 用户名不能为空 -->
<field-validator type="requiredstring">
<!-- 指定验证规则中属性名称指定相应值 -->
<param name="trim">true</param>
<!-- 填写提示的错误信息 -->
<message>用户名不能为空</message>
</field-validator>
</field>
<field name="psw">
<!-- 密码不能为空 -->
<field-validator type="requiredstring">
<param name="trim">true</param>
<message><![CDATA[密码不能为空]]></message>
</field-validator>
<!-- 密码长度在6到12之间 -->
<field-validator type="regex">
<param name="expression">^[A-Za-z0-9]{6,12}$</param>
<message><![CDATA[密码的长度不匹配(需要输入6到12之间)]]></message>
</field-validator>
</field>
<!-- 验证年龄不能小于0 -->
<field name="age">
<field-validator type="agevalidator">
<message><![CDATA[年龄不能小于0]]></message>
</field-validator>
</field>
</validators>
     
       在该文件中<field-validator type="requiredstring">,其中type为字段指定校验规则
         struts2中的校验规则xwork-core-2.1.6.jar中,com.opensymphony.xword2.validator.validators中的default.xml文件
         
   
   (2)自定义校验规则(验证年龄不能小于0)
       建立AgeValidator文件,定义校验规则,必须实现Validator接口
    或者继承ValidatorSupport 和 FieldValidatorSupport 
      
       加载验证规则
       在src的目录下创建validators.xml,配置如下
        <validators>
<!-- name:为自定义的校验规则指定名称,
           与ValidateXmlAction-validateXmlAction_login-validation.xml文件中校验规则type的值对应
    class:校验规则的类路径
-->

<validator name="agevalidator" class="cn.itcast.web.h_validate.AgeValidator"></validator>
</validators>
如果不想在src目录下创建validators.xml,就需要在struts2的校验规则下进行修改
路径如下:struts2中的校验规则xwork-core-2.1.6.jar中,com.opensymphony.xword2.validator.validators中的default.xml文件
     
     
     
     

(3)一些校验器例子

required  必填校验器

<field-validatortype="required">

       <message>性别不能为空!</message>

</field-validator>

requiredstring  必填字符串校验器

<field-validator type="requiredstring">

       <param name="trim">true</param>

       <message>用户名不能为空!</message>

</field-validator>

stringlength字符串长度校验器

<field-validator type="stringlength">

  <paramname="maxLength">10</param>

  <paramname="minLength">2</param>

  <paramname="trim">true</param>

  <message><![CDATA[产品名称应在2-10个字符之间]]></message>

</field-validator>

int:整数校验器

<field-validator type="int">

  <paramname="min">1</param>

  <paramname="max">150</param>

  <message>年龄必须在1-150之间</message>

</field-validator>

字段OGNL表达式校验器

<field name="imagefile">

  <field-validatortype="fieldexpression">

  <paramname="expression"><![CDATA[imagefile.length()<= 0]]></param>

  <message>文件不能为空</message>

  </field-validator>

</field>

email:邮件地址校验器

<field-validatortype="email">

  <message>电子邮件地址无效</message>

</field-validator>

regex:正则表达式校验器

<field-validatortype="regex">

    <paramname="expression"><![CDATA[^13\d{9}$]]></param>

    <message>手机号格式不正确!</message>

</field-validator>


0 0
原创粉丝点击