从Struts2 Action Class调用Javascript

时间:2011-01-20 10:29:24

标签: javascript struts2

我想从struts2调用一个javascript函数。

package com.example.controller;

import java.io.IOException;
import java.io.PrintWriter;

import com.opensymphony.xwork2.ActionSupport;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletResponseAware;


public class FileUploadAction extends ActionSupport implements ServletResponseAware {

 private static final long serialVersionUID = 1L;
 HttpServletResponse response;

 public String execute() throws IOException{

  System.out.println("I am in Action");

  PrintWriter out;
  out = response.getWriter();


  response.setContentType("text/html");  
  out.println("<html>");
  out.println("<head>");
  out.println("<script type=\"text/javascript\">");
  out.println("function foo() { ");
  out.println("alert('From Struts Action');");
  out.println("window.top.uploadComplete('1');");
  out.println("}");
  out.println("</script>");
  out.println("</head>");
  out.println("<body onload=\"foo();\">");
  out.println("</body>");
  out.println("</html>");

  return SUCCESS;
 }

 @Override
 public void setServletResponse(HttpServletResponse response) {
  this.response = response;
 }
 public HttpServletResponse getServletResponse() {
  return this.response;
 }

}

在这里,我甚至没有“警觉”。即它不起作用, 并在后端发出警告

    [WARN] 404 - GET /success (127.0.0.1) 1393 bytes
   Request headers
      Host: 127.0.0.1:8888
      User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12
      Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
      Accept-Language: en-gb,en;q=0.5
      Accept-Encoding: gzip,deflate
      Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
      Keep-Alive: 115
      Connection: keep-alive
      Cookie: JSESSIONID=pvv1gasa4o7l
      Referer: http://127.0.0.1:8888/GWTDemo.html?gwt.codesvr=127.0.0.1:9997
   Response headers
      Content-Type: text/html; charset=iso-8859-1
      Content-Length: 1393

请帮帮忙?

2 个答案:

答案 0 :(得分:1)

您尝试提交两个响应 - 首先直接发送到HttpServletResponse,然后使用Struts2命名结果(即SUCCESS)。

将JavaScript代码放在视图图层中。

答案 1 :(得分:0)

你能描述为什么你需要从Struts2调用javascript动作可能会帮助我们为你提供更好的方法以及史蒂文所说的是正确的你尝试提交2个回复