Showing posts with label Struts2. Show all posts
Showing posts with label Struts2. Show all posts

Wednesday, 25 April 2012

Make Textbox hidden/visible based on the DropDown selection using JavaScript

SOLUTION:

the following function will help you to solve this ......

1
2
3
4
5
6
7
8
function hideTextBox(dropDown1){
var valFromDropDown = dropDown1.value;
if(valFromDropDown == 'WRITE'){
document.forms[0].textBox1.style.visibility = "";
} else{
document.forms[0].textBox1.style.visibility = "hidden";
}
}

in the above example hideTextBox is the function name .....
and the input for this function is dropDown value selected......
in this example we are hiding the the text box if the drop down value is 'WRITE' else it will show the textbox......


the following Example.jsp page will clearly explain you how to implement this and please ignore this Symobl(--)inside the every tag Starting. i put this (--) for displaying html tags only kindly ignore that symbol


Example.jsp(please ignore this(--)symbol and try it it will surely work
--------------------------------------------------------------------

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<%@taglib uri="/includes/struts-html.tld" prefix="html"%>
<%@taglib uri="/includes/struts-bean.tld" prefix="bean"%>
<%@taglib uri="/includes/struts-logic.tld" prefix="logic"%>



<script language="javascript">

function hideTextBox(dropDown1){
var valFromDropDown = dropDown1.value;
if(valFromDropDown == 'WRITE'){
document.forms[0].textBox1.style.visibility = "";
} else{
document.forms[0].textBox1.style.visibility = "hidden";
}
}

</script>




<table width="100%" border="0" cellspacing="0" cellpadding="0">

<tr>
<td width="20%">SelectProcess:
<td width="30%">
<html:select property="dropDown1" onchange="javascript:hideTextBox(this)">
<html:option value="READ">Read
<html:option value="WRITE">Write
<html:option value="OVERWRITE">OverWrite
</html:select>
<td width="20%">
<td width="30%">
</tr>

<tr>
<td width="20%">TextBox1:
<td width="30%">
<td width="30%"><html:text property="textBox1" maxlength="10" size="10">
</td>
<td width="20%">
<td width="30%">

</table>

</html:html>

--------------------------------------------------------------------------------------
from the above Example.jsp you can clearly understood how the function is implemented

note:

you have to declare these property in the form bean this is the example used in struts Frame work.

if you still having doubts write a comment on this.

Thanks

Thursday, 12 April 2012

How to write our own result type in struts2

Action Class


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.lkr.action;


import com.lkr.service.UserService;
import com.lkr.vo.User;
import com.opensymphony.xwork2.ActionSupport;


public class GetImageAction extends ActionSupport {


 private static final long serialVersionUID = 1L;
 private UserService userService;
 private Long id;
 private User user;


 public Long getId() {
  return id;
 }


 public void setId(Long id) {
  this.id = id;
 }


 public UserService getUserService() {
  return userService;
 }


 public void setUserService(UserService userService) {
  this.userService = userService;
 }


 @Override
 public String execute() throws Exception {

  System.out.println("this is come from after display image jsp");
  user = userService.getUserById(id);
  return "imageBytesResult";
 }


 public String getContentDisposition() {
  return "";
 }

 public int getBufferSize() {
  return 4096;
 }
}

Result Type Class


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.lkr.action;


import javax.servlet.http.HttpServletResponse;


import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;


public class ImageBytesResult implements Result {


 private static final long serialVersionUID = 1L;


 @Override
 public void execute(ActionInvocation invocation) throws Exception {
  GetImageAction action = (GetImageAction) invocation.getAction();
  HttpServletResponse response = ServletActionContext.getResponse();


  //response.setContentType(action.getContentType());
  //response.setContentLength(action.getContentLength());
  response.getOutputStream().write(action.getImageInBytes());
  response.getOutputStream().flush();
 }


}

Service


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.lkr.service;


import java.util.List;

import com.lkr.dao.UserDAO;
import com.lkr.vo.User;


public class UserService{
 private UserDAO userDao;


 public UserDAO getUserDao() {
  return userDao;
 }


 public void setUserDao(UserDAO userDao) {
  this.userDao = userDao;
 }


 
 public User save(User user) throws Exception {


  return userDao.save(user);
 }



 public List<User> getAllUsers() throws Exception {


  return userDao.getAllUsers();
 }


 
 public User getUserById(long id) throws Exception {
  return userDao.getUserById(id);
 }
}

DAO


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.lkr.dao;


import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;

import org.hibernate.Transaction;

import com.lkr.vo.User;


public class UserDAO {


 
 public User save(User user) throws Exception {
  Transaction tx=getSession().beginTransaction();
  getSession().save(user);
  
  tx.commit();
  return user;
 }


 
 public List<User> getAllUsers() throws Exception {
  List<User> allUsers = getSession().createQuery("from User").list();
  return allUsers;
 }


 
 public User getUserById(long id) throws Exception {
  User user = (User) getSession().get(User.class, new Long(id));
  // Convert BLOB to byte array
  user.setImageInBytes(getImageInBytes(user));
  user.setContentLength((int) user.getImage().length());
  return user;
 }


 public byte[] getImageInBytes(User user) {


  if (user.getImage() == null) {
   return new byte[0];
  }
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try {
   InputStream is = user.getImage().getBinaryStream();
   byte[] buf = new byte[1024];
   int i = 0;
   while ((i = is.read(buf)) >= 0) {
    baos.write(buf, 0, i);
   }
   is.close();
  } catch (Exception ex) {
   ex.printStackTrace();
  }
  return baos.toByteArray();
 }
}

struts.xml


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">


<struts>
 <constant name="struts.devMode" value="false" />
 <constant name="struts.custom.i18n.resources" value="global" />
 <constant name="struts.objectFactory" value="spring" />


 <package name="commonPackage" namespace="/" extends="struts-default">


  <result-types>
   <result-type name="imageBytesResult"
    class="com.lkr.action.ImageBytesResult" />
  </result-types>


  <action name="addUserData" class="com.lkr.action.UserAction">
   <result name="input">
    WEB-INF/jsp/imageUploader.jsp
   </result>
  </action>
  <action name="displayFullImage" class="com.lkr.action.FullImageAction">
   <result name="input">
    WEB-INF/jsp/dispalyFullImage.jsp
   </result>
  </action>


  <action name="getImage" class="com.lkr.action.GetImageAction">
   <result name="imageBytesResult" type="imageBytesResult">
   </result>
  </action>
 </package>


</struts>

If you are directly getting Byte[] from the database then you don't need to convert Blob to Byte[]

Saturday, 7 April 2012

Creating Pdf By Using Struts2

Struts Framework and Stream Result type configuration for the Action to send binary stream to the browser as PDF
content type

In this example I shall be showing step by step ways to follow through various pieces of code to process or achieve
an objective of presenting binary content type to browser based client and this is presented to the client with the
same name as mentioned in struts.xml configuration file.

Struts.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
  <package name="stream-example" namespace="/sample-stream"
                 extends="struts-default">
    <action name="pdfAction" class="com.lkr.struts2.pdf.GeneratingPdfAction" 
                        method="generatingPdf">
       <result name="test-stream" type="stream">
         <param name="inputName">fileStream</param>
  <param name="contentType">application/pdf</param>
         <param name="contentDisposition">filename="test.pdf"</param>
       </result>
    </action>
  </package>
</struts>

Action class "GeneratingPdfAction.java" is having a generatingPdf method that assigns an input stream to a private
instance variable, this variable is mentioned as the inputName param value to the result tag.

In this example, the inputName param is having value as fileStream, that is defined as an instance variable
in Action class.


GeneratingPdfAction

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package com.lkr.struts2.pdf;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class GeneratingPdfAction {
 private InputStream fileStream;
 private static String FILE = "c:/temp/FirstPdf.pdf";
 private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
   Font.BOLD);
 private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
   Font.NORMAL, BaseColor.RED);
 private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
   Font.BOLD);
 private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
   Font.BOLD);

 public void setFileStream(InputStream arg) {
  fileStream = arg;
 }

 public InputStream getFileStream() {
  return fileStream;
 }


 public String generatingPdf() throws Exception {
  
  try {
   Document document = new Document();
   PdfWriter.getInstance(document, new FileOutputStream(FILE));
   document.open();
   addMetaData(document);
   addTitlePage(document);
   addContent(document);
   document.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
  try{
   fileStream = new DataInputStream(
     new FileInputStream(FILE));
  } catch (IOException ioEx) {
   ioEx.printStackTrace();
  }
  
  return "test-stream";
 }
 
 private static void addMetaData(Document document) {
  document.addTitle("My first PDF");
  document.addSubject("Using iText");
  document.addKeywords("Java, PDF, iText");
  document.addAuthor("Konda Reddy. Lingamdinne");
  document.addCreator("Konda Reddy. Lingamdinne");
 }

 private static void addTitlePage(Document document)
   throws DocumentException {
  Paragraph preface = new Paragraph();
  // We add one empty line
  addEmptyLine(preface, 1);
  // Lets write a big header
  preface.add(new Paragraph("Title of the document", catFont));

  addEmptyLine(preface, 1);
  // Will create: Report generated by: _name, _date
  preface.add(new Paragraph(
    "Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    smallBold));
  addEmptyLine(preface, 3);
  preface.add(new Paragraph(
    "This document describes something which is very important ",
    smallBold));

  addEmptyLine(preface, 8);

  preface.add(new Paragraph(
    "This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.de ;-).",
    redFont));

  document.add(preface);
  // Start a new page
  document.newPage();
 }

 private static void addContent(Document document) throws DocumentException {
  Anchor anchor = new Anchor("First Chapter", catFont);
  anchor.setName("First Chapter");

  // Second parameter is the number of the chapter
  Chapter catPart = new Chapter(new Paragraph(anchor), 1);

  Paragraph subPara = new Paragraph("Subcategory 1", subFont);
  Section subCatPart = catPart.addSection(subPara);
  subCatPart.add(new Paragraph("Hello"));

  subPara = new Paragraph("Subcategory 2", subFont);
  subCatPart = catPart.addSection(subPara);
  subCatPart.add(new Paragraph("Paragraph 1"));
  subCatPart.add(new Paragraph("Paragraph 2"));
  subCatPart.add(new Paragraph("Paragraph 3"));

  // Add a list
  Paragraph paragraph = new Paragraph();
  addEmptyLine(paragraph, 5);
  subCatPart.add(paragraph);

  // Add a table
  createTable(subCatPart);

  // Now add all this to the document
  document.add(catPart);

  // Next section
  anchor = new Anchor("Second Chapter", catFont);
  anchor.setName("Second Chapter");

  // Second parameter is the number of the chapter
  catPart = new Chapter(new Paragraph(anchor), 1);

  subPara = new Paragraph("Subcategory", subFont);
  subCatPart = catPart.addSection(subPara);
  subCatPart.add(new Paragraph("This is a very important message"));

  // Now add all this to the document
  document.add(catPart);

 }

 private static void createTable(Section subCatPart)
   throws BadElementException {
  PdfPTable table = new PdfPTable(3);

  // t.setBorderColor(BaseColor.GRAY);
  // t.setPadding(4);
  // t.setSpacing(4);
  // t.setBorderWidth(1);

  PdfPCell c1 = new PdfPCell(new Phrase("Table Header 1"));
  c1.setHorizontalAlignment(Element.ALIGN_CENTER);
  table.addCell(c1);

  c1 = new PdfPCell(new Phrase("Table Header 2"));
  c1.setHorizontalAlignment(Element.ALIGN_CENTER);
  table.addCell(c1);

  c1 = new PdfPCell(new Phrase("Table Header 3"));
  c1.setHorizontalAlignment(Element.ALIGN_CENTER);
  table.addCell(c1);
  table.setHeaderRows(1);

  table.addCell("1.0");
  table.addCell("1.1");
  table.addCell("1.2");
  table.addCell("2.1");
  table.addCell("2.2");
  table.addCell("2.3");

  subCatPart.add(table);

 }

 private static void addEmptyLine(Paragraph paragraph, int number) {
  for (int i = 0; i < number; i++) {
   paragraph.add(new Paragraph(" "));
  }
 }

}


web.xml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, 
    Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <display-name>Struts 2 Stream Result type</display-name>
  <filter>
  <filter-name>sample-filter</filter-name>
  <filter-class> 
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>sample-filter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

This example application creates PDF file and reads the PDF file from the path mentioned in the Action class and  
generatingPdf method.
This result type definition in struts.xml file sends those to the client as downloadable file name.