Struts2 Core Developers Guide-FAQ

1.What are the fundamental differences between Struts and JSF
Specifically, JSF is a "component" framework whereas Struts is an "action" framework.
总的来说,JSF,asp.net这种框架采用的是一种,类似于cs架构中的组件式,基于组建事件的编程风格.
而struts事基于action的框架,这里的action对于http来说应该可以理解为url,或者说是REST中的资源路径.
2.如何在页面上直接从流中显示图片.
faq中居然自己写了一个MyActionResult类实现,一看日期居然是2006-7-22,好像在struts2中可以直接通过streamresult指定contenttype为image/jpeg,image/gif来实现了.
3.How can we return a text string as the response
faq中描述可以利用streamresult在stream中加入text信息来解决.但是这个给人感觉比较奇怪.\
4.How can we test applications?
原则,尽量把一些业务逻辑代码移到facade层中,保持action类中的代码量尽量少这样就可以通过测试,facade来覆盖大部分的系统功能.
另外faq中推荐了一种Selenium工具来进行UI测试.
5.How can we test Actions
直接创建并且调用action对象的方法.
通过ActionProxyFactory包装后调用,这样可以调用测试拦截器和result的运行结果是否正确.
6.如何处理文件上传的请求.
建议的方式是采用fileuploadinterceptor,可以实现多文件上传功能
代码如下
<form name="myForm" enctype="multipart/form-data">
      <input type="file" name="myDoc" value="Browse File A ..." />
      <input type="file" name="myDoc" value="Browse File B ..." />
      <input type="file" name="myDoc" value="Browse File C ..." />
      <input type="submit" />
   </form>
public void setMyDoc(File[] myDocs)
public void setMyDocContentType(String[] contentTypes)
public void setMyDocFileName(String[] fileNames)

7.How can we force the Action Mappings (struts.xml) to reload
devMode=true或者struts.configuration.xml.reload=true
8.如何分割struts配置文件
<struts>
    <include file="struts-default.xml"/>
    <include file="config-browser.xml"/>
    <package name="default" extends="struts-default">
....
    </package>
    <include file="other.xml"/>
</struts>

可以加载单个jar文件中的struts.xml配置文件.
9.Parameters in configuration results
result中的location属性支持ognl表达式,所以可以通过其实现结果的参数化.
<struts>
....
   <package name="somePackage" namespace="/myNamespace" extends="struts-default">
      <action name="myAction" class="com.project.MyAction">
         <result name="success" type="redirectAction">otherAction?id=${id}</result>
         <result name="back" type="redirect">${redirectURL}</result>
      </action>

      <action name="otherAction" class="com.project.MyOtherAction">
         ...
      </action>      
   </package>
....
</struts>

不过需要对应的action方法中有getId和getRedirectURL方法.
10.运行时获取session
Map attibutes = ActionContext.getContext().getSession();
或者实现SessionAware并且加入servlet-config拦截器.
11.运行时获取request
HttpServletRequest request = ServletActionContext.getRequest();
或者实现ServletRequestAware并且加入servlet-config拦截器.
12.运行时获取response
HttpServletResponse response = ServletActionContext.getResponse()
或者实现ServletResponseAware并且加入servlet-config拦截器.
13.获取提交的request parameters
Map parameters = ActionContext.getContext().getParameters();
实现ParameterAware并且加入servlet-config拦截器.
14.访问action配置中定义的参数
直接在action中定义对应action中参数名的settermethod,或者定义setParams(Map)来实现.
15.Can we access an Action's Result
Map resultsMap = invocation.getProxy().getConfig().getResults();
16.How do I obtain security details (JAAS)
从request中获取
HttpServletRequest request = ServletActionContext.getRequest();
String authType = request.getAuthType();         // http or https
String user = request.getRemoteUser();           // the user principal (in string)
Principalprincipal = request.getUserPrincipal(); // get a Principal object
bool isAuth = request.isUserInRole("patrick");

实现PrincipalAware并且加入servlet-config拦截器
通过调用PrincipalProxy的同名方法实现.
17.如何改变页面的主题(theme)
<saf:set name="theme" value="simple" scope="page" />
由于value支持ognl所以也可以写成
<saf:set name="theme" value="%{myTheme}" scope="page" />
18.Why isn't our Prepare interceptor being executed
Prepare 拦截器最好在validation拦截器之前,否则可能被打断.
19.Why doesn't my setter get called ?
getter和setter操作的数据类型必须一直,否则ognl会忽略.
20.How do we repopulate controls when validation fails
faq中提示采用preparable接口和action标记实现,但是感觉ConversionErrorInterceptor也可以实现相同的功能
21.如何测试校验信息
public class WebLoginActionTest extends TestCase {
    
    private WebLoginAction wla;
    
    protected void setUp() throws Exception {
        wla = new WebLoginAction();
        wla.setJ_username("");
        wla.setJ_password(null);
        super.setUp();
    }
 
    public void testWebLoginActionValidation() throws ValidationException {
        ActionValidatorManager avm = ActionValidatorManagerFactory.getInstance();        
        
        avm.validate(wla,"");
        Map fieldErrors = wla.getFieldErrors();
        
        assertTrue(wla.hasErrors());
        assertEquals(2, fieldErrors.size());
        assertTrue(fieldErrors.containsKey("j_username"));
        assertTrue(fieldErrors.containsKey("j_password"));
                
        System.out.println("[errors] : " +  fieldErrors.toString());              
    }
}

22.为什么使用CDATA时有些消息会被忽略.
确保<![CDATA[ 后没有空格.
23.如何改变页面的locale
  • 可以通过requst_locale参数传递
  • 可以通过action的setLocale方法实现

24.如何定义全局properties文件
struts.custom.i18n.resources=global-messages, image-messages
25.How do I add I18N to a UI tag, like the textfield tag
如何为普通的标记添加i18n的getText支持.
修改controlheader模板
${parameters.label?html}:<#t/>

<#assign mm="getText('"+parameters.label?html+"')" /><#t/>
${stack.findValue(mm)}:<#t/>

or

${stack.findValue("getText('"+parameters.label?html+"')")}

After making the change, tags with a label attribute will use the value you set as a key.

<saf:textfield label="label.firstName" name="firstName" />

26.Can I add I18N outside the Action's context
可以通过如下的标签来实现对应的properties文件的加载以便在为调用action的情况下使用resource bundle.
<p><saf:i18n name="alternate">
    <img src="<saf:text name="action.logo.path"/>"
         alt="<saf:text name="action.logo.alt"/>"/>
</saf:i18n></p>

27.How to escape special chars in resource bundles
如何在resource文件中转义特殊字符
The special chars \', { and }:
escape ' with another '

''
	(double-single quote)
escape \ with another \
\\

	(double backslash)
enclose } with '
'}'

enclose { with '
'{'

28.How do I change the invalid input error message for a particular field
如何修改某个字段的错误信息
invalid.fieldvalue.user.dob=Please enter Date of Birth in the correct format.
29.为jsp页面添加jsp标签的支持
在web.xml中添加如下定义
<servlet>
    <servlet-name>jspSupportServlet</servlet-name>
    <servlet-class>org.apache.struts2.views.JspSupportServlet</servlet-class>
    <load-on-startup>10</load-on-startup>
</servlet>

30.Can an action tag run another method apart from the default execute method
可以采用action别名来实现该需求.

你可能感兴趣的:(UI,servlet,struts,JSF,asp.net)