Struts编程心得

前期阅读了Struts的UserGuide和相关的一些文档,开始动手做Struts的开发

例子很简单,就是做一个登录的过程,参考了文档和Struts的一些Example的代码,总结了以下几点:

1、能用struts的标签的HTML代码最好都用struts的标签来代替。因为struts的标签一般都提供将相对路径转换为绝对URL的功能,这样可以保证css,图片等资源被100%找到

2、 <html:base/>标签最好用上,因为这样做了之后,就可以保证在一些无法用struts标签代替的HTML代码中的资源路径的引用是 正确的。如<link ...>这样的HTML,还有<td background="...>这样的HTML代码

3、 struts自带了common-logging,可以使用log4j,jdk的logging还有自身的simple-logging,推荐使用 log4j!具体的做法是这样,首先将log4j的jar包放到WEB-INF/lib下,这样,struts就可以找到log4j了;然后,在WEB- INF/class目录下建立一个文件log4j.properties,在里面写上配置,这样,log4j就可以工作了!至于在代码中如何调用,请看 struts文档阅读摘要。log4j的配置请看刚发的“log4j官方sample配置”一帖!
4、如果要使用Validator,还要使用DynaActionForm,那么要保证如下一些事情:

(1)在struts-confg.xml中配置validator的Plug-In

(2)在validator.xml中配置validate的规则

(3)在struts-config.xml中配置form-bean,typeclass必须是DynaValidatorForm

(4)在struts-config.xml中配置这个action时,必须要配置input属性,这样DynaValidatorForm才可以在validator失败的时候正确返回到输入页面

注:这里DynaValidatorForm还有一个继承类,是DynaValidatorActionForm,这两个类,根据源码里面的注释,有这样的区别(目前还不是很理解):

DynaValidatorForm:

* <p>This class extends <strong>DynaActionForm</strong> and provides
* basic field validation based on an XML file. The key passed into the
* validator is the action element's 'name' attribute from the
* struts-config.xml which should match the form element's name attribute
* in the validation.xml.</p>

DynaValidatorActionForm:

* <p>This class extends <strong>DynaValidatorForm</strong> and provides
* basic field validation based on an XML file. The key passed into the
* validator is the action element's 'path' attribute from the
* struts-config.xml which should match the form element's name attribute
* in the validation.xml.</p>


还漏了一点,要用validator,要在jsp代码里添加如下:

1、在<html:form 标签里添加 onsubmit="return validateLoginForm(this);"

2、在JSP页面里添加

<html:javascript formName="LoginForm" dynamicJavascript="true" staticJavascript="false"/>
<script language="Javascript1.1" src="staticJavascript.jsp"></script>
5、我们可以通过书写PlugIn的方式,让我们的应用在启动的时候就执行一些代码,通常这些代码都是初始化用的。书写完成后需要在struts-config.xml中书写PlugIn的配置,然后就OK了。具体的实现代码和配置可以看EasyCluster的代码。

6、一般来说,在PlugIn里初始化后,可以将数据放在application对象中,其实也就是servlet context中。代码如下:

servlet.getServletContext().setAttribute(Constants.DATASOURCE_KEY, ds);

这样,以后在JSP中,就可以直接调用application.getAttribute方法来获得对象

在servlet中,就可以调用this.getServlet().getServletContext().getAttribute来获得对象

7、bean:write 这个标签中有一个属性叫做filter,默认值是true。如果这个filter被置为true的话,那么,Struts将会自动对bean:write的输出做HTML的解析,如把<font color=red>变成

&ltfont color=red&gt

这是非常讨厌的情况,因为我们有的时候会在JavaBean里面写上一些HTML代码,希望将来在JSP中直接可以显示出来。所以,如果在JavaBean里有这样的HTML代码,记得在客户端输出的时候把filter置成false
 

原文地址:https://www.cnblogs.com/super119/p/1988606.html