Struts Development Tips

Source: Internet
Author: User
Skill Struts Development Tips
Has experienced the "China Telecom Customer Intimate Service" project development and is currently under development of the "China Telecom Headquarters Business Analysis" project, Accumulated a number of Struts1.1 and tiles development of some of the techniques and techniques, close-up, easy to develop later, but also believe that the reader in the development of struts to provide some help
Module configuration
1. Struts configuration file definition
For a module in the system, the configuration of the module needs to be defined before development, and the configuration file for that struts is named:
Struts-config-xxx.xml
XXX is the lowercase English name or abbreviation for the module, such as: Struts-config-sysman.xml
Note: The middle is "-" instead of "_" connector
Unified save in the "Web-infxml" folder and need to add the appropriate configuration file in Web.xml
Address, as specified in the following example:
...
<init-param>
<param-name>config</param-name>
<param-value>/web-inf/struts-config.xml,/web-inf/xml/struts-config-pages.xml,/web-inf/xml/ Struts-config-sysman.xml</param-value>
</init-param>
...
Note: You need to use the "," connector to separate the individual profile names
In addition, all static JSPs need to define their ". Do" access through the configuration file, saved in the
In the Struts-config-pages.xml file, the following example reads:
...
<!--homepage Steering-->
<action path= "/main" type= "org.apache.struts.actions.ForwardAction" parameter= "/main.jsp"/>
...
2. Tiles configuration file definition
The framework configuration file for the system is Tiles-defs_zh_cn.xml (supports internationalized applications through the. Properties property file, default is Tiles-defs.xml), and the framework structure of the module needs to be defined in the following example:
...
<!--define default home-->
<definition name= "Default.frame" path= "/layouts/defaultlayout.jsp" >
<put name= "title" value= "Welcome to enter the telecom Business Analysis system"/>
<put name= "header" value= "/top.jsp"/>
<put name= "Body" value= "Default.body"/>
<put name= "Footer" value= "/buttom.jsp"/>
</definition>
<!--define the default home-->
<definition name= "Default.body" path= "/layouts/main.jsp" >
<put name= "logon" value= "/logon.jsp"/>
<put name= "Date" value= "/layouts/date.jsp"/>
<put name= "Linksite" value= "/layouts/link.html"/>
</definition>
...
Framework naming conventions by "System (subsystem). Function module. Page module", as Above "Default.frame"
The page action of the settings in the Struts-config-pages.xml file can be written like this:
<action path= "/main" type= "org.apache.struts.actions.ForwardAction" parameter= "Default.frame"/>
This eliminates the need to write a separate Tiles:insert page, as follows:
<tiles:insert definition= "Vip.warn.day" flush= "true"/>
3. Comments in the module
Not only do you need to add the necessary annotations to your program, you also need to add annotations when you define the configuration file, mainly in Struts-config-xxx.xml and Tiles-defs_zh_ Cn.xml add comments to these files, explain the function of the action or configuration module, and put it in front of the configuration item, see the configuration file above
4. For configuration file editing
You can't use XML editing in JBuilder because JB automatically changes the encoding and content in XML, so editing XML configuration files uses editing software, such as UE
Event definition
The classes for events are mainly action, Actionform, and the ". Do" definitions submitted in the JSP, as well as the submission of page actions, with login login as an example:
1. The naming definition for the class (uppercase should be the first letter)
In the form of "Action name +action/form"
such as: Loginaction.class, Loginform.class
2. Page address definition (first letter should be lowercase)
If there are more than two words, the first letter of the second word is capitalized, and so on
In the form of "action name"
such as: Login.do or Loginsys.do
JSP file naming also follows this specification
3. Page Action Definition
Because the form in the JSP page corresponds to Actionform, which has its own action this attribute, so the page action if defined also as action, will cause unnecessary trouble, so, the page action is defined as "act",
If you need to edit a record, the address is as follows:
"/editrecord.do?act= Edit"
If deletion is required, the address is as follows:
"/editrecord.do?act=delete"
4. Control mechanisms for menu and action event triggers
Because the menus and actions in the system are requested by the ". Do" form to the service, a mechanism is needed to control which requests are made to the menu and which are the event requests;
We introduce filter filter in the system, control all requests, and judge whether the user is logged in and have access to resources (menu, etc.);
Conventions:
JSP page for the system in the menu requests are "Get" method, for the action is "POST" method;
With such a convention, in the filter first Judge request method, if it is "get" method, it is considered a request to the menu, so go to "menu table" according to the request address read the corresponding records, and read the user's permission table, judge the user's menu permissions;
If it is a "POST" method, it is considered to be an operation request, and the "Act" action in request is extracted to determine the user's permission point.

Parameter Information acquisition
1. Public parameter information can be invoked in any JSP that requires the variable, by plugin the variable into the application when the Web service is started.
In the following ways:
public void Setservletcontext (Actionservlet actionservlet) {
try {
ServletContext sc = Actionservlet.getservletcontext ();
Sysinitpwd
Sc.setattribute (Constants.sys_init_pwd,selectlists.getsysconfig ("Pwdinit"));
...
How to invoke in programs such as action:
Getservlet (). Getservletcontext (). getattribute ("...");

2. For the data to be displayed on the page as much as possible in the scope of request, you can reduce the server-side memory load, in the following ways:
Call Employee Handling class
Staffdeal sd=new staffdeal ();
Query employees based on employee status
ArrayList Al=sd.qrystaff (strstate);
Put in Request
Request.setattribute ("Staffinfo", AL);
3. Private or need to obtain parameter information according to user's attribute, can be obtained by using "controlclass=xxx" in the definition of tiles, configure the following example:
<definition name= "Vip.welcome" path= "/vip/welcome.jsp" controllerclass= "Viptx.logic.vip.welcomeAction"/>
You need to implements the Perform method in controller, code as follows:
public void Perform (Componentcontext componentcontext,
HttpServletRequest request,
HttpServletResponse response,
ServletContext ServletContext) throws Ioexception,servletexception {
HttpSession session = Request.getsession ();
Get the session.
User user = (user) Session.getattribute (constants.user_key);
if (user = null) {
return null;
}
String uid = User.getuserid ();
String sql = "Select Userid,content from Ti_salutatory where Userid=´" +uid+ "´";
try {
...
}
catch (Exception ex) {
throw new Servletexception (Ex.getmessage ());
}
}
4. Tips for background error information on the front page
First configure "message.common={0}" in Properties
Then, when you use Actionerrors or actionmessages in the action class, the method is as follows:
...
Actionmessages ams = new Actionmessages (); Exception handling
try{
...
}
catch (Exception ex) {
Ex.printstacktrace ();
Ams.add (Actionmessages.global_message,
New Actionmessage ("Message.common", Ex.getmessage ()));
}
finally {
if (!ams.isempty ()) {
Savemessages (Request, AMS);
}
}
...
Use the following methods in the JSP page:
<font color= "Red" ><bean:write name= "MSG"/></font>

If have backstage messages produce, the front page can appear the error message
5. System Configuration File
System parameters, such as database connections, are configured in the Sysconfi.xml file and stored in the "Web-inf/xml" folder, see the file.
Development specifications and Common methods
Development specification for Java See the Java programming specification. doc, which gives only some of the specifications used in the development of struts:
1. java file storage is divided by business logic and module as package name, such as: telecombi.logic.sysman.security
Package names are lowercase
All action and actionform are stored under the same package for ease of management and do not call across packages
2. All Actionform properties are "first word lowercase + second word first letter capital + ..." form, such as: StaffID, staffname, not allowed to use "_" for the word connector
3. Need to verify the page, all need the client and service end two times authentication (that is, JSP in the form of JavaScript validation and action in the Excute method to verify), can not only use one of the methods to prevent customers to bypass JS direct submission;
You must use staticjavascript= "false" when verifying the form that you are submitting to a login, or you will write JavaScript to the page, such as:

Dynamicjavascript= "true"
Staticjavascript= "false"/>
<script language= "Javascript1.1" src= "staticjavascript.jsp" ></script>
The validated formname must correspond to the name of the form in Validation.xml, otherwise the validation is invalid
4. Actionform represents the form in HTML, where the variables need to correspond to the attributes in the form, such as: To use <form:text property= "UserName"/&gt in the JSP; You must have username this variable in the actionform you use.
5. For the logic in action, if the processing method in more than one, you need to create a new processing class, responsible for the action in the logical centralized processing, named Xxxdeal, such as: logindeal;
Action implements business logic processing by calling the method of the handler class
6. The operation of the database uses the Dbmanager class, and some of these methods are described in detail as follows:
 Query result-Object Select operation, using the Select (String sql,string className) method
StringBuffer sql = new StringBuffer (
"Select staff_id StaffID from Ts_m_staff")
. Append ("where Staff_id=´"). Append (UID). Append ("´");
try {
/**
* User is an object class, which has staffid this attribute, and the corresponding Get/set method, by
* Dbmanager Select method to get a ArrayList collection of user
*/
ArrayList rs = Dbmanager.select (Sql.tostring (), User.class.getName ());
/**
* If you are sure that only one object is returned, you can use the
*
*/
User user= (user) Rs.get (0);
}
catch (Exception ex) {
throw new Servletexception (Ex.getmessage ());
}
The extracted data can be stored in the session or page, etc. for JSP page calls, the method is Session.setattribute ("user", User1)
...
Operations such as insert or update
Using the ExecuteSQL (String sql) method inside Dbmanager, if it is batch processing, use the Executebatchsql (string[] sqls) method to return the success flag to Constants.operate_ SUCCESS
The failure flag is constants.operate_failed
No further information to return
The transformation of the resultset object to the Hashtable collection object using the Select (String sql) method:
In addition to using the Dbmanager Select to convert query results to objects, you can also use the previous way of using the ResultSet object directly, although the DataSet object returned here is Hashtable;
The data structures stored by Hashtable are:
ColumnName1? ArrayList1 (Result set for this field)
ColumnName2? ArrayList2 (Result set for this field)
...
A lot of the methods used in the system are used to generate the dropdown data, take the Hashtable from the Select method to the field value, and generate Labelvaluebean, as follows:
/** common function Hashtable into ArrayList (labelvaluebean) * *
private static ArrayList Hashtolvb (Hashtable HT, string ID, string Name,boolean hasblank) {
if (ht!=null) {
ArrayList al = new ArrayList ();
ArrayList alid = (ArrayList) ht.get (Id.touppercase ());
ArrayList alname = (ArrayList) ht.get (Name.touppercase ());
int ilen = Alid.size ();
if (Hasblank)
Al.add (New Labelvaluebean ("Unknown", "1"));
for (int i = 0; i < Ilen; i++) {
Al.add (New Labelvaluebean (String) alname.get (i),
(String) Alid.get (i));
}
Return al;
}
else{
return null;
}
}
autosetform (String sql, Object frm) method Introduction:
A The method can return an object that has been assigned to a property after querying the database, using the following method:
User User=dbmanager. Autosetform (Sql,new User ());
SQL is a query statement
B This method can also be assigned to the form after the page operation, such as the submission of a page on a record to edit the operation, when the action gets the ID number of the record and query the database success, you need to set the details of the Actionform to the property variables, This is the time to use this method as follows:
Form= Dbmanager. Autosetform (Sql,form);
The actionform that is passed in the Excute method of form action

7. Call the stored procedure
Using the Execproc (String procname,arraylist procprts) method in Dbmanager
ProcName is the stored procedure name, Procprts is the set of entry parameters for the stored procedure, and returns the Procouts object, which has result and exceptioninfo two properties, indicating the processing token and exception information returned (if any)
8. Processing of data operation return information
After the operation of the data, you need to return the success of the operation, and other information, the following steps:
 Use the "Messages.comm" key in the property file to add specific return information to the key
 Use the "Actionmessages" object in the program, the Java program is as follows:
Actionmessages ams = new Actionmessages ();
...
Execution results
Procouts Presult=null;
Whether the call succeeds
if (presult.getresult () = =-1) {
Ams.add (Actionmessages.global_message,
New Actionmessage ("Message.common",
Presult.getexceptioninfo ()));
}
if (!ams.isempty ()) {
Savemessages (Request, AMS);
}
The method is called in the JSP as follows:
<font color= "Red" ><bean:write name= "MSG"/></font>



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.