STRUTS
1.在WEB-INF中需要的配置(主要是实例化ActionServlet---struts-config.xml)
a. 如果标签不能识别:<jsp-config>
<taglib> <taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/c.tld</taglib-location> </taglib>
b.配置欢迎页面: <welcome-file-list> <welcome-file>/logon.jsp</welcome-file>
</welcome-file-list>
c.ActonServlet主要配置: <servlet> <servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param> <param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value></init-param>
</servlet>
<servlet-mapping> <servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern> </servlet-mapping>
2.struts-config.xml配置:(主要为中央处理器建立关联)
a. <action-mappings > <action
path="/logon" scope="request" type="mypack.action.LogonAction"
attribute="logonForm" name="logonForm" input="/logon.jsp">
<forward name="show" path="/AddAssociate.jsp" />
<forward name="failure" path="/logon.jsp" /> </action>
b.<form-beans >
<form-bean name="logonForm" type="mypack.struts.form.LogonForm" /> </form-beans>
c.resource文件:<message-resources parameter="mypack.struts.ApplicationResources" />
3.通过ActionForm的validate方法若验证通过才创建action实例:
public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) {
ActionErrors errors=new ActionErrors();if(userName==null){ //ActionMessage为父类
errors.add(“contant”,new ActionMessage(“resource.key”));//ActionErrors唯一方法
return errors;}
ActionErrors为ActionMessages子类,其add方法必须为ActionError,但1.2采用ActionMessage
4.虽然ActionServlet只有一个,但是通过配置组件ModuleConfig来创建具体子模块处理器RequestProcessor,由Action负责处理具体业务并通过ActionForward返回合适的结果.
如: public class LogonAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
LogonForm logonForm = (LogonForm) form; ActionErrors errors = new ActionErrors();
ActionForward forward = new ActionForward();
String userName = (String) (logonForm.getUserName()); if (!(userName.equals("admin"))
errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("logonagain"));
if (!errors.isEmpty()) {
saveErrors(request, errors); // saveErrors方法(request,errors必为ActionErrors)
forward = mapping.findForward("failure");}
else { HttpSession session = request.getSession();
session.setAttribute("user", userName);forward = mapping.findForward("show");}
return forward; }}
5.DAO访问数据库的模型:
a.public class ConnectDB { public static Connection getConnection(){
Connection conn=null;try{ Class.forName(driver);
conn=DriverManager.getConnection(url,user,password);}
catch(Exception e){e.printStackTrace();} return conn; }}
b.因为ActionForm中的数据生命周期只能到Action,于是只有通过action继续传递
AssociateForm associateForm = (AssociateForm) form;
String associateId=associateForm.getAssociateId();
String name=associateForm.getName();AssociateDao associateDao=new AssociateDao();
associateDao.addAssociateDao(associateId,name);将参数传递到DAO
c.在DAO中插入数据: public void addAssociateDao(String associateId,String name) { Connection conn=ConnectDB.getConnection();
String sql="insert into associateInfo(associateId,name) values(?,?)";
PreparedStatement pstmt=null; (try) pstmt=conn.prepareStatement(sql);
pstmt.setString(1,associateId);pstmt.setString(2,name);pstmt.execute();
6.访问数据库:a.在jsp页面的标签: 用jstl<c:set/>标签调用DAO中get方法并存在一定的范围
<jsp:useBean id="associateDao1" class="mypack.dao.AssociateDao" scope="page"/>
<c:set var="associates" value="${associateDao1.associateDao}" scope="page"/>
b. public Collection getAssociateDao() throws SQLException{
Connection conn=ConnectDB.getConnection();
Statement stmt=conn.createStatement();String sql="select * from associateInfo";
ResultSet rs=stmt.executeQuery(sql); List associateList=new ArrayList();
while(rs.next()){Associate temp=new Associate();//需要创建一个模型层数据中介 temp.setAssociateId(rs.getString("associateId"));
temp.setName(rs.getString("name"));associateList.add(temp);}//将数据全部封装
stmt.close();conn.close(); return associateList; }
c. <logic:iterate id="associate" name="associates" > //用<logic:iterate/>迭代集合
<td><bean:write name="associate" property="associateId" /></Td>
<td><bean:write name="associate" property="name" /></Td> </logic:iterate>
7.用validator框架实现验证:
a.jsp页面: <html:form action="/valid" onsubmit="return validatevalidForm(this)" />
<html:javascript formName="validForm"/>
b.struts-config.xml中配置插件: <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/valid.xml" /> </plug-in>
c. valid.xml的配置: <form-validation>
<global> <constant><constant-name>phone</constant-name>//设置全局变量
<constant-value>^\d{8}\d*$</constant-value> </constant> </global>
<formset> <form name="validForm">
<field property="phone" depends="required,mask">//通过变量验证的字段名
<var> <var-name>mask</var-name> <var-value>${phone}</var-value> </var>
<arg0 key="lable" /> </field> </form> </formset>
</form-validation>
d. properties文件的key:errors.required ={0} 为必填 lable=用户名 //{0}arg0为参数
备注:正则表达式:
*
|
匹配0或多次,对邻近一个(组)起作用
|
Ab*:a,abb
|
+
|
匹配>=1次,对邻近一个(组)起作用
|
Ab+:ab,abb
|
?
|
匹配0或一次, 对邻近一个(组)起作用
|
Ab?:a,ab
|
{n}
|
匹配指定的次数, 对邻近一个(组)起作用
|
Ab{2}c:abbc,aabbc
|
{n,m}
|
匹配从n到m次, 对邻近一个(组)起作用
|
Ab{2,3}c:abbc,abbbc
|
^(也表示字符串头)
|
不想匹配的字符,一般和[]一起
|
A[^b]c:adc,aec
|
$(字符串结束位置)
|
^\w+$:为一个或多个数字,字母
|
^\d{8}\d*$:只能8位数字
|
~
|
表示一个范围
|
[0~9]:0,1…9
|
\d
|
等价于[0~9]表示一个数字
|
\da:1a,2a
|
\D
|
等价于[^0~9],不能为数字
|
\Da:aa,da
|
\w
|
等价于[A~Z0~9]匹配单个数字或字母
|
\wa:1a,va
|
\W
|
等价于[^A~Z0~9]不匹配单个数字或字母
|
\Wa:!a,#a
|
\
|
转义字符
|
\.表示.
|
8.STRUTS国际化:
a.全部设为UTF-8编码:<%@ page language="java" contentType="text/html;charset=UTF-8" %>
b.bat文件: native2ascii –encoding gb2312 ori.properties target.properties
9.存放常量共享数据:
a.存放常量的java文件:public final class Constants{
public static final String PERSON_KEY=”personbean”;}
b.Action中保存数据:request.setAttribute(Constants.PERSON_KEY,class类);
c.在页面输出:<logic:present name="personbean" scope="request" >
<bean:write name="personbean" property="userName"/></logic:present>
10.输出下拉菜单组:<jsp:useBean id="groupDao" class="mypack.GroupDao" scope="page"/>
<c:set var="groups" value="${groupDao.groups}" /> //get方法
<td><html:select property="groupId"> //读取数据库中的groupName属性
<html:options collection="groups" property="groupId" labelProperty="groupName" />
</html:select></td>
11.Struts内置对象
a.forwardAction:(请求—ActionForm—Action—ActionForm—响应)
页面:<html:form action="/forward"><html:text property="userName"/> <html:submit/>
配置:<action input="/hello.jsp" name="forwardForm"
path="/forward" parameter="/forward.jsp" scope="request"
type="org.apache.struts.actions.ForwardAction"> </action>
输出:${forwardForm.userName}//在配置中的<form-beans >实例化
b.DispatchAction(用于不同的表单响应同一个Action)
页面:<html:form action="/personManager" >
<html:hidden property="method" value="addPerson" />
<html:text property="person.password" />
<html:submit value="add"/> </html:form>
<html:form action="/personManager" >
<html:text property="person.password" />
<html:submit property="method" value="updatePerson"/> </html:form>
配置:<action path="/personManager"
type="mypack.struts.action.MyDispatchAction" //继承DispatchAction
parameter="method" name="forward2Form" scope="request"
input="/dispatch.jsp" >
<forward name="success" path="/success.jsp"></forward> </action>
<action>中根据value自动映射:public ActionForward addPerson(){ }
public ActionForward updatePerson( ){ }
输出:${forward2Form.person.password }
备注:DispatchAction参数根据表单中的property映射,具体值由value传入。
c.LookupDispatchAction(同一个表单不同的触发事件)
页面:<html:form action="/personManager2">
<html:text property="person.password" />
<html:submit property="action" value="addPerson" />
<html:submit property="action">
<bean:message key="button.update.person" /> </html:submit> </html:form>
配置:<action path="/personManager2" parameter="action"
type="mypack.struts.action.MyLookupDispatch"
name="forward2Form" scope="request" input="/dispatch.jsp" >
<forward name="success" path="/success.jsp"></forward> </action>
资源文件:button.add.person=addPerson button.update.person=updatePerson
Action(重写父类LookupDispatchAction抽象方法): protected Map getKeyMethodMap() {
Map map=new HashMap(); map.put("button.add.person", "addPerson");
map.put("button.update.person", "updatePerson"); return map; }
public ActionForward addPerson(){ }
public ActionForward updatePerson( ){ request.setAttribute("ok", "update"); }
输出:${ok }
备注:LookupDispatchAction的映射由getKeyMethodMap方法建立,具体值也由value传入