SSH框架搭配(五)

六、以上 SSH 框架基本完成了,现在给它加点内容吧
  1. 加入 struts 的验证框架
   1 struts-config.xml 中加入插件
  <plug-in className= "org.apache.struts.validator.ValidatorPlugIn">
    <set-property property= "pathnames"
      value= "/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" />
  </plug-in>
 
 
(2)  复制validator-rules.xml和validation.xml到WEB-INF下
(3) 
3 )在 src 下建包 com.test.struts
ApplicationResources.properties
loginForm.username=name
loginForm.password=password
error.usevalidate=username not found


     errors.required={0} is required.
     errors.minlength={0} can not be less than {1} characters.
     errors.maxlength={0} can not be greater than {1} characters.
     errors.invalid={0} is invalid.

     errors. byte={0} must be a byte.
     errors. short={0} must be a short.
     errors.integer={0} must be an integer.
     errors. long={0} must be a long.
     errors. float={0} must be a float.
     errors. double={0} must be a double.

     errors.date={0} is not a date.
     errors.range={0} is not in the range {1} through {2}.
     errors.creditcard={0} is an invalid credit card number.
     errors.email={0} is an invalid e-mail address.
 
2 加入拦截器
写一个拦截器MyInterceptor.java
package com.test.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.struts.action.ActionMapping;

public class MyInterceptor implements MethodInterceptor {

   public Object invoke(MethodInvocation arg0) throws Throwable {
    HttpServletRequest request= null;
    ActionMapping mapping = null;
    Object[] kk=arg0.getArguments();
     for( int i=0;i<kk.length;i++){    
       if(kk[i] instanceof HttpServletRequest) request=(HttpServletRequest)kk[i];
       if(kk[i] instanceof ActionMapping ) mapping=(ActionMapping)  kk[i];        
    }
    String path=mapping.getPath();
    HttpSession session=request.getSession();
     if(session.getAttribute( "user")!= null)
      {
       return arg0.proceed();        
      }
     else{
       return mapping.findForward( "login");
    }
  }
    
}
 
 
(2) spring 中配置拦截器
applicationContext_action.xml
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
 <property name="beanNames">
  <list>
   <value>/login</value>
  </list>
 </property>
 <property name="interceptorNames">
  <list>
   <value>myintercepter</value>
  </list>
 </property>
</bean>

<bean id="myintercepter" class="com.test.interceptor.MyInterceptor"></bean>

你可能感兴趣的:(框架,ssh,职场,休闲)