`

struts02表单验证文件上传自定义拦截器类型转换常用常量

阅读更多

一.package下可以配置全局页面
 <!-- package的继承案例:配置全局的结果视图 -->
 <package name="mypackage" extends="struts-default"> 
 <!-- 配置全局错误结果 :范围只是本包 但可以通过继承扩展到其它包-->
  <global-results>
   <result type="dispatcher" name="error">/customer/error.jsp</result>
  </global-results>
 </package>
二.常用常量:
struts2配置文件中常用常量在default.properties文件中的都能配置
<constant name="struts.i18n.encoding" value="UTF-8" />
指定Web应用的默认编码集,相当于调用HttpServletRequest的setCharacterEncoding方法
<constant name="struts.action.extension" value="do,,action" />
该属性指定需要Struts 2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts 2处理。    如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。  
<constant name="struts.serve.static.browserCache " value="false" />
设置浏览器是否缓存静态内容,默认值为true,开发阶段最好false
<constant name="struts.configuration.xml.reload" value="true" />
当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false,开发阶段最好true
<constant name="struts.devMode" value="true" />
开发模式下设为true,这样可以打印出更详细的错误信息
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
动态方法调用,可以解决多个请求对应一个Servlet的问题,后面详细讲解,默认为true,关闭则设为false.
下面是其他的一些常量,使用方法和上面相同。
struts.serve.static.browserCache 该属性设置浏览器是否缓存静态内容。当应用处于开发阶段时,我们希望每次请求都获得服务器的最新响应,则可设置该属性为false。
struts.enable.DynamicMethodInvocation 该属性设置Struts 2是否支持动态方法调用,该属性的默认值是true。如果需要关闭动态方法调用,则可设置该属性为false。
struts.enable.SlashesInActionNames 该属性设置Struts 2是否允许在Action名中使用斜线,该属性的默认值是false。如果开发者希望允许在Action名中使用斜线,则可设置该属性为true。
struts.tag.altSyntax 该属性指定是否允许在Struts 2标签中使用表达式语法,因为通常都需要在标签中使用表达式语法,故此属性应该设置为true,该属性的默认值是true。
struts.devMode该属性设置Struts 2应用是否使用开发模式。如果设置该属性为true,则可以在应用出错时显示更多、更友好的出错提示。该属性只接受true和flase两个值,该属性的默认值是false。通常,应用在开发阶段,将该属性设置为true,当进入产品发布阶段后,则该属性设置为false。
struts.i18n.reload该属性设置是否每次HTTP请求到达时,系统都重新加载资源文件。该属性默认值是false。在开发阶段将该属性设置为true会更有利于开发,但在产品发布阶段应将该属性设置为false。
提示 开发阶段将该属性设置了true,将可以在每次请求时都重新加载国际化资源文件,从而可以让开发者看到实时开发效果;产品发布阶段应该将该属性设置为false,是为了提供响应性能,每次请求都需要重新加载资源文件会大大降低应用的性能。
struts.ui.theme该属性指定视图标签默认的视图主题,该属性的默认值是xhtml。
struts.ui.templateDir该属性指定视图主题所需要模板文件的位置,该属性的默认值是template,即默认加载template路径下的模板文件。
struts.ui.templateSuffix该属性指定模板文件的后缀,该属性的默认属性值是ftl。该属性还允许使用ftl、vm或jsp,分别对应FreeMarker、Velocity和JSP模板。
struts.configuration.xml.reload该属性设置当struts.xml文件改变后,系统是否自动重新加载该文件。该属性的默认值是false。
struts.velocity.configfile该属性指定Velocity框架所需的velocity.properties文件的位置。该属性的默认值为velocity.properties。
struts.velocity.contexts该属性指定Velocity框架的Context位置,如果该框架有多个Context,则多个Context之间以英文逗号(,)隔开。
struts.velocity.toolboxlocation该属性指定Velocity框架的toolbox的位置。
struts.url.http.port该属性指定Web应用所在的监听端口。该属性通常没有太大的用户,只是当Struts 2需要生成URL时(例如Url标签),该属性才提供Web应用的默认端口。
struts.url.https.port该属性类似于struts.url.http.port属性的作用,区别是该属性指定的是Web应用的加密服务端口。
struts.url.includeParams该属性指定Struts 2生成URL时是否包含请求参数。该属性接受none、get和all三个属性值,分别对应于不包含、仅包含GET类型请求参数和包含全部请求参数。
struts.custom.i18n.resources该属性指定Struts 2应用所需要的国际化资源文件,如果有多份国际化资源文件,则多个资源文件的文件名以英文逗号(,)隔开。
struts.dispatcher.parametersWorkaround 对于某些Java EE服务器,不支持HttpServlet Request调用getParameterMap()方法,此时可以设置该属性值为true来解决该问题。该属性的默认值是false。对于WebLogic、Orion和OC4J服务器,通常应该设置该属性为true。
struts.freemarker.manager.classname 该属性指定Struts 2使用的FreeMarker管理器。该属性的默认值是org.apache.struts2.views.freemarker.FreemarkerManager,这是Struts 2内建的FreeMarker管理器。
struts.freemarker.wrapper.altMap该属性只支持true和false两个属性值,默认值是true。通常无需修改该属性值。
struts.xslt.nocache 该属性指定XSLT Result是否使用样式表缓存。当应用处于开发阶段时,该属性通常被设置为true;当应用处于产品使用阶段时,该属性通常被设置为false。
struts.configuration.files 该属性指定Struts 2框架默认加载的配置文件,如果需要指定默认加载多个配置文件,则多个配置文件的文件名之间以英文逗号(,)隔开。该属性的默认值为struts-default.xml,struts-plugin.xml,struts.xml,看到该属性值,读者应该明白为什么Struts 2框架默认加载struts.xml文件了。

三.struts配置文件拆分

<include file="customer.xml"></include>

四.得到form表单数据:
package cn.itcast.action;

import java.io.Serializable;
import java.util.Date;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
//(不建议使用)动态方法调用:http://localhost:8080/struts2day02/customer/addCustomer!updateCustomer(应该执行addCustomer,使用!updateCustomer,在请求addCustomer就执行了updateCustomer)
//关闭动态调用的功能:struts.enable.DynamicMethodInvocation = false
public class CustomerAction extends ActionSupport implements Serializable{
 //每次请求都会重新实例化该类,是线程安全的。
// public CustomerAction(){
//  System.out.println("实例化了");
// }
// 
 
 private Integer id;//Struts2会自动类型转换:仅限基本类型
 private String name;
 private String[] hobby;
 private Date birthday;
 
 private AddressAction address;//Struts2设置值时,如果发现该类没有实例,则创建实例(通过反射调用默认构造方法)
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 
 public AddressAction getAddress() {
  return address;
 }
 public void setAddress(AddressAction address) {
  this.address = address;
 }
 
 
 
 public Date getBirthday() {
  return birthday;
 }
 public void setBirthday(Date birthday) {
  this.birthday = birthday;
 }
 public String[] getHobby() {
  return hobby;
 }
 public void setHobby(String[] hobby) {
  this.hobby = hobby;
 }
 public String addCustomer(){
  
  try{
   System.out.println("addCustomer");
   System.out.println("ID:"+id+"\tNAME:"+name+"\tProvince:"+address.getProvince()+"\tCITY:"+address.getCity());
   System.out.println("爱好:");
   for(String s:hobby){
    System.out.println(s);
   }
   System.out.println(birthday);
   ActionContext.getContext().put("birthday", birthday);
   //调用service层保存用户的信息
   return SUCCESS;
  }catch(Exception e){
   return ERROR;
  }
 }
 public String updateCustomer(){
  System.out.println("updateCustomer");
  try{
   //调用service层更新用户的信息
   return SUCCESS;
  }catch(Exception e){
   return ERROR;
  }
 }
}

jsp:

<html>
  <head>
    <title>添加新客户</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

  </head>
 
  <body>
    <form action="${pageContext.request.contextPath}/customer/addCustomer.action" method="post">
     ID:<input type="text" name="id" /><br/>
     姓名:<input type="text" name="name"/><br/>
     省份:<input type="text" name="address.province"/><br/>
     城市:<input type="text" name="address.city"/><br/>
     爱好:<input type="checkbox" name="hobby" value="吃饭" checked="checked"/>吃饭
       <input type="checkbox" name="hobby" value="睡觉" checked="checked"/>睡觉
       <input type="checkbox" name="hobby" value="想巧玲" checked="checked"/>想巧玲<br/>
     出生日期:<input type="text" name="birthday"/><br/>
     <input type="submit" value="保存"/>
    </form>
  </body>
</html>

一、自定义类型转换器
 1、编写一个类,继承com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter
 2、覆盖掉其中的public Object convertValue(Map<String, Object> context, Object value,Class toType)
   context:OGNL表达式的上下文
   value:实际的值。用户输入的都是字符串,但他是一个String数组。
   toType:目标类型
 public class DateConvertor extends DefaultTypeConverter {
  /*
   context:ognl表达式的上下文
   value:用户输入的值( 保存数据时)或者模型中的属性。用户输入的值是String数组
   toType:目标类型
   */
  @Override
  public Object convertValue(Map<String, Object> context, Object value,
    Class toType) {
   DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
   if(toType==Date.class){
    //2013/05/31----->java.util.Date 保存数据时
    String strValue = ((String[])value)[0];
    try {
     return df.parse(strValue);
    } catch (ParseException e) {
     throw new RuntimeException(e);
    }
   }else{
    //java.util.Date----->2013/05/31 获取数据时
    Date dValue = (Date)value;
    return df.format(dValue);
   }
  }
 }
 3、注册类型转换器
  3.1局部类型转换器:只对当前的Action有效
  具体做法:在动作类相同的包中,建立一个名称是“动作类名-conversion.properties”的配置文件,
   文件中增加以下内容:要验证的字段=验证器的类全名
     birthday=cn.itcast.convertor.DateConvertor
  3.2全局类型转换器:对所有的Action都有效
  具体做法:在WEB-INF/classes目录下,建立一个名称为"xwork-conversion.properties"的配置文件,
   文件中增加以下内容:目标类型全名=验证器的类全名
     java.util.Date=cn.itcast.convertor.DateConvertor
  
  
  
 注意:如果转换失败,Struts2框架会寻找name=input的结果页面
二、自定义拦截器
 1、编写一个类,实现com.opensymphony.xwork2.interceptor.Interceptor
 2、主要实现public String intercept(ActionInvocation invocation) throws Exception{}方法
  该方法的返回值就相当于动作的返回值
  如果调用了String result = invocation.invoke();得到了动作类的返回的值。
 public String intercept(ActionInvocation invocation) throws Exception {
  //判断用户是否登录
  HttpSession session = ServletActionContext.getRequest().getSession();
  Object obj = session.getAttribute("user");
  if(obj==null){
   return "login";
  }else{
   return invocation.invoke();//调用动作方法
  }
 }
 3、拦截器定义好后,一定要在配置文件中进行注册:
  <interceptors> 只是定义拦截器,并没有起作用
   <interceptor name="permissionInterceptor" class="cn.itcast.interceptor.PermissionInterceptor"></interceptor>
  </interceptors>
 4、配置文件中的动作,要通过
  <interceptor-ref name="permissionInterceptor"></interceptor-ref>使用该拦截器
 注意:一旦动作中使用了自定义的拦截器,那么默认的就不起作用了。一般应该采用如下的做法:
  <interceptor-ref name="defaultStack"></interceptor-ref>
  <interceptor-ref name="permissionInterceptor"></interceptor-ref>
  
 多个动作类都要使用的话,可以通过package来进行组合。
  <package name="mypackage" extends="struts-default">
<!--  <interceptors> 只是定义拦截器,并没有起作用 -->
<!--   <interceptor name="permissionInterceptor" class="cn.itcast.interceptor.PermissionInterceptor"></interceptor>-->
<!--   <interceptor-stack name="mydefaultstack">-->
<!--    <interceptor-ref name="defaultStack"></interceptor-ref>-->
<!--    <interceptor-ref name="permissionInterceptor"></interceptor-ref>-->
<!--   </interceptor-stack>-->
<!--  </interceptors>-->
  <!-- 配置全局错误结果 :范围只是本包-->
  <global-results>
   <result type="dispatcher" name="error">/customer/error.jsp</result>
  </global-results>
     </package>
           <package name="interceptor" extends="mypackage">
  
  <action name="visitIndex" class="cn.itcast.action.VisitAction" method="execute">
<!--   <interceptor-ref name="mydefaultstack"></interceptor-ref>-->
   <result name="success">/index.jsp</result>
   <result name="login">/login.jsp</result>
  </action>
 </package
三、用户输入数据的验证
 1、手工编程验证,针对该动作类中的所有的动作方法
 步骤:
 a、动作类继承ActionSupport
 b、覆盖调用public void validate()方法
 c、在validate方法中,编写不符合要求的代码判断,并调用父类的addFieldError(String fieldName,String errorMessage)
  如果fieldError(存放错误信息的Map)有任何的元素,就是验证不通过,动作方法不会执行。
  Struts2框架会返回到name=input的result
 d、在name=input指定的页面上使用struts2的标签显示错误信息。<s:fielderror/>

1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics