﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-Sun River-随笔分类-Struts and JSF</title><link>http://www.blogjava.net/SunRiver/category/17339.html</link><description>Topics about Java EE, XML,AJAX,SOA,OSGi,DB, .NET etc.</description><language>zh-cn</language><lastBuildDate>Fri, 10 Aug 2007 16:34:05 GMT</lastBuildDate><pubDate>Fri, 10 Aug 2007 16:34:05 GMT</pubDate><ttl>60</ttl><item><title>POI</title><link>http://www.blogjava.net/SunRiver/archive/2007/08/09/135443.html</link><dc:creator>Sun River</dc:creator><author>Sun River</author><pubDate>Thu, 09 Aug 2007 04:37:00 GMT</pubDate><guid>http://www.blogjava.net/SunRiver/archive/2007/08/09/135443.html</guid><description><![CDATA[Example One:创建XLS<br><br>群众：笑死人了，这还要你教么，别丢人现眼了，用FileOutputStream就可以了，写个文件，扩展名为xls就可以了，哈哈，都懒得看你的，估计又是个水货上来瞎喊，下去，哟货~~<br><br>小笔：无聊的人一边去，懒得教你，都没试过，还鸡叫鸡叫，&amp;^%&amp;**(()&amp;%$#$#@#@<br><br><span class=Code><br><font style="BACKGROUND-COLOR: #fafafa" face=Courier size=2>&nbsp;&nbsp;&nbsp; HSSFWorkbook wb = new HSSFWorkbook();//构建新的XLS文档对象<br>&nbsp;&nbsp;&nbsp; FileOutputStream fileOut = new FileOutputStream("workbook.xls");<br>&nbsp;&nbsp;&nbsp; wb.write(fileOut);//注意，参数是文件输出流对象<br>&nbsp;&nbsp;&nbsp; fileOut.close();<br><br></font></span><br><br>Example Two:创建Sheet<br><br>群众：有点责任心好吧，什么是Sheet?欺负我们啊？<br><br>小笔：花300块去参加Office 培训班去，我不负责教预科<br><br><br>&nbsp;&nbsp;&nbsp;<font size=2><font style="BACKGROUND-COLOR: #fafafa"><font face=Courier><span class=Code>HSSFWorkbook wb = new HSSFWorkbook();//创建文档对象<br>&nbsp;&nbsp;&nbsp; HSSFSheet sheet1 = wb.createSheet("new sheet");//创建Sheet对象，参数为Sheet的标题<br>&nbsp;&nbsp;&nbsp; HSSFSheet sheet2 = wb.createSheet("second sheet");//同上,注意，同是wb对象，是一个XLS的两个Sheet<br>&nbsp;&nbsp;&nbsp; FileOutputStream fileOut = new FileOutputStream("workbook.xls");<br>&nbsp;&nbsp;&nbsp; wb.write(fileOut);<br>&nbsp;&nbsp;&nbsp; fileOut.close();<br></span><br><br></font></font></font>Example Three:创建小表格，并为之填上数据<br><br>群众：什么是小表格啊？<br><br>小笔：你用过Excel吗？人家E哥天天都穿的是网格衬衫~~~~<br><br><span class=Code><br><font style="BACKGROUND-COLOR: #fafafa" face=Courier size=2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HSSFWorkbook document = new HSSFWorkbook();//创建XLS文档<br><br>HSSFSheet salary = document.createSheet("薪水");//创建Sheet<br><br>HSSFRow titleRow = salary.createRow(0);//创建本Sheet的第一行<br><br><br><br>titleRow.createCell((short) 0).setCellValue("工号");//设置第一行第一列的值<br>titleRow.createCell((short) 1).setCellValue("薪水");//......<br>titleRow.createCell((short) 2).setCellValue("金额");//设置第一行第二列的值<br><br><br>File filePath = new File(baseDir+"excel/example/");<br><br>if(!filePath.exists())<br>filePath.mkdirs();<br><br>FileOutputStream fileSystem = new FileOutputStream(filePath.getAbsolutePath()+"/Three.xls");<br><br>document.write(fileSystem);<br><br>fileSystem.close();<br></font></span>
<p>&nbsp;</p>
<p>Example Four :带自定义样式的数据(eg:Date)<br><br>群众：Date！么搞错，我昨天已经插入成功了~<br><br>小笔：是么？那我如果要你5/7/06 4：23这样输出你咋搞？<br><br>群众：无聊么？能写进去就行了！<br><br>小笔：一边凉快去~<br><br><span class=Code><br><font style="BACKGROUND-COLOR: #fafafa" face=Courier size=2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HSSFWorkbook document = new HSSFWorkbook();<br><br>HSSFSheet sheet = document.createSheet("日期格式");<br><br>HSSFRow row = sheet.createRow(0);<br><br><br>HSSFCell secondCell = row.createCell((short) 0);<br><br>/**<br>&nbsp;* 创建表格样式对象<br>&nbsp;*/<br>HSSFCellStyle style = document.createCellStyle();<br><br>/**<br>&nbsp;* 定义数据显示格式<br>&nbsp;*/<br>style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));<br><br>/**<br>&nbsp;* setter<br>&nbsp;*/<br>secondCell.setCellValue(new Date());<br><br>/**<br>&nbsp;* 设置样式<br>&nbsp;*/<br>secondCell.setCellStyle(style);<br><br><br><br>File filePath = new File(baseDir+"excel/example/");<br><br>if(!filePath.exists())<br>filePath.mkdirs();<br><br>FileOutputStream fileSystem = new FileOutputStream(filePath.getAbsolutePath()+"/Four.xls");<br><br>document.write(fileSystem);<br><br>fileSystem.close();<br><br></font></span></p>
<p>Example Five:读取XLS文档<br><br><br><font size=2><font style="BACKGROUND-COLOR: #fafafa"><font face=Courier><span class=Code>File filePath = new File(baseDir+"excel/example/");<br><br>if(!filePath.exists())<br>throw new Exception("没有该文件");<br>/**<br>&nbsp;* 创建对XLS进行读取的流对象<br>&nbsp;*/<br>POIFSFileSystem reader = new POIFSFileSystem(new FileInputStream(filePath.getAbsolutePath()+"/Three.xls"));<br>/**<br>&nbsp;* 从流对象中分离出文档对象<br>&nbsp;*/<br>HSSFWorkbook document = new HSSFWorkbook(reader);<br>/**<br>&nbsp;* 通过文档对象获取Sheet<br>&nbsp;*/<br>HSSFSheet sheet = document.getSheetAt(0);<br>/**<br>&nbsp;* 通过Sheet获取指定行对象<br>&nbsp;*/<br>HSSFRow row = sheet.getRow(0);<br>/**<br>&nbsp;* 通过行、列定位Cell<br>&nbsp;*/<br>HSSFCell cell = row.getCell((short) 0);<br><br>/**<br>&nbsp;* 输出表格数据<br>&nbsp;*/<br>log.info(cell.getStringCellValue());<br></span><br><br></font></font></font>至此，使用POI操作Excel的介绍告一段落，POI是一个仍然在不断改善的项目，有很多问题，比如说中文问题，大数据量内存溢出问题等等，但这个Pure Java的库的性能仍然是不容质疑的，是居家旅行必备良品。<br><br>而且开源软件有那么一大点好处是，可以根据自己的需要自己去定制。如果大家有中文、性能等问题没解决的，可以跟我索要我已经改好的库。当然，你要自己看原代码，我也不拦你。<br></p>
<br>
<img src ="http://www.blogjava.net/SunRiver/aggbug/135443.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/SunRiver/" target="_blank">Sun River</a> 2007-08-09 12:37 <a href="http://www.blogjava.net/SunRiver/archive/2007/08/09/135443.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Java, POI and Excel </title><link>http://www.blogjava.net/SunRiver/archive/2007/08/09/135436.html</link><dc:creator>Sun River</dc:creator><author>Sun River</author><pubDate>Thu, 09 Aug 2007 04:26:00 GMT</pubDate><guid>http://www.blogjava.net/SunRiver/archive/2007/08/09/135436.html</guid><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: &nbsp;如何将JSP中将查询结果导出为Excel，其实可以利用jakarta提供的POI接口将查询结果导出到excel。POI接口是jakarta组织的一个子项目，它包括POIFS，HSSF，HWSF，HPSF，HSLF，目前比较成熟的是HSSF，它是一组操作微软的excel文档的API，现在到达3.0版本，已经能够支持将图片插入到excel里面。java 代码import&nbsp;...&nbsp;&nbsp;<a href='http://www.blogjava.net/SunRiver/archive/2007/08/09/135436.html'>阅读全文</a><img src ="http://www.blogjava.net/SunRiver/aggbug/135436.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/SunRiver/" target="_blank">Sun River</a> 2007-08-09 12:26 <a href="http://www.blogjava.net/SunRiver/archive/2007/08/09/135436.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Recipe </title><link>http://www.blogjava.net/SunRiver/archive/2007/08/07/135030.html</link><dc:creator>Sun River</dc:creator><author>Sun River</author><pubDate>Tue, 07 Aug 2007 10:28:00 GMT</pubDate><guid>http://www.blogjava.net/SunRiver/archive/2007/08/07/135030.html</guid><description><![CDATA[<h3 class=docSection1Title id=408942-967>Populating Value Objects from ActionForms</h3>
<a name=jakartastrutsckbk-CHP-5-SECT-6.1></a>
<h4 class=docSection2Title>Problem</h4>
<p class=docText>You don't want to have to write numerous getters and setters to pass data from your action forms to your business objects.</p>
<a name=jakartastrutsckbk-CHP-5-SECT-6.2></a>
<h4 class=docSection2Title>Solution</h4>
<p class=docText>Use the<a name=jakartastrutsckbk-CHP-5-ITERM-1842></a> <a name=jakartastrutsckbk-CHP-5-ITERM-1843></a>introspection utilities provided by the Jakarta Commons BeanUtils package in your <tt>Action.execute( )</tt> method:</p>
<pre><span class=docEmphBold>import org.apache.commons.beanutils.*;</span>
// other imports omitted
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
BusinessBean businessBean = new BusinessBean( );
<strong>BeanUtils.copyProperties(businessBean, form);</strong>
// ... rest of the Action</pre>
<br><a name=jakartastrutsckbk-CHP-5-SECT-6.3></a>
<h4 class=docSection2Title>Discussion</h4>
<p class=docText>A significant portion of the development effort for a web application is spent moving data to and from the different system tiers. Along the way, the data may be transformed in one way or another, yet many of these transformations are required because the tier to which the data is moving requires the information to be represented in a different way.</p>
<p class=docText>Data sent in the HTTP request is represented as simple text. For some data types, the value can be represented as a <tt>String</tt> object throughout the application. However, many data types should be represented in a different format in the business layer than on the view. Date fields provide the classic example. A date field is retrieved from a form's input field as a <tt>String</tt>. Then it must be converted to a <tt>java.util.Date</tt> in the model. Furthermore, when the value is persisted, it's usually transformed again, this time to a <tt>java.sql.Timestamp</tt>. Numeric fields require similar transformations.</p>
<p class=docText>The Jakarta Commons BeanUtils package supplied with the Struts distribution provides some great utilities automating the movement and conversion of data between objects. These utilities use JavaBean property names to match the source property to the destination property for data transfer. To leverage these utilities, ensure you give your properties consistent, meaningful names. For example, to represent an employee ID number, you may decide to use the property name <tt>employeeId</tt>. In all classes that contain an employee ID, you should use that name. Using <tt>empId</tt> in one class and <tt>employeeIdentifier</tt> in another will only lead to confusion among your developers and will render the BeanUtils facilities useless.</p>
<p class=docText>The entire conversion and copying of properties from <tt>ActionForm</tt> to business object can be performed with one static method call:<a name=jakartastrutsckbk-CHP-5-ITERM-1844></a></p>
<pre><strong>BeanUtils.copyProperties(</strong>
<span class=docEmphBoldItalic>businessBean</span>
<strong>, </strong>
<span class=docEmphBoldItalic>form</span>
<strong>);</strong></pre>
<br>
<p class=docText>This <tt>copyProperties( )</tt> method attempts to copy each JavaBean property in <tt><em>form</em></tt> to the property with the same name in <tt><em>businessBean</em></tt>. If a property in <tt><em>form</em></tt> doesn't have a matching property in <tt><em>businessBean</em></tt>, that property is silently ignored. If the data types of the matched properties are different, BeanUtils will attempt to convert the value to the type expected. BeanUtils provides converters from <tt>String</tt>s to the following types:<a name=jakartastrutsckbk-CHP-5-ITERM-1845></a> <a name=jakartastrutsckbk-CHP-5-ITERM-1846></a><a name=jakartastrutsckbk-CHP-5-ITERM-1847></a></p>
<ul>
    <li>
    <p class=docList><tt>java.lang.BigDecimal</tt></p>
    <li>
    <p class=docList><tt>java.lang.BigInteger</tt></p>
    <li>
    <p class=docList><tt>boolean</tt> and <tt>java.lang.Boolean</tt></p>
    <li>
    <p class=docList><tt>byte</tt> and <tt>java.lang.Byte</tt></p>
    <li>
    <p class=docList><tt>char</tt> and <tt>java.lang.Character</tt></p>
    <li>
    <p class=docList><tt>java.lang.Class</tt></p>
    <li>
    <p class=docList><tt>double</tt> and <tt>java.lang.Double</tt></p>
    <li>
    <p class=docList><tt>float</tt> and <tt>java.lang.Float</tt></p>
    <li>
    <p class=docList><tt>int</tt> and <tt>java.lang.Integer</tt></p>
    <li>
    <p class=docList><tt>long</tt> and <tt>java.lang.Long</tt></p>
    <li>
    <p class=docList><tt>short</tt> and <tt>java.lang.Short</tt></p>
    <li>
    <p class=docList><tt>java.lang.String</tt></p>
    <li>
    <p class=docList><tt>java.sql.Date</tt></p>
    <li>
    <p class=docList><tt>java.sql.Time</tt></p>
    <li>
    <p class=docList><tt>java.sql.Timestamp</tt></p>
    </li>
</ul>
<p class=docText>While the conversions to character-based and numeric types should cover most of your needs, <a name=jakartastrutsckbk-CHP-5-ITERM-1848></a><a name=jakartastrutsckbk-CHP-5-ITERM-1849></a>date type fields (as shown in <a class=docLink href="mk:@MSITStore:E:\Java%20DOCs\Struts\Struts%20Cookbook%20(2005)%20-%20LiB.chm::/059600771X/jakartastrutsckbk-CHP-3-SECT-13.html#jakartastrutsckbk-CHP-3-SECT-13">Recipe 3-13</a>) can be problematic. A good solution suggested by Ted Husted is to implement transformation getter and setter methods in the business object that convert from the native type (e.g. <tt>java.util.Date</tt>) to a <tt>String</tt> and back again.</p>
<p>
<table cellSpacing=0 cellPadding=1 width="90%" align=center bgColor=black border=0>
    <tbody>
        <tr>
            <td>
            <table cellSpacing=0 cellPadding=6 width="100%" bgColor=white border=0>
                <tbody>
                    <tr>
                        <td vAlign=top width=60><img height=54 alt="" src="mk:@MSITStore:E:\Java%20DOCs\Struts\Struts%20Cookbook%20(2005)%20-%20LiB.chm::/059600771X/images/tip_yellow.gif" width=50></td>
                        <td vAlign=top>
                        <p class=docText>Because BeanUtils knows how to handle <tt>DynaBean</tt>s and the <tt>DynaActionForm</tt> implements <tt>DynaBean</tt>, the Solution will work unchanged for <tt>DynaActionForm</tt>s and normal <tt>ActionForm</tt>s.</p>
                        </td>
                    </tr>
                </tbody>
            </table>
            </td>
        </tr>
    </tbody>
</table>
</p>
<br>
<p class=docText>As an example, suppose you want to collect information about an employee for a human resources application. Data to be gathered includes the employee ID, name, salary, marital status, and hire date. <a class=docLink href="mk:@MSITStore:E:\Java%20DOCs\Struts\Struts%20Cookbook%20(2005)%20-%20LiB.chm::/059600771X/jakartastrutsckbk-chp-5-sect-6.html#jakartastrutsckbk-CHP-5-EX-9">Example 5-9</a> shows the <tt>Employee</tt> business object. Most of the methods of this class are getters and setters; for the <tt>hireDate</tt> property, however, helper methods are provided that get and set the value from a <tt>String</tt>.</p>
<a name=jakartastrutsckbk-CHP-5-EX-9></a><a name=jakartastrutsckbk-CHP-5-ITERM-1850></a>
<h5 class=docExampleTitle>Example 5-9. Employee business object</h5>
<pre>package com.oreilly.strutsckbk.ch05;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Employee {
private String employeeId;
private String firstName;
private String lastName;
private Date hireDate;
private boolean married;
private BigDecimal salary;
public BigDecimal getSalary( ) {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public String getEmployeeId( ) {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getFirstName( ) {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName( ) {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isMarried( ) {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
public Date getHireDate( ) {
return hireDate;
}
public void setHireDate(Date HireDate) {
this.hireDate = HireDate;
}
public String getHireDateDisplay( ) {
if (hireDate == null)
return "";
else
return dateFormatter.format(hireDate);
}
public void setHireDateDisplay(String hireDateDisplay) {
if (hireDateDisplay == null)
hireDate = null;
else {
try {
hireDate = dateFormatter.parse(hireDateDisplay);
} catch (ParseException e) {
e.printStackTrace( );
}
}
}
private DateFormat dateFormatter = new SimpleDateFormat("mm/DD/yy");
}</pre>
<br>
<p class=docText><a class=docLink href="mk:@MSITStore:E:\Java%20DOCs\Struts\Struts%20Cookbook%20(2005)%20-%20LiB.chm::/059600771X/jakartastrutsckbk-chp-5-sect-6.html#jakartastrutsckbk-CHP-5-EX-10">Example 5-10</a> shows the corresponding <tt>ActionForm</tt> that will retrieve the data from the HTML form. The hire date is represented in the <tt>ActionForm</tt> as a <tt>String</tt> property, <tt>hireDateDisplay</tt>. The salary property is a <tt>java.lang.String</tt>, not a <tt>java.math.BigDecimal</tt>, as in the <tt>Employee</tt> object of <a class=docLink href="mk:@MSITStore:E:\Java%20DOCs\Struts\Struts%20Cookbook%20(2005)%20-%20LiB.chm::/059600771X/jakartastrutsckbk-chp-5-sect-6.html#jakartastrutsckbk-CHP-5-EX-9">Example 5-9</a>.</p>
<a name=jakartastrutsckbk-CHP-5-EX-10></a><a name=jakartastrutsckbk-CHP-5-ITERM-1851></a>
<h5 class=docExampleTitle>Example 5-10. Employee ActionForm</h5>
<pre>package com.oreilly.strutsckbk.ch05;
import java.math.BigDecimal;
import org.apache.struts.action.ActionForm;
public class EmployeeForm extends ActionForm {
private String firstName;
private String lastName;
private String hireDateDisplay;
private String salary;
private boolean married;
public String getEmployeeId( ) {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getFirstName( ) {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName( ) {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isMarried( ) {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
public String getHireDateDisplay( ) {
return hireDateDisplay;
}
public void setHireDateDisplay(String hireDate) {
this.hireDateDisplay = hireDate;
}
public String getSalary( ) {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
}</pre>
<br>
<p class=docText>If you wanted to use a <tt>DynaActionForm</tt>, you would configure it identically as the <tt>EmployeeForm</tt> class. The <tt>form-bean</tt> declarations from the <span class=docEmphasis>struts-config.xml</span> file show the declarations for the <tt>EmployeeForm</tt> and a functionally identical <tt>DynaActionForm</tt>:</p>
<pre>&lt;form-bean name="EmployeeForm"
type="com.oreilly.strutsckbk.ch05.EmployeeForm"/&gt;
&lt;form-bean name="EmployeeDynaForm"
type="org.apache.struts.action.DynaActionForm"&gt;
&lt;form-property name="employeeId" type="java.lang.String"/&gt;
&lt;form-property name="firstName" type="java.lang.String"/&gt;
&lt;form-property name="lastName" type="java.lang.String"/&gt;
&lt;form-property name="salary" type="java.lang.String"/&gt;
&lt;form-property name="married" type="java.lang.Boolean"/&gt;
&lt;form-property name="hireDateDisplay" type="java.lang.String"/&gt;
&lt;/form-bean&gt;</pre>
<br>
<p class=docText>The following is the <tt>action</tt> mapping that processes the form. In this case, the <tt>name</tt> attribute refers to the handcoded <tt>EmployeeForm</tt>. You could, however, change this to use the <tt>EmployeeDynaForm</tt> without requiring any modifications to the <tt>SaveEmployeeAction</tt> or the <span class=docEmphasis>view_emp.jsp</span> JSP page:</p>
<pre>&lt;action    path="/SaveEmployee"
name="EmployeeForm"
scope="request"
type="com.oreilly.strutsckbk.ch05.SaveEmployeeAction"&gt;
&lt;forward name="success" path="/view_emp.jsp"/&gt;
&lt;/action&gt;</pre>
<br>
<p class=docText>The data is converted and copied from the form to the business object in the <tt>SaveEmployeeAction</tt> shown in <a class=docLink href="mk:@MSITStore:E:\Java%20DOCs\Struts\Struts%20Cookbook%20(2005)%20-%20LiB.chm::/059600771X/jakartastrutsckbk-chp-5-sect-6.html#jakartastrutsckbk-CHP-5-EX-11">Example 5-11</a>.</p>
<a name=jakartastrutsckbk-CHP-5-EX-11></a>
<h5 class=docExampleTitle>Example 5-11. Action to save employee data</h5>
<pre>package com.oreilly.strutsckbk.ch05;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class SaveEmployeeAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
Employee emp = new Employee( );
// Copy to business object from ActionForm
BeanUtils.copyProperties( emp, form );
request.setAttribute("employee", emp);
return mapping.findForward("success");
}
}</pre>
<br>
<p class=docText>Finally, two <a name=jakartastrutsckbk-CHP-5-ITERM-1852></a>JSP pages complete the example. The JSP of <a class=docLink href="mk:@MSITStore:E:\Java%20DOCs\Struts\Struts%20Cookbook%20(2005)%20-%20LiB.chm::/059600771X/jakartastrutsckbk-chp-5-sect-6.html#jakartastrutsckbk-CHP-5-EX-12">Example 5-12</a> (<span class=docEmphasis>edit_emp.jsp</span>) renders the HTML form to retrieve the data.</p>
<a name=jakartastrutsckbk-CHP-5-EX-12></a>
<h5 class=docExampleTitle>Example 5-12. Form for editing employee data</h5>
<pre>&lt;%@ page contentType="text/html;charset=UTF-8" language="java" %&gt;
&lt;%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix=
"bean" %&gt;
&lt;%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix=
"html" %&gt;
&lt;%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Struts Cookbook - Chapter 5 : Add Employee&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h2&gt;Edit Employee&lt;/h2&gt;
&lt;html:form action="/SaveEmployee"&gt;
Employee ID: &lt;html:text property="employeeId"/&gt;&lt;br /&gt;
First Name: &lt;html:text property="firstName"/&gt;&lt;br /&gt;
Last Name: &lt;html:text property="lastName"/&gt;&lt;br /&gt;
Married? &lt;html:checkbox property="married"/&gt;&lt;br /&gt;
Hired on Date: &lt;html:text property="hireDateDisplay"/&gt;&lt;br /&gt;
Salary: &lt;html:text property="salary"/&gt;&lt;br /&gt;
&lt;html:submit/&gt;
&lt;/html:form&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<br>
<p class=docText>The JSP in <a class=docLink href="mk:@MSITStore:E:\Java%20DOCs\Struts\Struts%20Cookbook%20(2005)%20-%20LiB.chm::/059600771X/jakartastrutsckbk-chp-5-sect-6.html#jakartastrutsckbk-CHP-5-EX-13">Example 5-13</a> (<span class=docEmphasis>view_emp.jsp</span>) displays the results. This page is rendering data from the business object, and not an <tt>ActionForm</tt>. This is acceptable since the data on this page is for display purposes only. This approach allows for the formatting of data, (<tt>salary</tt> and <tt>hireDate</tt>) to be different than the format in which the values were entered.</p>
<a name=jakartastrutsckbk-CHP-5-EX-13></a><a name=jakartastrutsckbk-CHP-5-ITERM-1853></a>
<h5 class=docExampleTitle>Example 5-13. View of submitted employee data</h5>
<pre>&lt;%@ page contentType="text/html;charset=UTF-8" language="java" %&gt;
&lt;%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix=
"bean" %&gt;
&lt;%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Struts Cookbook - Chapter 5 : View Employee&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h2&gt;View Employee&lt;/h2&gt;
Employee ID: &lt;bean:write name="employee" property="employeeId"/&gt;&lt;br /&gt;
First Name: &lt;bean:write name="employee" property="firstName"/&gt;&lt;br /&gt;
Last Name: &lt;bean:write name="employee" property="lastName"/&gt;&lt;br /&gt;
Married? &lt;bean:write name="employee" property="married"/&gt;&lt;br /&gt;
Hired on Date: &lt;bean:write name="employee" property="hireDate"
format="MMMMM dd, yyyy"/&gt;&lt;br /&gt;
Salary: &lt;bean:write name="employee" property="salary" format="$##0.00"/
&gt;&lt;br /&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<br>
<p class=docText>When you work with this example, swap out the handcoded form for the <tt>DyanActionForm</tt> to see how cleanly BeanUtils works. When you consider how many files need to be changed for one additional form input, the use of BeanUtils in conjunction with <a name=jakartastrutsckbk-CHP-5-ITERM-1854></a><tt>DynaActionForm</tt>s becomes obvious.</p>
<img src ="http://www.blogjava.net/SunRiver/aggbug/135030.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/SunRiver/" target="_blank">Sun River</a> 2007-08-07 18:28 <a href="http://www.blogjava.net/SunRiver/archive/2007/08/07/135030.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>2006-12-03: Questions about Struts</title><link>http://www.blogjava.net/SunRiver/archive/2006/12/04/85377.html</link><dc:creator>Sun River</dc:creator><author>Sun River</author><pubDate>Mon, 04 Dec 2006 07:46:00 GMT</pubDate><guid>http://www.blogjava.net/SunRiver/archive/2006/12/04/85377.html</guid><description><![CDATA[
		<p>
				<font color="#000080">
						<b>
								<font color="#ff1493">Question:</font>
						</b> How you will handle exceptions in Struts?<br /><b>Answer:</b> In Struts you can handle the exceptions in two ways:<br /><b>a) Declarative Exception Handling: </b>You can either define global exception handling tags in your struts-config.xml or define the exception handling tags within &lt;action&gt;..&lt;/action&gt; tag. <br /><b>Example:</b></font>
				<br />
				<font color="#000080">&lt;exception <br /></font>
				<font color="#000080">      key="database.error.duplicate"<?XML:NAMESPACE PREFIX = O /?><o:p> <br /></o:p></font>
				<font color="#000080">      path="/UserExists.jsp"<o:p> <br /></o:p></font>
				<font color="#000080">      type="mybank.account.DuplicateUserException"/&gt;<br /></font>
				<font color="#000080">
						<b>b) Programmatic Exception Handling:</b> Here you can use try{}catch{} block to handle the exception.<o:p><br /><strong><font color="#ff1493">Question:</font><b>Explain Struts navigation flow?<br /></b>Struts Navigation flow.<br />1) A request is made from previously displayed view.<br />2) The request reaches the ActionServlet which acts as the controller .The ActionServlet Looksup the requested URI in an XML file (Struts-Config.xml) and determines the name of the Action class that has to perform the requested business logic.<br />3)The Action Class performs its logic on the Model Components associated with the Application.<br />4) Once The Action has been completed its processing it returns the control to the Action Servlet.As part of its return the Action Class provides a key to determine where the results should be forwarded for presentation.<br />5)The request is complete when the Action Servlet responds by forwarding the request to the view, and this view represents the result of the action.<br /><font color="#ff1493">Question: <b><font color="#0000ff">What is the purpose of tiles-def.xml file, resourcebundle.properties file, validation.xml file?<br /></font></b><font color="#0000ff">1. tiles-def.xml<br />  tiles-def.xml is used as a configuration file for an appliction during tiles development. You can define the layout / header / footer / body content for your View. <br /></font><font color="#0000ff">  Eg:<br /></font><font color="#0000ff">&lt;tiles-definitions&gt;<br />   &lt;definition name="siteLayoutDef" path="/layout/thbiSiteLayout.jsp"&gt;<br />      &lt;put name="title" value="Title of the page" /&gt;<br />      &lt;put name="header" value="/include/thbiheader.jsp" /&gt;<br />      &lt;put name="footer" value="/include/thbifooter.jsp" /&gt;<br />      &lt;put name="content" type="string"&gt;<br />      Content goes here<br />   &lt;/put&gt;<br />  &lt;/definition&gt;<br />&lt;/tiles-definitions&gt;</font></font></strong></o:p></font>
		</p>
		<p>
				<font color="#0000ff">&lt;tiles-definitions&gt;<br />&lt;definition name="userlogin" extends="siteLayoutDef"&gt;<br />&lt;put name="content" value="/dir/login.jsp" /&gt;<br />&lt;/definition&gt;<br />&lt;/tiles-definitions&gt;</font>
		</p>
		<p>
				<font color="#0000ff">2. validation.xml<br /></font>
				<font color="#0000ff">The validation.xml file is used to declare sets of validations that should be applied to Form Beans.<br /></font>
				<font color="#0000ff">Each Form Bean you want to validate has its own definition in this file. Inside that definition, you specify the validations you want to apply to the Form Bean's fields. </font>
				<font color="#0000ff">Eg:</font>
		</p>
		<p>
				<font color="#0000ff">&lt;form-validation&gt;<br />&lt;formset&gt;<br />&lt;form name="logonForm"&gt;<br />&lt;field property="username"<br />depends="required"&gt;<br />&lt;arg0 key=" prompt.username"/&gt;<br />&lt;/field&gt;<br />&lt;field property="password"<br />depends="required"&gt;<br />&lt;arg0 key="prompt.password"/&gt;<br />&lt;/field&gt;<br />&lt;/form&gt;<br />&lt;/formset&gt;<br />&lt;/form-validation&gt;</font>
		</p>
		<p>
				<font color="#0000ff">3. Resourcebundle.properties</font>
		</p>
		<p>
				<font color="#0000ff">Instead of having hard-coded error messages in the framework, Struts Validator allows you to specify a key to a message in the ApplicationResources.properties (or resourcebundle.properties) file that should be returned if a validation fails. </font>
				<font color="#0000ff">Eg:</font>
		</p>
		<p>
				<font color="#0000ff">In ApplicationResources.properties<br /></font>
				<font color="#0000ff">errors.registrationForm.name={0} Is an invalid name.<br /></font>
				<font color="#0000ff">In the registrationForm.jsp <br /></font>
				<font color="#0000ff">&lt;html:messages id="messages" property="name"&gt;<br />&lt;font color="red"&gt;<br />&lt;bean:write name="messages" /&gt;<br />&lt;/html:messages&gt;</font>
		</p>
		<p>
				<font color="#0000ff">Output(in red color) : abc Is an invalid name</font>
		</p>
		<p>
				<font color="#0000ff">=================</font>
		</p>
		<p class="MsoNormal">
				<font color="#0000ff">1. Purpose of tiles-def.xml file is used to in the design face of the webpage. For example in the webpage "top or bottom or left is<br />fixed" center might be dynamically chaged.<br />It is used for the easy design of the web sites. Reusability</font>
		</p>
		<p>
				<font color="#0000ff">2. resourcebundle.properties file is used for lot of purpose. One of its purpose is internationalization. We can make our page to view on any language. It is independent of it. Just based on the browser setting it selects the language and it displayed as you mentioned in the resourcebundle.properties file.</font>
		</p>
		<p>
				<font color="#0000ff">3. Validation rule.xml is used to put all the validation of the front-end in the validationrule.xml. So it verifies. If the same rule is applied in more than one page. No need to write the code once again in each page. Use validation to chek the errors in forms.</font>
		</p>
		<p>
				<font color="#0000ff">============================</font>
		</p>
		<p>
				<font color="#0000ff">tiles-def.xml - is required if your application incorporates the tiles framework in the "View" part of MVC. Generally we used to have a traditional JSP's (Which contgains HTML &amp; java scriplets) are used in view. But Tiles is an advanced (mode or less ) implementation of frames used in HTML. We used to define the frames in HTML to seperate the header html, footer html, menu or left tree and body.html to reuse the contents. Hence in the same way, Tiles are defined to reuse the jsp's in struts like architectures, and we can define the jsp's which all are to be display at runtime, by providing the jsp names at runtime. To incorporate this we need tile-def.xml and the Class generally which extends RequestProcessor should extend TilesRequestProcessor.</font>
		</p>
		<p>
				<font color="#0000ff">resourcebundle.properties — It is to incorporate i18n (internationalization) in View part of MVC.</font>
		</p>
		<p>
				<font color="#0000ff">validation.xml - This file is responsible for business validations carried at server side before processing the request actually. It reduces the complexity in writing _JavaScript validations, and in this way, we can hide the validations from the user, in View of MVC.</font>
		</p>
		<p class="MsoNormal">
				<b>
						<font color="#0000ff">
								<font color="#ff1493">Question: </font>What we will define in Struts-config.xml file. And explain their purpose?<br /></font>
				</b>
				<font color="#0000ff">In struts-config.xml we define Date Sources / Form Beans / Global Exceptions / Global Forwards / Action Mappings / Message Resources / Plug-ins</font>
		</p>
		<p>
				<font color="#0000ff">Example :</font>
		</p>
		<p>
				<font color="#0000ff">&lt;!– Date Sources –&gt;<br />&lt;data-sources&gt;<br />&lt;data-source autoCommit="false" description="First Database Config" driverClass=" org.gjt.mm.mysql.Driver" maxCount="4" minCount="2" password="admin" url="jdbc: mysql://localhost/ARTICLEDB" user="admin"&gt;<br />&lt;/&lt;data-sources&gt;<br />&lt;!– Form Beans –&gt;<br />&lt;form-beans&gt;<br />&lt;form-bean name="registrationForm" type="com.aaa.merchant.wsp.ActionForms.RegistrationForm"&gt;<br />&lt;/form-bean&gt;</font>
		</p>
		<p>
				<font color="#0000ff">&lt;!– Global Exceptions –&gt;<br />&lt;global-exceptions&gt;<br />&lt;exception key="some.key" type="java.io.IOException" handler="com.yourcorp.ExceptionHandler"/&gt;</font>
		</p>
		<p>
				<font color="#0000ff">&lt;/global-exceptions&gt;</font>
		</p>
		<p>
				<font color="#0000ff">&lt;!– A global-forward is retrieved by the ActionMapping findForward method. When the findForward method can't find a locally defined forward with the specified name, it searches the global-forwards available and return the one it finds.–&gt;<br />&lt;global-forwards&gt;<br />&lt;forward name="logoff" path="/logoff"/&gt;<br />&lt;forward name="logon" path="/logon.jsp"/&gt;<br />&lt;/global-forwards&gt;</font>
		</p>
		<p>
				<font color="#0000ff">&lt;!– Actionn Mappings –&gt;<br />&lt;action-mappings&gt;<br />&lt;action path="/validateRegistration" type="com.dd.merchant.wsp.Actions.ValidateRegistration" validate="true" input="" name="registrationForm"&gt;<br />&lt;forward name="success" path="/logon.jsp"&gt;<br />&lt;/forward&gt;<br />&lt;/action&gt;<br />&lt;/action-mappings&gt;</font>
		</p>
		<p>
				<font color="#0000ff">&lt;!– Message Resources –&gt;<br />&lt;message-resources parameter="wsppaymentsweb.resources.ApplicationResources"/&gt;</font>
		</p>
		<p>
				<font color="#0000ff">&lt;!– Plug-ins –&gt;<br />&lt;plug-in className="org.apache.struts.validator.ValidatorPlugIn"&gt;<br />&lt;set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/&gt;<br />&lt;/plug-in&gt;</font>
		</p>
		<p>
				<font color="#0000ff">===============================</font>
		</p>
		<p class="MsoNormal">
				<font color="#0000ff">Struts-Config.xml is one of the most important part of any web application based on Sturts. This file is responsible for instructing the Struts what forms are available, what actions are available, and also allows a number of plug-in models to be added to the base Struts package. It can contain Data Source Configuration,Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions, Message Resources Definitions etc.</font>
		</p>
		<p>
				<font color="#0000ff">The most important are Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions.</font>
		</p>
		<p>
				<font color="#0000ff">The &lt;form-bean/&gt; is configured using only two attributes, name and type and doesn't contain any body. The form-bean tag is used to describe an instance of a particular Form Bean that will be later bound to action.</font>
		</p>
		<p>
				<font color="#0000ff">The attribute name specifies the name of the form bean, which is a unique identifier to this form bean &amp; the attribute type specifies the absolute path of the class file.</font>
		</p>
		<p>
				<font color="#0000ff">&lt;global-forwards/&gt;: It is also configured using only two attributes, name and path and there is also an optional attribute redirect. The &lt;forward/&gt; specifies the mapping of a logical name to a context-relative URI path. In the above sample xml file we can see, one of the &lt;forward/&gt; is specified with the name as failure and its corresponding path as index.jsp. That means whenever the logical name failure is encountered the action will be forwarded to the index.jsp page.</font>
		</p>
		<p>
				<font color="#0000ff">The optional attribute redirect is set to false by default. When it is set to true it causes the ActionServlet to use HttpSevletResponse.sendRedirect() method.</font>
		</p>
		<p>
				<font color="#0000ff">&lt;action-mappings/&gt;: The action mapping mainly defines the mapping between the logical Action name and the physical action class. Now lets have an understanding about its attributes.</font>
		</p>
		<p>
				<font color="#0000ff">Â· The attribute path must be compulsorily defined and it should start with a '/' character. It specifies the context relative path of the submitted request.</font>
		</p>
		<p>
				<font color="#0000ff">Â· The type attribute specifies the absolute path of the fully qualified class name of the Action class.</font>
		</p>
		<p>
				<font color="#0000ff">Â· The attribute name must be the same as that of the form bean name for which you want to associate the action.</font>
		</p>
		<p>
				<font color="#0000ff">Â· The attribute scope specifies the scope of the particular form bean which is an optional one and its default value is session.</font>
		</p>
		<p>
				<font color="#0000ff">Â· The next attribute validate is also an optional one which by default is set to true. When set to true, the validate() method in the form bean is called which gets associated with a particular Action.</font>
		</p>
		<p>
				<font color="#0000ff">Â· The next attribute, input is also optional. Whenever a validation error is encountered then the control returns to the path specified in the input attribute.</font>
		</p>
		<p>
				<font color="#0000ff">&lt;controller/&gt;: The &lt;controller/&gt; can be used to modify the default behaviour of the Struts Controller i.e, we can define a RequestProcessor.</font>
		</p>
		<p>
				<font color="#0000ff">===============================<br />In struts-config.xml, we define all the global-forwards, action mappings, view mappings, form-bean mappings, controller mapping and finally message-resources declaration if any.<br />Why we need to declare means, the Controller servelet defined in struts internally looks for this xml file for its proceddings. In real scenario, that the controller servlet inplemented internally is nothing but a slave to this struts-config.xml. The information provided in this file is nothing but like the intelligence to the controller servlet to say - what to do in which situation ?<br />So, Controller servlet, needs this file to proceede/ run the application.</font>
		</p>
		<p class="MsoNormal">
				<b>
						<font color="#0000ff">What is DispatchAction?</font>
				</b>
		</p>
		<p class="MsoNormal">
				<font color="#0000ff">DispatchAction is specialized child of Struts Action class. It combines or group the methods that can further access the bussiness logic at a single place. The method can be anyone from CRUD [Create,Retrieve,Update or Delete] or it can be security check one like autheniticate user etc.<br />This class apart from having thread-safe execute method also can have user-defined methods.<br />In struts-config.xml files following changes are required for Dispatch action to work:</font>
		</p>
		<p>
				<font color="#0000ff">&lt;action-mappings&gt;<br />&lt;action path="/login"<br />type ="com…..LoginAction"<br />name ="loginForm"<br />parameter ="task"<br />scope = "request"<br />validate = "false"<br />input = "/index.jsp"&gt;<br />&lt;forward name="success" path="/jsp/common/index.jsp"/&gt;<br />&lt;forward name="loginagain" path="/index.jsp"/&gt;<br />&lt;/action&gt;<br />&lt;/action-mappings&gt;</font>
		</p>
		<p>
				<font color="#0000ff">If above is your struts-config.xml file structure and LoginAction extends DispatchAction instead of normal Action class. And assuming [keep assuming] your LoginAction class have method named authenticateUser, then in your login.jsp add any hidden parameter called task with value as your method name and on submit of that page following will be the url:</font>
		</p>
		<p>
				<font color="#0000ff">http://localhost:8080/yourproject/jsp/login.jsp?login.do&amp;task=authenticateUser</font>
		</p>
		<p>
				<font color="#0000ff">Thus if we try to combine the last part of this puzzle we get the climax at struts-config.xml file's action-mapping tag described above. The parameter property of &lt;action&gt; tag have the task as it's value pointing to task variable in the request having it's value as authenticateUser hence the framework search in the LoginAction a method called authenticateUser through reflection and forwards the execution flow to it. This is all folks, the briallancy of Struts framework. Note DispatchAction class is included in 1.1 version.</font>
		</p>
		<p class="MsoNormal">
				<font color="#0000ff">
				</font> </p>
		<p class="MsoNormal">
				<b>
						<font color="#0000ff">How to call ejb from Struts?</font>
				</b>
		</p>
		<p class="MsoNormal">
				<font color="#0000ff">
				</font> </p>
		<p class="MsoNormal">
				<font color="#0000ff">We can call EJB from struts by using the service locator design patteren or by Using initial context with create home object and getting return remote referenc object.</font>
		</p>
		<p class="MsoNormal">
				<b>
						<font color="#0000ff">What is the difference between ActionErrors and ActionMessages?</font>
				</b>
		</p>
		<p class="MsoNormal">
				<font color="#0000ff">There is no differnece between these two classes.All the behavior of ActionErrors was copied into ActionMessages and vice versa. This was done in the attempt to clearly signal that these classes can be used to pass any kind of messages from the controller to the view — where as errors being only one kind of message.</font>
		</p>
		<p>
				<font color="#0000ff">The difference between saveErrors(…) and saveMessages(…) is simply the attribute name under which the ActionMessages object is stored, providing two convenient default locations for storing controller messages for use by the view. If you look more closely at the html:errors and html:messages tags, you can actually use them to get an ActionMessages object from any arbitrary attribute name in any scope.</font>
		</p>
		<p class="MsoNormal">
				<font color="#0000ff">
				</font> </p>
		<p class="MsoNormal">
				<b>
						<font color="#0000ff">What are the various Struts tag libraries?</font>
				</b>
		</p>
		<p class="MsoNormal">
				<font color="#0000ff">The Struts distribution includes four tag libraries for the JSP framework (in struts-config.xml) :<br />* Bean tag library [ struts-bean.tld ] : Contains tags for accessing JavaBeans and their properties. Developers can also define new beans and set properties<br />* HTML tag library [ struts-html.tld ] : Contains tags to output standard HTML, including forms, textfields, checkboxes, radio buttons<br />* Logic tag library [ struts-logic.tld ] : Contains tags for generating conditional output, iteration capabilities and flow management<br />* Tiles or Template tag library [ struts-tiles.tld / struts-template.tld ] : For tiles implementation<br />* Nested tag library [ struts-nested.tld ] : allows the use of nested beans.</font>
		</p>
		<p>
				<font color="#0000ff">The libraries are designed to:</font>
		</p>
		<p>
				<font color="#0000ff">* Facilitate the separation of presentation and business logic.<br />* Dynamically generate Web pages.<br />* Implement the flow of control to and from the ActionServlet.</font>
		</p>
		<p class="MsoNormal">
				<b>
						<font color="#0000ff">How you will handle errors and exceptions using Struts?</font>
				</b>
		</p>
		<p class="MsoNormal">
				<font color="#0000ff">Struts exception handling can be done by two ways:<br />1. Declarative (using struts features via struts-config.xml)</font>
		</p>
		<p class="MsoNormal">
				<font color="#0000ff">&lt;global-exceptions&gt;<br />&lt;exception<br />type="hansen.playground.MyException2"<br />key ="errors.exception2"<br />path="/error.jsp"/&gt;<br />&lt;/global-exceptions&gt;</font>
		</p>
		<p>
				<font color="#0000ff">This makes coding in the Action class very simple<br />Since the execute method declares throws Exception we don't need a try-catch block.<br />Struts saves the exception using one of its global constants. You may use the field G lobals.EXCEPTION_KEY to retrieve it from the request object.</font>
		</p>
		<p>
				<font color="#0000ff">2. Programmatic (using the usual try-catch exception handling in Action Class)</font>
		</p>
		<p>
				<font color="#0000ff">===============</font>
		</p>
		<p class="MsoNormal">
				<font color="#0000ff">We can Handle the errors by holding them into ActionError or ActionErrors classes defined by struts Framework. The other way around is by using the methods say saveErrors()….etc defined in Action class and can throw the error messages.</font>
		</p>
		<p>
				<font color="#0000ff">=================</font>
		</p>
		<p>
				<font color="#0000ff">Struts handles errors by providing the ActionErrors class which is<br />extended from org.apache.struts.action…<br />To install your customized exception handler, the first step is to<br />create a class that extends org.apache.struts.action.ExceptionHandler. There are<br />two methods that you can override, execute() and storeException().<br />For handling exceptions you have to mention in &lt;global-exceptions&gt; tag<br />of struts-config.xml which accepts attributes like exception type,key and<br />path.</font>
		</p>
		<p class="MsoNormal">
				<b>
						<font color="#0000ff">How you will save the data across different pages for a particular client request using Struts?</font>
				</b>
		</p>
		<p class="MsoNormal">
				<font color="#0000ff">One simple and general way is by using session Object.</font>
		</p>
		<p>
				<font color="#0000ff">In specific, we can pass this by using request Object as well.</font>
		</p>
		<p>
				<font color="#0000ff">======================================<br />Create an appropriate instance of ActionForm that is form bean and store that form bean in session scope. So that it is available to all the pages that for a part of the request.</font>
		</p>
		<p>
				<font color="#0000ff">request.getSession()<br />session.setAttribute()</font>
		</p>
		<p class="MsoNormal">
				<b>
						<font color="#0000ff">What is Action Class? What are the methods in Action class?</font>
				</b>
		</p>
		<p class="MsoNormal">
				<font color="#0000ff">An Action class is some thing like an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.<br />The controller (RequestProcessor) will select an appropriate Action for each request, create an instance (if necessary), and call the execute method. Struts Action class is a unit of logic. It is where a call to business function is made. In short the Action class acts like a bridge between client side(user action) and business operation(on server.<br />Some of the impotant methods of Action class are, execute()<br />generateToken() resetToken() getServlet()</font>
		</p>
		<p class="MsoNormal">
				<b>
						<font color="#0000ff">Explain about token feature in Struts?</font>
				</b>
		</p>
		<p class="MsoNormal">
				<font color="#0000ff">
				</font> </p>
		<p class="MsoNormal">
				<font color="#0000ff">Use the Action Token methods to prevent duplicate submits:<br />There are methods built into the Struts action to generate one-use tokens. A token is placed in the session when a form is populated and also into the HTML form as a hidden property. When the form is returned, the token is validated. If validation fails, then the form has already been submitted, and the user can be apprised.<br /> saveToken(request)<br />on the return trip,<br /> isTokenValid(request)<br />resetToken(request)</font>
		</p>
		<p class="MsoNormal">
				<b>
						<font color="#0000ff">What is the difference between ActionForm and DynaActionForm</font>
				</b>
		</p>
		<p class="MsoNormal">
				<font color="#0000ff"># The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.</font>
		</p>
		<p>
				<font color="#0000ff"># The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.</font>
		</p>
		<p>
				<font color="#0000ff"># ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.</font>
		</p>
		<p>
				<font color="#0000ff"># ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter( .. ).</font>
		</p>
		<p>
				<font color="#0000ff"># DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.</font>
		</p>
		<p>
				<font color="#0000ff"># Time savings from DynaActionForm is insignificant. It doesn t take long for today s IDEs to generate getters and setters for the ActionForm attributes. (Let us say that you made a silly typo in accessing the DynaActionForm properties in the Action instance. It takes less time to generate the getters and setters in the IDE than fixing your Action code and redeploying your web application)</font>
		</p>
<img src ="http://www.blogjava.net/SunRiver/aggbug/85377.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/SunRiver/" target="_blank">Sun River</a> 2006-12-04 15:46 <a href="http://www.blogjava.net/SunRiver/archive/2006/12/04/85377.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>