天天看點

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">

   <value>myintercepter</value>

</bean>

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