Hardik Mishra
Hardik Mishra

Reputation: 14877

Call Javascript from Struts2 Action Class

I want to call a javascript function from struts2.

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;
 }

}

Here, I am not getting even 'alert'. i.e. it is not working, and In back end it throws warning

    [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

Please help ?

Upvotes: 1

Views: 2816

Answers (2)

Umesh Awasthi
Umesh Awasthi

Reputation: 23587

Can you describe why you need to call javascript from Struts2 action may be it will help us to provide you better way and what Steven said is correct you tried commiting 2 responses

Upvotes: 0

Steven Benitez
Steven Benitez

Reputation: 11055

You are trying to commit two responses -- first directly to the HttpServletResponse and then using the Struts2 named result (i.e., SUCCESS).

Place the JavaScript code in your view layer.

Upvotes: 1

Related Questions