【Java EE (Struts2 + Spring + Hibernate)开发】: Struts2(一)基本用法(待续)

网友投稿 268 2022-09-06

【Java EE (Struts2 + Spring + Hibernate)开发】: Struts2(一)基本用法(待续)

【Java EE (Struts2 + Spring + Hibernate)开发】: Struts2(一)基本用法 ​

1 MVC 的思想概述

2 Struts2 的下载和安装

为 Web 应用添加 Struts2 支持

在 Eclipse 中使用 Struts 2

增加登录处理

3 Struts2 的流程

4 Struts2 的常规配置

4-1 常量配置

struts2 除了可使用 struts.xml 文件来管理配置之外,还可以使用 struts.properties 文件来管理常量。 Struts2常量的具体用法实例

struts2 会默认加载类加载路径下的 struts.xml, struts-default.xml, struts-plugin.xml 三类文件,其中 struts.xml 是开发者默认配置文件, struts-default.xml 是 struts2 框架自带的配置文件,而 struts-plugin.xml 则是 struts2 插件的默认配置文件。

struts2配置常量总共有三种方式: - 通过 struts.properties 文件。 - 通过 struts.xml 文件。

通过 Web 应用的 web.xml 文件。

struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts.custom.i18n.resources mess

一个完整的 struts.xml 实例

参数值 参数值 参数值 参数值 参数值 映射资源 参数值 异常处理资源 参数值 参数值 映射资源 参数值 参数值 异常处理资源 参数值

4-2 包含其他配置文件

5 实现 Action

5-1 Action 接口 和 ActionSupport 基类

public interface Action //定义Action接口里包含的一些结果字符串 public static final String ERROR = "error"; public static final String INPUT = "input"; public static final String LOGIN = "login"; public static final String NONE = "none"; public static final String SUCCESS = "success"; //定义处理用户请求的execute()方法 public String execute() throws

ActionSupport是一个默认的Action实现类,该类里已经提供了许多默认方法,这些方法包括获取国际化信息的方法、数据校验的方法、默认的处理用户请求的方法等,实际上,ActionSupport是Struts2的默认的Action处理类,如果让开发者的Action类继承该ActionSupport类,则会大大简化Action的开发。

package com.opensymphony.xwork2;import com.opensymphony.xwork2.inject.Container;import com.opensymphony.xwork2.inject.Inject;import com.opensymphony.xwork2.util.ValueStack;import com.opensymphony.xwork2.util.logging.Logger;import com.opensymphony.xwork2.util.logging.LoggerFactory;import java.io.Serializable;import java.util.Collection;import java.util.List;import java.util.Locale;import java.util.Map;import java.util.ResourceBundle;/*** Provides a default implementation for the most common actions.* See the documentation for all the interfaces this class implements for more detailed information.*/public class ActionSupport implements Action, Validateable, ValidationAware, TextProvider, LocaleProvider, Serializableprotected static Logger LOG = LoggerFactory.getLogger(ActionSupport.class);private final ValidationAwareSupport validationAware = new ValidationAwareSupport();private transient TextProvider textProvider;private Container container;public void setActionErrors(Collection errorMessages) { validationAware.setActionErrors(errorMessages);}public Collection getActionErrors() { return validationAware.getActionErrors();}public void setActionMessages(Collection messages) { validationAware.setActionMessages(messages);}public Collection getActionMessages() { return validationAware.getActionMessages();}/*** @deprecated@Deprecatedpublic Collection getErrorMessages() { return getActionErrors();}/*** @deprecated@Deprecatedpublic Map> getErrors() { return getFieldErrors();}//设置表单域校验错误信息public void setFieldErrors(Map> errorMap) { validationAware.setFieldErrors(errorMap);}//返回表单域错误校验信息public Map> getFieldErrors() { return validationAware.getFieldErrors();}//控制locale的相关信息public Locale getLocale() { ActionContext ctx = ActionContext.getContext(); if (ctx != null) { return ctx.getLocale(); } else { LOG.debug("Action context not initialized"); return null; }}public boolean hasKey(String key) { return getTextProvider().hasKey(key);}public String getText(String aTextName) { return getTextProvider().getText(aTextName);}//返回国际化信息的方法public String getText(String aTextName, String defaultValue) { return getTextProvider().getText(aTextName, defaultValue);}public String getText(String aTextName, String defaultValue, String obj) { return getTextProvider().getText(aTextName, defaultValue, obj);}public String getText(String aTextName, List args) { return getTextProvider().getText(aTextName, args);}public String getText(String key, String[] args) { return getTextProvider().getText(key, args);}public String getText(String aTextName, String defaultValue, List args) { return getTextProvider().getText(aTextName, defaultValue, args);}public String getText(String key, String defaultValue, String[] args) { return getTextProvider().getText(key, defaultValue, args);}public String getText(String key, String defaultValue, List args, ValueStack stack) { return getTextProvider().getText(key, defaultValue, args, stack);}public String getText(String key, String defaultValue, String[] args, ValueStack stack) { return getTextProvider().getText(key, defaultValue, args, stack);}//用于访问国际化资源包的方法public ResourceBundle getTexts() { return getTextProvider().getTexts();}public ResourceBundle getTexts(String aBundleName) { return getTextProvider().getTexts(aBundleName);}//添加错误信息public void addActionError(String anErrorMessage) { validationAware.addActionError(anErrorMessage);}public void addActionMessage(String aMessage) { validationAware.addActionMessage(aMessage);}添加字段校验的错误信息public void addFieldError(String fieldName, String errorMessage) { validationAware.addFieldError(fieldName, errorMessage);}//默认Input方法,直接访问input字符串public String input() throws Exception { return INPUT;}public String doDefault() throws Exception { return SUCCESS;}/*** A default implementation that does nothing an returns "success".*

* Subclasses should override this method to provide their business logic.*

* See also {@link com.opensymphony.xwork2.Action#execute()}.** @return returns {@link #SUCCESS}* @throws//默认处理用户请求的方法,直接返回SUCCESS字符串public String execute() throws Exception { return SUCCESS;}public boolean hasActionErrors() { return validationAware.hasActionErrors();}public boolean hasActionMessages() { return validationAware.hasActionMessages();}public boolean hasErrors() { return validationAware.hasErrors();}public boolean hasFieldErrors() { return validationAware.hasFieldErrors();}/*** Clears field errors. Useful for Continuations and other situations* where you might want to clear parts of the state on the same action.*/public void clearFieldErrors() { validationAware.clearFieldErrors();}/*** Clears action errors. Useful for Continuations and other situations* where you might want to clear parts of the state on the same action.*/public void clearActionErrors() { validationAware.clearActionErrors();}/*** Clears messages. Useful for Continuations and other situations* where you might want to clear parts of the state on the same action.*/public void clearMessages() { validationAware.clearMessages();}/*** Clears all errors. Useful for Continuations and other situations* where you might want to clear parts of the state on the same action.*/public void clearErrors() { validationAware.clearErrors();}/*** Clears all errors and messages. Useful for Continuations and other situations* where you might want to clear parts of the state on the same action.*///清理错误信息的方法public void clearErrorsAndMessages() { validationAware.clearErrorsAndMessages();}/*** A default implementation that validates nothing.* Subclasses should override this method to provide validations.*///包含空校验的方法public void validate() {}@Overridepublic Object clone() throws CloneNotSupportedException { return super.clone();}/*** * Stops the action invocation immediately (by throwing a PauseException) and causes the action invocation to return* the specified result, such as {@link #SUCCESS}, {@link #INPUT}, etc.*

*

* The next time this action is invoked (and using the same continuation ID), the method will resume immediately* after where this method was called, with the entire call stack in the execute method restored.*

*

* Note: this method can only be called within the {@link #execute()} method.* ** @parampublic void pause(String result) {}/*** If called first time it will create {@link com.opensymphony.xwork2.TextProviderFactory},* inject dependency (if {@link com.opensymphony.xwork2.inject.Container} is accesible) into in,* then will create new {@link com.opensymphony.xwork2.TextProvider} and store it in a field* for future references and at the returns reference to that field** @returnprivate TextProvider getTextProvider() {if (textProvider == null) { TextProviderFactory tpf = new TextProviderFactory(); if (container != null) { container.inject(tpf); } textProvider = tpf.createInstance(getClass(), this); }return textProvider;}@Injectpublic void setContainer(Container container) { this.container = container; }}

5-2 Action 访问 Servlet API (一般推荐使用,IOC方式,只能获得request,而response则得不到)

Struts2框架提供了一种更轻松的方式来访问Servlet API。在web应用中通常要访问Servlet API的就是HttpServletRequest、HttpSession和ServletContext,这三个类别分别代表JSP内置对象中的request、session和application。

Struts2提供了一个ActionContext类,Struts2的Action通常可以通过该类来访问Servlet API。下面是ActionContext类中包含的几个常用方法: (1)Object get(Object key): 该方法类似于调用 HttpServletRequest 的getAttribute(String name) 方法。 (2)Map getApplication():返回一个Map对象,该对象模拟了该应用的 ServletContext实例。 (3)static ActionContext getContext():静态方法,获取系统的 ActionContext 实例。 (4)Map getparameters():获取所有的请求参数,类似于调用 HttpServletRequest 对象的 getParameterMap() 方法。 (5)Map getSession():返回一个 Map 对象,该对象模拟一个 HttpSession 实例。 (6)void setApplication(Map application):直接传入一个Map 实例,该 Map 实例里面的 key-value 对转换成 application 的属性名、属性值。 (7)void setSession(Map session):直接传入一个 Map 实例,该Map实例里面的 key-value 对转换成 session 的属性名、属性值。

5-3 Action 直接访问 Servlet API (不推荐,麻烦,非IOC方式,与Servlet API耦合大)

虽然Struts2提供了ActionContext来访问Servlet API,但这种访问不能直接获得Servlet API,为了在Action中直接访问Servlet API,Struts2还提供了以下接口。

ServletContextAware:实现该接口的Action可以直接访问Web应用的ServletContext实例;ServletRequestAware:实现该接口的Action可以直接访问用户请求对象的HttpServletRequest的实例;ServletResponseAware:实现该接口的Action可以直接访问服务器响应的HttpServletResponse的实例;

5-4 使用 ServletActionContext 访问 Servlet API (非IOC方式,强烈推荐使用)

Struts2还提供了一个ServletActionContext,其静态方法有:getPageContext()、getRequest() 、getResponse()、getServletContext()。 1. HttpServletRequest request=ServletActionContext.getRequest(); 2. HttpServletResponse response=ServletActionContext.getResponse(); 3. request.getSession().setAttribute(“username”,”admin”); 4. request.setAttribute(“password”,”123456”);

6 配置 Action

6-1 包和命名空间

Struts2使用包来组织Action,Struts2框架中的核心组件就是Action和拦截器,Struts2框架使用包来管理Action和拦截器等,每个包就是多个Action、多个拦截器、多个拦截器引用的集合。

在struts.xml文件中,package 元素用于定义包配置,每个package元素定义一个包配置,定义package时可以指定如下几个属性: 1. name: 这是一个必须的属性,该属性指定该包的名字,该名字是该包被其他包引用的key。 2. extends: 该属性是一个可选属性,该属性指定该报继承其他包。继承其他包,就可以继承其他包中的 Action 定义、拦截器定义等。 3. namespace: 该属性是一个可选属性,该属性定义该包的命名空间。 4. abstract: 该属性是一个可选属性,他指定该包是否是一个抽象包,在抽象包中不能有package属性。 因为Struts2的配置文件时从上到下进行处理,所以父包应该在子包的前面定义。

下面是一个简单的struts.xml文件配置文件范例。在下面的struts.xml文件中配置两个包,其中名为default的包,继承了Struts2框架的默认包:struts-default。

参数值 showcase.jsp /date.jsp /empmanager/editskill.jsp /empmanager/editSkill.jsp edit.action?skillName=${currentSkill.name}

6-2 Action 的基本配置

6-3 使用 Action 的动态方法 DMI(Dynamic Method Invocation)调用

可以在url地址中动态指定action执行那个方法。Url地址如下:

+ ! + 方法名 注:只要Action对象中有这个方法,并且返回类型为String就可以调用。 这样Struts.xml配置文件中不需要配置methed属性。代码如下:

/user_add_success.jsp

Action类:

public class UserAction extends ActionSupport public String add() { return

使用动态方法调用前必须设置 Struts2允许动态方法调用,设置 struts.enable.DynamicMethodInvocation 的常量值为 true 。

6-4 指定 method 属性及使用通配符

当我们配置 Action 时,实际上可以认为需要配置三个属性: name 属性指定该 Action 处理怎样的请求,该属性不可省略; class 属性指定该 Action 的处理类,默认使用 ActionSupport 作为处理类; method 属性指定使用哪个方法处理请求,默认使用 execute 方法处理请求。

6-5 配置默认 Action

show.jsp

6-6 配置 Action 的默认处理类

7 配置处理结果

8 配置 Struts2 的异常处理

9 Convention 插件与“约定”支持

10 使用 Struts2 的国际化

11 使用 Struts2 的标签库

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:MySQL中的多表查询②
下一篇:Quartz 基础知识及示例代码(一)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~