欧美日韩亚洲精品一区二区三区,久久久久久999,久久这里精品http://www.aygfsteel.com/SunRiver/category/17339.htmlTopics about Java EE, XML,AJAX,SOA,OSGi,DB, .NET etc.zh-cnFri, 10 Aug 2007 16:34:05 GMTFri, 10 Aug 2007 16:34:05 GMT60POIhttp://www.aygfsteel.com/SunRiver/archive/2007/08/09/135443.htmlSun RiverSun RiverThu, 09 Aug 2007 04:37:00 GMThttp://www.aygfsteel.com/SunRiver/archive/2007/08/09/135443.html
群眾:笑死人了,這還要你教么,別丟人現(xiàn)眼了,用FileOutputStream就可以了,寫個文件,擴(kuò)展名為xls就可以了,哈哈,都懶得看你的,估計又是個水貨上來瞎喊,下去,喲貨~~

小筆:無聊的人一邊去,懶得教你,都沒試過,還雞叫雞叫,&^%&**(()&%$#$#@#@


    HSSFWorkbook wb = new HSSFWorkbook();//構(gòu)建新的XLS文檔對象
    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    wb.write(fileOut);//注意,參數(shù)是文件輸出流對象
    fileOut.close();



Example Two:創(chuàng)建Sheet

群眾:有點責(zé)任心好吧,什么是Sheet?欺負(fù)我們啊?

小筆:花300塊去參加Office 培訓(xùn)班去,我不負(fù)責(zé)教預(yù)科


   HSSFWorkbook wb = new HSSFWorkbook();//創(chuàng)建文檔對象
    HSSFSheet sheet1 = wb.createSheet("new sheet");//創(chuàng)建Sheet對象,參數(shù)為Sheet的標(biāo)題
    HSSFSheet sheet2 = wb.createSheet("second sheet");//同上,注意,同是wb對象,是一個XLS的兩個Sheet
    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    wb.write(fileOut);
    fileOut.close();


Example Three:創(chuàng)建小表格,并為之填上數(shù)據(jù)

群眾:什么是小表格啊?

小筆:你用過Excel嗎?人家E哥天天都穿的是網(wǎng)格襯衫~~~~


                  HSSFWorkbook document = new HSSFWorkbook();//創(chuàng)建XLS文檔

HSSFSheet salary = document.createSheet("薪水");//創(chuàng)建Sheet

HSSFRow titleRow = salary.createRow(0);//創(chuàng)建本Sheet的第一行



titleRow.createCell((short) 0).setCellValue("工號");//設(shè)置第一行第一列的值
titleRow.createCell((short) 1).setCellValue("薪水");//......
titleRow.createCell((short) 2).setCellValue("金額");//設(shè)置第一行第二列的值


File filePath = new File(baseDir+"excel/example/");

if(!filePath.exists())
filePath.mkdirs();

FileOutputStream fileSystem = new FileOutputStream(filePath.getAbsolutePath()+"/Three.xls");

document.write(fileSystem);

fileSystem.close();

 

Example Four :帶自定義樣式的數(shù)據(jù)(eg:Date)

群眾:Date!么搞錯,我昨天已經(jīng)插入成功了~

小筆:是么?那我如果要你5/7/06 4:23這樣輸出你咋搞?

群眾:無聊么?能寫進(jìn)去就行了!

小筆:一邊涼快去~


                  HSSFWorkbook document = new HSSFWorkbook();

HSSFSheet sheet = document.createSheet("日期格式");

HSSFRow row = sheet.createRow(0);


HSSFCell secondCell = row.createCell((short) 0);

/**
 * 創(chuàng)建表格樣式對象
 */
HSSFCellStyle style = document.createCellStyle();

/**
 * 定義數(shù)據(jù)顯示格式
 */
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));

/**
 * setter
 */
secondCell.setCellValue(new Date());

/**
 * 設(shè)置樣式
 */
secondCell.setCellStyle(style);



File filePath = new File(baseDir+"excel/example/");

if(!filePath.exists())
filePath.mkdirs();

FileOutputStream fileSystem = new FileOutputStream(filePath.getAbsolutePath()+"/Four.xls");

document.write(fileSystem);

fileSystem.close();

Example Five:讀取XLS文檔


File filePath = new File(baseDir+"excel/example/");

if(!filePath.exists())
throw new Exception("沒有該文件");
/**
 * 創(chuàng)建對XLS進(jìn)行讀取的流對象
 */
POIFSFileSystem reader = new POIFSFileSystem(new FileInputStream(filePath.getAbsolutePath()+"/Three.xls"));
/**
 * 從流對象中分離出文檔對象
 */
HSSFWorkbook document = new HSSFWorkbook(reader);
/**
 * 通過文檔對象獲取Sheet
 */
HSSFSheet sheet = document.getSheetAt(0);
/**
 * 通過Sheet獲取指定行對象
 */
HSSFRow row = sheet.getRow(0);
/**
 * 通過行、列定位Cell
 */
HSSFCell cell = row.getCell((short) 0);

/**
 * 輸出表格數(shù)據(jù)
 */
log.info(cell.getStringCellValue());


至此,使用POI操作Excel的介紹告一段落,POI是一個仍然在不斷改善的項目,有很多問題,比如說中文問題,大數(shù)據(jù)量內(nèi)存溢出問題等等,但這個Pure Java的庫的性能仍然是不容質(zhì)疑的,是居家旅行必備良品。

而且開源軟件有那么一大點好處是,可以根據(jù)自己的需要自己去定制。如果大家有中文、性能等問題沒解決的,可以跟我索要我已經(jīng)改好的庫。當(dāng)然,你要自己看原代碼,我也不攔你。




Sun River 2007-08-09 12:37 發(fā)表評論
]]>
Java, POI and Excel http://www.aygfsteel.com/SunRiver/archive/2007/08/09/135436.htmlSun RiverSun RiverThu, 09 Aug 2007 04:26:00 GMThttp://www.aygfsteel.com/SunRiver/archive/2007/08/09/135436.html閱讀全文

Sun River 2007-08-09 12:26 發(fā)表評論
]]>
Recipe http://www.aygfsteel.com/SunRiver/archive/2007/08/07/135030.htmlSun RiverSun RiverTue, 07 Aug 2007 10:28:00 GMThttp://www.aygfsteel.com/SunRiver/archive/2007/08/07/135030.htmlPopulating Value Objects from ActionForms

Problem

You don't want to have to write numerous getters and setters to pass data from your action forms to your business objects.

Solution

Use the introspection utilities provided by the Jakarta Commons BeanUtils package in your Action.execute( ) method:

import org.apache.commons.beanutils.*;
// other imports omitted
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
BusinessBean businessBean = new BusinessBean( );
BeanUtils.copyProperties(businessBean, form);
// ... rest of the Action

Discussion

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.

Data sent in the HTTP request is represented as simple text. For some data types, the value can be represented as a String 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 String. Then it must be converted to a java.util.Date in the model. Furthermore, when the value is persisted, it's usually transformed again, this time to a java.sql.Timestamp. Numeric fields require similar transformations.

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 employeeId. In all classes that contain an employee ID, you should use that name. Using empId in one class and employeeIdentifier in another will only lead to confusion among your developers and will render the BeanUtils facilities useless.

The entire conversion and copying of properties from ActionForm to business object can be performed with one static method call:

BeanUtils.copyProperties(
businessBean
, 
form
);

This copyProperties( ) method attempts to copy each JavaBean property in form to the property with the same name in businessBean. If a property in form doesn't have a matching property in businessBean, 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 Strings to the following types:

  • java.lang.BigDecimal

  • java.lang.BigInteger

  • boolean and java.lang.Boolean

  • byte and java.lang.Byte

  • char and java.lang.Character

  • java.lang.Class

  • double and java.lang.Double

  • float and java.lang.Float

  • int and java.lang.Integer

  • long and java.lang.Long

  • short and java.lang.Short

  • java.lang.String

  • java.sql.Date

  • java.sql.Time

  • java.sql.Timestamp

While the conversions to character-based and numeric types should cover most of your needs, date type fields (as shown in Recipe 3-13) 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. java.util.Date) to a String and back again.

Because BeanUtils knows how to handle DynaBeans and the DynaActionForm implements DynaBean, the Solution will work unchanged for DynaActionForms and normal ActionForms.


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. Example 5-9 shows the Employee business object. Most of the methods of this class are getters and setters; for the hireDate property, however, helper methods are provided that get and set the value from a String.

Example 5-9. Employee business object
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");
}

Example 5-10 shows the corresponding ActionForm that will retrieve the data from the HTML form. The hire date is represented in the ActionForm as a String property, hireDateDisplay. The salary property is a java.lang.String, not a java.math.BigDecimal, as in the Employee object of Example 5-9.

Example 5-10. Employee ActionForm
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;
}
}

If you wanted to use a DynaActionForm, you would configure it identically as the EmployeeForm class. The form-bean declarations from the struts-config.xml file show the declarations for the EmployeeForm and a functionally identical DynaActionForm:

<form-bean name="EmployeeForm"
type="com.oreilly.strutsckbk.ch05.EmployeeForm"/>
<form-bean name="EmployeeDynaForm"
type="org.apache.struts.action.DynaActionForm">
<form-property name="employeeId" type="java.lang.String"/>
<form-property name="firstName" type="java.lang.String"/>
<form-property name="lastName" type="java.lang.String"/>
<form-property name="salary" type="java.lang.String"/>
<form-property name="married" type="java.lang.Boolean"/>
<form-property name="hireDateDisplay" type="java.lang.String"/>
</form-bean>

The following is the action mapping that processes the form. In this case, the name attribute refers to the handcoded EmployeeForm. You could, however, change this to use the EmployeeDynaForm without requiring any modifications to the SaveEmployeeAction or the view_emp.jsp JSP page:

<action    path="/SaveEmployee"
name="EmployeeForm"
scope="request"
type="com.oreilly.strutsckbk.ch05.SaveEmployeeAction">
<forward name="success" path="/view_emp.jsp"/>
</action>

The data is converted and copied from the form to the business object in the SaveEmployeeAction shown in Example 5-11.

Example 5-11. Action to save employee data
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");
}
}

Finally, two JSP pages complete the example. The JSP of Example 5-12 (edit_emp.jsp) renders the HTML form to retrieve the data.

Example 5-12. Form for editing employee data
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix=
"bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix=
"html" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head>
<title>Struts Cookbook - Chapter 5 : Add Employee</title>
</head>
<body>
<h2>Edit Employee</h2>
<html:form action="/SaveEmployee">
Employee ID: <html:text property="employeeId"/><br />
First Name: <html:text property="firstName"/><br />
Last Name: <html:text property="lastName"/><br />
Married? <html:checkbox property="married"/><br />
Hired on Date: <html:text property="hireDateDisplay"/><br />
Salary: <html:text property="salary"/><br />
<html:submit/>
</html:form>
</body>
</html>

The JSP in Example 5-13 (view_emp.jsp) displays the results. This page is rendering data from the business object, and not an ActionForm. This is acceptable since the data on this page is for display purposes only. This approach allows for the formatting of data, (salary and hireDate) to be different than the format in which the values were entered.

Example 5-13. View of submitted employee data
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix=
"bean" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head>
<title>Struts Cookbook - Chapter 5 : View Employee</title>
</head>
<body>
<h2>View Employee</h2>
Employee ID: <bean:write name="employee" property="employeeId"/><br />
First Name: <bean:write name="employee" property="firstName"/><br />
Last Name: <bean:write name="employee" property="lastName"/><br />
Married? <bean:write name="employee" property="married"/><br />
Hired on Date: <bean:write name="employee" property="hireDate"
format="MMMMM dd, yyyy"/><br />
Salary: <bean:write name="employee" property="salary" format="$##0.00"/
><br />
</body>
</html>

When you work with this example, swap out the handcoded form for the DyanActionForm 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 DynaActionForms becomes obvious.



Sun River 2007-08-07 18:28 發(fā)表評論
]]>
2006-12-03: Questions about Strutshttp://www.aygfsteel.com/SunRiver/archive/2006/12/04/85377.htmlSun RiverSun RiverMon, 04 Dec 2006 07:46:00 GMThttp://www.aygfsteel.com/SunRiver/archive/2006/12/04/85377.html Question: How you will handle exceptions in Struts?
Answer: In Struts you can handle the exceptions in two ways:
a) Declarative Exception Handling: You can either define global exception handling tags in your struts-config.xml or define the exception handling tags within <action>..</action> tag.
Example:

<exception?
??????key="database.error.duplicate"?
????? path="/UserExists.jsp"?
????? type="mybank.account.DuplicateUserException"/>
b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception.
Question:Explain Struts navigation flow?
Struts Navigation flow.
1) A request is made from previously displayed view.
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.
3)The Action Class performs its logic on the Model Components associated with the Application.
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.
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.
Question: What is the purpose of tiles-def.xml file, resourcebundle.properties file, validation.xml file?
1. tiles-def.xml
? 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.
? Eg:
<tiles-definitions>
?? <definition name="siteLayoutDef" path="/layout/thbiSiteLayout.jsp">
????? <put name="title" value="Title of the page" />
????? <put name="header" value="/include/thbiheader.jsp" />
????? <put name="footer" value="/include/thbifooter.jsp" />
????? <put name="content" type="string">
????? Content goes here
?? </put>
? </definition>
</tiles-definitions>

<tiles-definitions>
<definition name="userlogin" extends="siteLayoutDef">
<put name="content" value="/dir/login.jsp" />
</definition>
</tiles-definitions>

2. validation.xml
The validation.xml file is used to declare sets of validations that should be applied to Form Beans.
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. Eg:

<form-validation>
<formset>
<form name="logonForm">
<field property="username"
depends="required">
<arg0 key=" prompt.username"/>
</field>
<field property="password"
depends="required">
<arg0 key="prompt.password"/>
</field>
</form>
</formset>
</form-validation>

3. Resourcebundle.properties

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. Eg:

In ApplicationResources.properties
errors.registrationForm.name={0} Is an invalid name.
In the registrationForm.jsp
<html:messages id="messages" property="name">
<font color="red">
<bean:write name="messages" />
</html:messages>

Output(in red color) : abc Is an invalid name

=================

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
fixed" center might be dynamically chaged.
It is used for the easy design of the web sites. Reusability

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.

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.

============================

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 & 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.

resourcebundle.properties — It is to incorporate i18n (internationalization) in View part of MVC.

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.

Question: What we will define in Struts-config.xml file. And explain their purpose?
In struts-config.xml we define Date Sources / Form Beans / Global Exceptions / Global Forwards / Action Mappings / Message Resources / Plug-ins

Example :

<!– Date Sources –>
<data-sources>
<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">
</<data-sources>
<!– Form Beans –>
<form-beans>
<form-bean name="registrationForm" type="com.aaa.merchant.wsp.ActionForms.RegistrationForm">
</form-bean>

<!– Global Exceptions –>
<global-exceptions>
<exception key="some.key" type="java.io.IOException" handler="com.yourcorp.ExceptionHandler"/>

</global-exceptions>

<!– 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.–>
<global-forwards>
<forward name="logoff" path="/logoff"/>
<forward name="logon" path="/logon.jsp"/>
</global-forwards>

<!– Actionn Mappings –>
<action-mappings>
<action path="/validateRegistration" type="com.dd.merchant.wsp.Actions.ValidateRegistration" validate="true" input="" name="registrationForm">
<forward name="success" path="/logon.jsp">
</forward>
</action>
</action-mappings>

<!– Message Resources –>
<message-resources parameter="wsppaymentsweb.resources.ApplicationResources"/>

<!– Plug-ins –>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>

===============================

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.

The most important are Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions.

The <form-bean/> 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.

The attribute name specifies the name of the form bean, which is a unique identifier to this form bean & the attribute type specifies the absolute path of the class file.

<global-forwards/>: It is also configured using only two attributes, name and path and there is also an optional attribute redirect. The <forward/> 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 <forward/> 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.

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.

<action-mappings/>: 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.

?· The attribute path must be compulsorily defined and it should start with a '/' character. It specifies the context relative path of the submitted request.

?· The type attribute specifies the absolute path of the fully qualified class name of the Action class.

?· The attribute name must be the same as that of the form bean name for which you want to associate the action.

?· The attribute scope specifies the scope of the particular form bean which is an optional one and its default value is session.

?· 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.

?· 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.

<controller/>: The <controller/> can be used to modify the default behaviour of the Struts Controller i.e, we can define a RequestProcessor.

===============================
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.
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 ?
So, Controller servlet, needs this file to proceede/ run the application.

What is DispatchAction?

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.
This class apart from having thread-safe execute method also can have user-defined methods.
In struts-config.xml files following changes are required for Dispatch action to work:

<action-mappings>
<action path="/login"
type ="com…..LoginAction"
name ="loginForm"
parameter ="task"
scope = "request"
validate = "false"
input = "/index.jsp">
<forward name="success" path="/jsp/common/index.jsp"/>
<forward name="loginagain" path="/index.jsp"/>
</action>
</action-mappings>

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:

http://localhost:8080/yourproject/jsp/login.jsp?login.do&task=authenticateUser

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 <action> 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.

?

How to call ejb from Struts?

?

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.

What is the difference between ActionErrors and ActionMessages?

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.

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.

?

What are the various Struts tag libraries?

The Struts distribution includes four tag libraries for the JSP framework (in struts-config.xml) :
* Bean tag library [ struts-bean.tld ] : Contains tags for accessing JavaBeans and their properties. Developers can also define new beans and set properties
* HTML tag library [ struts-html.tld ] : Contains tags to output standard HTML, including forms, textfields, checkboxes, radio buttons
* Logic tag library [ struts-logic.tld ] : Contains tags for generating conditional output, iteration capabilities and flow management
* Tiles or Template tag library [ struts-tiles.tld / struts-template.tld ] : For tiles implementation
* Nested tag library [ struts-nested.tld ] : allows the use of nested beans.

The libraries are designed to:

* Facilitate the separation of presentation and business logic.
* Dynamically generate Web pages.
* Implement the flow of control to and from the ActionServlet.

How you will handle errors and exceptions using Struts?

Struts exception handling can be done by two ways:
1. Declarative (using struts features via struts-config.xml)

<global-exceptions>
<exception
type="hansen.playground.MyException2"
key ="errors.exception2"
path="/error.jsp"/>
</global-exceptions>

This makes coding in the Action class very simple
Since the execute method declares throws Exception we don't need a try-catch block.
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.

2. Programmatic (using the usual try-catch exception handling in Action Class)

===============

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.

=================

Struts handles errors by providing the ActionErrors class which is
extended from org.apache.struts.action…
To install your customized exception handler, the first step is to
create a class that extends org.apache.struts.action.ExceptionHandler. There are
two methods that you can override, execute() and storeException().
For handling exceptions you have to mention in <global-exceptions> tag
of struts-config.xml which accepts attributes like exception type,key and
path.

How you will save the data across different pages for a particular client request using Struts?

One simple and general way is by using session Object.

In specific, we can pass this by using request Object as well.

======================================
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.

request.getSession()
session.setAttribute()

What is Action Class? What are the methods in Action class?

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.
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.
Some of the impotant methods of Action class are, execute()
generateToken() resetToken() getServlet()

Explain about token feature in Struts?

?

Use the Action Token methods to prevent duplicate submits:
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.
?saveToken(request)
on the return trip,
?isTokenValid(request)
resetToken(request)

What is the difference between ActionForm and DynaActionForm

# The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.

# 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.

# ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.

# 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( .. ).

# DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.

# 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)



Sun River 2006-12-04 15:46 發(fā)表評論
]]>
主站蜘蛛池模板: 深圳市| 紫金县| 保山市| 平邑县| 屏东县| 政和县| 孝昌县| 樟树市| 邵武市| 松阳县| 唐山市| 新绛县| 石嘴山市| 治多县| 建瓯市| 镇赉县| 新疆| 禹州市| 台安县| 宾阳县| 西乌珠穆沁旗| 台州市| 永善县| 手游| 大悟县| 广元市| 张家川| 云霄县| 沅江市| 怀化市| 冕宁县| 乐昌市| 西昌市| 沂水县| 东山县| 无极县| 正安县| 汶上县| 西贡区| 宝兴县| 泗阳县|