如何根据使用JSP的特定struts操作设置变量?

时间:2012-07-26 20:59:06

标签: java spring jsp servlets struts

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

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

有办法做到这一点吗?

2 个答案:

答案 0 :(得分: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>

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

答案 1 :(得分: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);
    }
}