Setting varible in action class and fetching value in JSP using struts2 - struts2

I am calling struts2 action class through a ajax call from javascript, which redirect it to b.jsp on success return. In action class I am setting a parameter called dummyValue, for which i have defined getter and setter in the action class. But when i try to display the value of this dummyValue using it does not shows any value.
struts.xml
<package name="AbcAction" namespace="/" extends="struts-default">
<action name="abcAction" class="com.AbcAction">
<result type="stream">
<param name="contentType">text/html</param>
<param name="inputName">stream</param>
</result>
<result name="input" type="dispatcher">/errorPage.jsp</result>
</action>
Setting the result type as stream on purpose.
AbcAction class
public class AbcAction extends ActionSupport {
private InputStream stream;
private String dummyValue;
public String execute() {
dummyValue = "Hello";
try
String str = "success";
stream = new ByteArrayInputStream(str.getBytes());
return SUCCESS;
}
catch (Exception e) {
e.printStackTrace();
String str = "error";
stream = new ByteArrayInputStream(str.getBytes());
return ERROR;
}
}
public InputStream getStream() {
return stream;
}
public void setStream(InputStream stream) {
this.stream = stream;
}
public String getDummyValue() {
return dummyValue;
}
public void setDummyValue(String dummyValue) {
this.dummyValue = dummyValue;
}
}
Javascript function to call action class
function callAbcAction() {
$.ajax({
url : "abcAction",
type: 'post',
data: { },
success : function(result){
if (result == "success") {
window.location='b.jsp';
}
else {
window.location='errorPage';
}
},
});
}
Tag to print dummyMsg in b.jsp
<div class="col-md-3">
<p>Dummy Value is : <s:property value="dummyValue"/></p>
</div>
It is redirecting to b.jsp on success return, but println only "Dummy Value is : " no value is coming.
Please help.
Thanks,
Savvy

Related

JsonObject null when sending from javascript to action struts2

Im working with struts2 .
and when Im Sending A JsonObject from js to action , JsonObject is null.
Code :
Js file :
var data = {"data":[{"name":"ABC","age":"20"},{"name":"XYZ","age":"22"}]};
$.ajax({
url: "Exam1/start",
data: data,
dataType: 'json',
type: 'POST',
contentType: 'application/json',
success: function (res) {
alert("OK");
}
});
and struts.xml :
<package name="default" extends="json-default" namespace="/">
<action name="start" method="init" class="ta.action.InitAction">
<param name="enableSMD">true</param>
<param name="ignoreInterfaces">false</param>
<param name="root">data</param>
<result type="json"/>
</action>
</package>
and Action :
public class InitAction extends ActionSupport{
private List<Student> data; // set and get
public String init() {
System.out.println("Data" + data );// data is null ( Why ??? )
}
}
and Class Student :
public class Student {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}

display generated report via jaspereports on browser

i'm developping a struts2 app,and i want to show up my generated report on browser. i've succefully generate my report on disk.but now i want to see it at browser.here is some code.
my index.jsp
<body>
Reporting
</body>
my action DataBeanList
public class DataBeanList extends ActionSupport {
public ArrayList<DataBean> getDataBeanList() {
ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();
dataBeanList.add(produce("Manisha", "India"));
dataBeanList.add(produce("Dennis Ritchie", "USA"));
dataBeanList.add(produce("V.Anand", "India"));
dataBeanList.add(produce("Shrinath", "California"));
dataBeanList.add(produce("issam", "casa"));
return dataBeanList;
}
/**
* This method returns a DataBean object,
* with name and country set in it.
*/
private DataBean produce(String name, String country) {
DataBean dataBean = new DataBean();
dataBean.setName(name);
dataBean.setCountry(country);
return dataBean;
}
public void exporte(){
String sourceFileName = "D://Test/workspace/ztest/WebContent/reports/jasper_report_template.jasper";
// + "test/jasper_report_template.jasper";
//D:\Test\workspace\ztest\WebContent\reports
String printFileName = null;
DataBeanList DataBeanList = new DataBeanList();
ArrayList dataList = DataBeanList.getDataBeanList();
JRBeanCollectionDataSource beanColDataSource =
new JRBeanCollectionDataSource(dataList);
Map parameters = new HashMap();
try {
printFileName = JasperFillManager.fillReportToFile(sourceFileName,
parameters, beanColDataSource);
if (printFileName != null) {
/**
* 1- export to PDF
*/
JasperExportManager.exportReportToPdfFile(printFileName,
"D://sample_report.pdf");
}
} catch (JRException e) {
e.printStackTrace();
}
}
}
First of all export you report to stream, something like that:
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,
parameters, beanDataSource);
JasperExportManager.exportReportToPdfStream(jasperPrint, out);
Then convert output stream to input stream and assign it inside your action to inputStream variable with getters/setters. And configure action to use stream result.
<action ...>
<result type="stream">
<param name="inputName">inputStream</param>
<param name="contentType">application/pdf</param>
<param name="contentDisposition">attachment;filename="report.pdf"</param>
</result>
</action>

How can i invoke the "execute" method of an Action redirected from another action in Struts 2?

I've got a problem with redirecting from one action to another in struts 2.
In action one (called: StudentZuPruefungHinzufuegen) i am creating action errors and want to show these in action two (called:ZeigePruefungsliste).
If i just use the "redirectAction" from struts it shows the correct action error at the place i wanted to show it. The problem is that the framework doesn't invoke my "execute" method before showing the resultpage with the action errors. Though the table I am filling within my "execute" method is empty and the resulting page is in fact useless.
Can somebody tell me how I can tell Struts to invoke the method while redirecting to action two?
My struts.xml looks like that:
<action name="ZeigePruefungsliste"
class="de.nak.multiplechoice.action.ZeigePruefungslisteAction">
<interceptor-ref name="store">
<param name="operationMode">RETRIEVE</param>
</interceptor-ref>
<interceptor-ref name="defaultLoginStack" />
<result type="tiles" name="*">pruefungsListe</result>
</action>
<action name="StudentZuPruefungHinzufuegen"
class="de.nak.multiplechoice.action.EditiereTeilnehmerAction">
<result type="tiles">studentZuPruefungHinzufuegen</result>
<interceptor-ref name="store">
<param name="operationMode">STORE</param>
</interceptor-ref>
<interceptor-ref name="defaultLoginStack" />
<result name="input" type="redirectAction">
<param name="actionName">
ZeigePruefungsliste
</param>
</result>
</action>
EDIT:
Code of my action classes.
public class EditiereTeilnehmerAction extends AbstractAction {
private static final long serialVersionUID = 882657701678551299L;
private Long ausgewaehltePruefungId;
private List<Nutzer> studenten;
private List<Long> ausgewaehlteStudenten;
#Override
public String execute() {
if (ausgewaehltePruefungId == null) {
addActionError("Es muss eine Prüfung ausgewählt werden.");
return INPUT;
}
studenten = getNutzerService().ladeAlleStudenten();
return SUCCESS;
}
public String zuPruefungHinzufuegen() {
getPruefungService().registriereStudentenFuerPruefung(ausgewaehltePruefungId, ausgewaehlteStudenten);
return SUCCESS;
}
public List<Nutzer> getStudenten() {
return studenten;
}
public void setStudenten(List<Nutzer> studenten) {
this.studenten = studenten;
}
public Long getAusgewaehltePruefungId() {
return ausgewaehltePruefungId;
}
public void setAusgewaehltePruefungId(Long ausgewaehltePruefungId) {
this.ausgewaehltePruefungId = ausgewaehltePruefungId;
}
public List<Long> getAusgewaehlteStudenten() {
return ausgewaehlteStudenten;
}
public void setAusgewaehlteStudenten(List<Long> ausgewaehlteStudenten) {
this.ausgewaehlteStudenten = ausgewaehlteStudenten;
}
}
public class ZeigePruefungslisteAction extends AbstractAction {
private static final long serialVersionUID = -7559234907568287686L;
private List<Pruefung> pruefungen;
#Override
public String execute() {
pruefungen = getPruefungService().getAllePruefungen(getAktuellenNutzer());
return SUCCESS;
}
public List<Pruefung> getPruefungen() {
return pruefungen;
}
}
public abstract class AbstractAction extends ActionSupport {
private static final long serialVersionUID = -6905222101893534102L;
private INutzerService nutzerService;
private IPruefungService pruefungService;
public HttpSession getHttpSession() {
HttpServletRequest request = (HttpServletRequest) ActionContext
.getContext().get(StrutsStatics.HTTP_REQUEST);
return request.getSession(true);
}
public Nutzer getAktuellenNutzer() {
return nutzerService.get(((Nutzer) getHttpSession().getAttribute(
StrutsKonstanten.NUTZER)).getId());
}
protected INutzerService getNutzerService() {
return nutzerService;
}
public void setNutzerService(INutzerService nutzerService) {
this.nutzerService = nutzerService;
}
protected IPruefungService getPruefungService() {
return pruefungService;
}
public void setPruefungService(IPruefungService pruefungService) {
this.pruefungService = pruefungService;
}
}
Greetings,
Marcus

Passing parameters to results in struts2 does not work

I have configured result as follows : Its my custom result type.
<result-types>
<result-type name="myBytesResult" class="blahblah.MyBytesResult" />
</result-types>
<action name="myAction" class="blahblah.MyAction">
<result name="success" type="myBytesResult">
<param name="pptId">${pptId}</param>
</result>
</action>
And my result has setter/getter for pptId and MyAction also has setter/getter for pptId. But when i check in my result, Its not setting pptId (I am getting ${pptId} as string in result). It seems its not getting getter from Action.
What could be reason for the same ?
The code MyAction
public String doDefault() {
System.out.println("Default Called");
setPptId("MyPpt");
return "success";
}
public byte[] getMyImageInBytes() throws Exception {
try {
//.....
} catch (Exception e) {
}
return null;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getPptId() {
return this.pptId;
}
public void setPptId(String pptId) {
this.pptId = pptId;
}
MyBytesResult
private String contentType;
private String pptId;
public void execute(ActionInvocation invocation) throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
//...Some more code for settign response
System.out.println("pt Id[" + this.pptId + "]");
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getPptId() {
return pptId;
}
public void setPptId(String pptId) {
this.pptId = pptId;
}
Updated answer
So, after some digging, it appears that this is actually working properly. It is the responsibility of the Result to evaluate the incoming data as an OGNL expression if that is necessary. This is how the redirect and http header results work. You can parse the value against the stack in your custom result as follows:
String resolvedPptId = TextParseUtil.translateVariables(pptId, stack)
From the Javadoc for translateVariables:
Converts all instances of ${...}, and %{...} in expression to the value returned by a call to {#link ValueStack#findValue(java.lang.String)}. If an item cannot
be found on the stack (null is returned), then the entire variable ${...} is not
displayed, just as if the item was on the stack but returned an empty string.

Return String result type from Struts2

I want to send String as a response to the AJAX xhrPOST method. I am using Struts2 to implement the server side processing. But, I am not getting how to send the result "type" as string and the mapping which should be done to send the string from the struts2 action class to the AJAX response.
You can have your action method return not a String result, but a result of type StreamResult.
In other words:
class MyAction {
public StreamResult method() {
return new StreamResult(new ByteArrayInputStream("mystring".getBytes()));
}
}
You don't necessarily have to return a String from a Struts2 action method. You can always return an implementation of the Result interface from xwork.
copy this in action class
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public String execute(){
inputStream = new StringBufferInputStream("some data to send for ajax response");
return SUCCESS;
}
Struts.xml
<action name=....>
<result type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
This works when we want to send a single data in response
You could create a simple StringResult pretty easily by extending StrutsResultSupport, but nothing exists built-in to the framework as far as I know.
Here's an implementation that I've used in the past of a simple StringResult:
public class StringResult extends StrutsResultSupport {
private static final Log log = LogFactory.getLog(StringResult.class);
private String charset = "utf-8";
private String property;
private String value;
private String contentType = "text/plain";
#Override
protected void doExecute(String finalLocation, ActionInvocation invocation)
throws Exception {
if (value == null) {
value = (String)invocation.getStack().findValue(conditionalParse(property, invocation));
}
if (value == null) {
throw new IllegalArgumentException("No string available in value stack named '" + property + "'");
}
if (log.isTraceEnabled()) {
log.trace("string property '" + property + "'=" + value);
}
byte[] b = value.getBytes(charset);
HttpServletResponse res = (HttpServletResponse) invocation.getInvocationContext().get(HTTP_RESPONSE);
res.setContentType(contentType + "; charset=" + charset);
res.setContentLength(b.length);
OutputStream out = res.getOutputStream();
try {
out.write(b);
out.flush();
} finally {
out.close();
}
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
I've used the json plugin to do similar things. If you use that, you can use the following to expose a single String property in your action:
<result name="success" type="json">
<param name="root">propertyToExpose</param>
</result>

Resources