1. 写一个简单,负责跳转到请求页面的Action
作用:比如点击一个 超链接“index.jsp”,Struts2拦截到该index.jsp请求,通过该Action处理后,又要回到"index.jsp"页面。
例:
public class SimpleViewResultAction {
public String execute() {
String url = ServletActionContext.getRequest().getRequestURI();
//相对与服务器根目录的路径 如:请求的页面路径为:http://localhost:8080/Hello/index.jsp,则该方法返回值为--"/2VTEL/index.jsp"
url = url.substring(7); //去掉"/2VTEL/",因为struts.xml配置中的相对路径是从"/Hello"开始的
ActionContext.getContext().put("url", url); //用于struts.xml配置文件中。
return "success";
}
2. 在struts.xml文件中配置
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- 为了让.jsp后缀也被Struts2拦截,需要修改默认的后缀拦截,增加对.jsp后缀的拦截 --> <constant name="struts.action.extension" value="action,jsp"/> <package name="tel" extends="struts-default"> <!-- 配置默认的Action,当找不到用户请求对应的Action时,则使用默认的Action --> <default-action-ref name="simpleViewResultAction"/> <action name="simpleViewResultAction" class="com.topthinking.tel.action.SimpleViewResultAction"> <!-- ${url} 中的url 是在SimpleViewResultAction 中execute方法中设置的,如果没有设定,${url}的值将为null --> <result>/${url}</result> </action> </package> </struts>