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>
Related
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
public class Login extends ActionSupport {
//connection made
PreparedStatement pstmt = con.prepareStatement("select * from register1 where username=? and password=?");
pstmt.setString(1, username);
pstmt.setString(2, pwd);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
String role = rs.getString(3);
if (role == null || role.equals("user")) {
session.setAttribute("username", username);
return "Cart"; //here i want to go for another .java file
}
}
Struts.xml
<action name="Login" class="mypack.Login">
<result name="Cart" type="dispatcher">
<param name="location">mypack.CartSelect</param>//Another .java file which support Action Support
</result>
</action>
Class 3:
public class CartSelect extends ActionSupport implements ServletContextAware {
public String execute() throws Exception {
I think what you need is not a dispatcher but instead a redirect.
Here is the reference for redirect action result type.
My problem is i am not able to display the pdf generated on jsp using Struts2.
I am able to generate the pdf dynamically using Dynamic Jasper in struts2 and also able to
download it using the
result type="stream" the only problem i am stuck at is displaying the pdf in jsp. i able to
display it using iframe tag but it display the old pdf not the one i generate at runtime.
if anyone has any suggestions do help me out thanks in advance
Action Class
public class GeneratePdf extends ActionSupport
{
public InputStream inputStream;
File file = new File("D:\\workspace\\desktopApp\\HRIS_Updated\\WebContent\\Jasper\\hris.employee.report.AwardReport.pdf");
public String execute(){
try {
inputStream = new DataInputStream( new FileInputStream(file));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public InputStream getInputStream() {
return inputStream;
}
}
in the .xml file
<action name="GeneratePdf" class="hris.report.action.GeneratePdf">
<result name="success" type="stream">
<param name="contentType">application/pdf</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">inline;filename="test.pdf"</param>
<param name="bufferSize">1024</param>
</result>
</action>
Hope it Helps :)
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.
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>