日期:2014-05-16  浏览次数:20402 次

Struts2 拦截器控制jsp页面跳转

源自一个题目:

请编写一个拦截器,该拦截器可以获得用户输入的用户名这个数据,业务逻辑为逐个判断用户名中是否包含“你”,“我”,“他”三个数据,如果包含则直接返回输入页面,如果不包含则运行至PersonAction。(除代码外,要给出拦截器和Action的配置文件)

最终项目结构:

直接上源码:

login.jsp:

<%@ page language="java" pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
	<s:form action="Person">
				<s:textfield name="username" label="用户名"/>
				<s:submit value="登录" align="center"/>				
	</s:form>
</body>
</html>


PersonInterceptor.java:

package com.intercept;
import java.util.Map;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class PersonInterceptor extends AbstractInterceptor{
	public String intercept(ActionInvocation ai)throws Exception{
		 Map<String, Object> map=ai.getInvocationContext().getParameters();
		 String[] username = (String[]) map.get("username");
       if(username[0].indexOf("你")==-1&&username[0].indexOf ("我")==-1&& username[0].indexOf ("他")==-1){
            String result=ai.invoke();
            return result;  
       }else{
    	   return "input";
       }
}
}

注:这是拦截器类,注意获取jsp传值的方法以及intercept方法返回值。

struts.xml:

<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.i18n.encoding" value="gb2312"/>
	<package name="LanJieQi" extends="struts-default">
		<interceptors>
			<interceptor name="intercept" class="com.intercept.PersonInterceptor">
			</interceptor>
		</interceptors>
		<action name="Person" class="com.action.PersonAction">
			<result name="input">/jsp/login.jsp</result>
			<result name="success">/jsp/success.jsp</result>
			 <interceptor-ref name="intercept"></interceptor-ref>
			 <interceptor-ref name="defaultStack"></interceptor-ref>
		</action>
	</package>
</struts>

注:传值如果可能是汉字的话,在加上<constant>标签定义编码格式。默认拦截器"defaultStack"别忘了且要放在action配置的最下面,否则缺少了拦截核心。

PersonAction.java:

package com.action;
import com.opensymphony.xwork2.ActionSupport;
public class PersonAction extends ActionSupport {
	private String username;

	public void setUsername(String username) {
		this.username = username;
	}

	public String getUsername() {
		return username;
	}

	public String execute() throws Exception {
		return SUCCESS;
	}
}


success.jsp:

<%@ page language="java" contentType="text/html; charset=GB2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
	<s:property value="username"/>
</body>
</html>


结果: