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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章