0

我有一些“模板”JSP 文件用于多个 struts 操作。我有另一个 JSP 文件,我想根据被调用的特定操作进行设置。例如:

<% if(this is one.action) { int testVar = 1; } %>
<% if(this is two.action) { int testVar = 2; } %>

有没有办法做到这一点?

4

2 回答 2

0

使用 Struts 2 的解决方案

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class MyLoggingInterceptor implements Interceptor {
    private static final long serialVersionUID = 1L;
    public String intercept(ActionInvocation invocation) throws Exception {
        String className = invocation.getAction().getClass().getName();
        System.out.println("Before calling action: " + className);
                    int pageNo = 0 ;
                    if(className.equals("Login")) {
                       pageNo = 1;
                    } else if(className.equals("Login")) {
                       pageNo = 2;
                    } // so on for other pages

                    String result = invocation.invoke();        
                    final ActionContext context = invocation.getInvocationContext ();
                    HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
                    request.setAttribute("pageNo", pageNo);
        return result;
    }

    public void destroy() {
        System.out.println("Destroying ...");
    }
    public void init() {
        System.out.println("Initializing ...");
    }
}

现在,在您想要的任何 jsp 页面中,您都将使用

request.getAttribute("pageNo");

Struts 1 的解决方案

而不是 Interceptor 使用 RequestProcessor 将 pageNo 变量放在请求范围内

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.RequestProcessor; 

public class CustomRequestProcessor extends RequestProcessor { 

public boolean processPreprocess(HttpServletRequest request, HttpServletResponse response) {
        System.out .println("Called the preprocess method before processing the request");
        String path = processPath(request, response);
        if (path == null) {
           return;
        }
        int pageNo = 0 ;
        if(path.equals("Login")) {
            pageNo = 1;
        } else if(path.equals("Login")) {
            pageNo = 2;
        } // so on for other pages
        request.setAttribute("pageNo", pageNo);

        return super.processPreprocess(request,response);
    }
}
于 2012-09-24T12:03:40.560 回答
0

一种解决方案是让两个操作文件都实现一个通用方法,比如说:

public Integer getPageID() {
    return pageID;
}

然后在你的 JSP 中:

<s:if test="%{pageID == 0}">
  <s:set name="testVar" value="1"/>
</s:if>
<s:elseif test="%{pageID == 1}">
  <s:set name="testVar" value="2"/>
</s:elseif>

如果您只设置一个变量,那么您应该考虑直接使用动作类中的变量。

于 2012-07-26T21:36:04.210 回答