Struts2拦截器的运用


              Struts2拦截器的运用

项目目录:
Struts2拦截器的运用_第1张图片

struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
  <package name="007" extends="struts-default">
     <interceptors>
        <interceptor name="liuchaoInterceptor" class="liu.chao.interceptor.LcInterceptor"></interceptor>
     </interceptors>
     <action name="liuchaoAction" class="liu.chao.action.LiuChaoAction">
         
         <interceptor-ref name="liuchaoInterceptor"/>
         <interceptor-ref name="defaultStack"/> 
         
         <result name="success">/success.jsp</result>
         <result name="error">/error.jsp</result>
     </action>
      
  
  </package>

</struts>   


LiuChaoAction:
package liu.chao.action;

import com.opensymphony.xwork2.ActionSupport;

public class LiuChaoAction extends ActionSupport {

	private String userName;
	private String passWord;
	
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassWord() {
		return passWord;
	}
	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}
	
	public String execute()throws Exception{
		
		if(userName.equals("liuchao")&&passWord.equals("1234")){
			
			System.out.println("进入Action中的execute()方法");
			return SUCCESS;
		}
		
		return ERROR;
	}
	
	
}


自定义拦截器LcInterceptor:
package liu.chao.interceptor;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LcInterceptor extends AbstractInterceptor implements StrutsStatics {

	@Override
	public String intercept(ActionInvocation arg0) throws Exception {
		// TODO Auto-generated method stub
		
		ActionContext ac=arg0.getInvocationContext();
		HttpServletRequest request=(HttpServletRequest)ac.get(HTTP_REQUEST); 
	    System.out.println("拦截器起作用了:"+request.getParameter("userName"));
		System.out.println("拦截器起作用了:"+request.getParameter("passWord"));

		return arg0.invoke();
		
		
	}

}

界面:
Struts2拦截器的运用_第2张图片
console:
Struts2拦截器的运用_第3张图片

  

你可能感兴趣的:(struts)