Struts2的环境要求
Apache Struts2的环境需求如下:
Servlet API 2.4
JSP API 2.0
Java 5
需要提醒的是,在Struts中会用到Annotation,所以请将JDK版本升级到1.5以上
Struts2环境搭建
Struts的下载
从游览器输入http://people.apache.org/builds/struts/,即可看到Struts的各个版本列表。
下表注明了各个压缩包的作用。
压缩包名称 | 作用 |
struts-2.1.0-docs.zip | 文档,包含了Struts2API |
struts-2.1.0-lib.zip | 构建Struts2工程所需要的包 |
struts-2.1.0-src.zip | Struts2的所有源代码 |
struts2-blank-2.1.0.war | 空白工程 |
struts-2.1.0-all.zip | 大集成,包括上面所有的内容 |
库文件
从网站上下载的Struts2包含了二三十个库文件,但大多数是可选的,有些库是插件,用于和其他框架的整合。
读者可自行下载struts2-blank-2.1.0.war压缩包,展开后是一个非常简单的项目,从WEB-INF/lib目录中可以看到5个库文件,解释如下:
包名 | 说明 |
commons-logging-1.0.4.jar | 日志管理 |
freemarker-2.3.8.jar | 表现层框架,定义了struts2的可视组件主题(theme) |
ognl-2.6.11.jar | OGNL表达式语言,struts2支持该EL |
struts2-core-2.0.10.jar | struts2的核心库 |
xwork-2.0.4.jar | webwork的核心库,自然需要它的支持 |
使用Eclipse搭建Struts2的开发环境
创建用户库
将Struts2所需的包建成用户库,可以更加方便地进行管理和使用,这是一个好的习惯——编程从习惯开始。
1.选择菜单Window->Preferences->Java->Build Path->User Libraries。
将Struts2所带的过滤器org.apache.struts2.dispatcher.FilterDispatcher配置到工程的web.xml文件中,默认情况下,该过滤器拦截请求字符串中以.action结尾的请求,并将该请求委托给指定的Action进行处理。最直观的表现就是调用Action的execute()方法。代码如下:
代码清单1:web.xml
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
注:在Sturts1.X中,该行为由Servlet完成。
创建包com.lizanhong.action,并在该包中创建HelloWorldAction类,该类继承自com.opensymphony.xwork2.ActionSupport。理论上,Action可以不继承任何类或实现任何接口,以增强程序的可测试性,这也是和Struts1.X不同的地方。但是,继承自ActionSupport可以减少更多的编码工作。
在ActionSupport中,定义了方法execute(),当用户向该Action发送请求时,会自动调用。程序代码如下:
代码清单2:HelloWorldAction.java
package com.lizanhong.action;
import com.opensymphony.xwork2.ActionSupport;
publicclass HelloWorldAction extends ActionSupport {
@Override
public String execute() throws Exception {
System.out.println("Action执行了。");
returnSUCCESS;
}
}
注:ActionSupport是Struts2提供的类,功能类似于Struts1.x中的Action类,该类封装了几个有用的功能,比如:
getText():从资源文件中获取国际化消息。
addFieldError():验证输入未通过时添加错误消息,支持国际化。
execute():该方法一般会被重写,当客户端向Action发送请求时,会调用此方法。
总结起来,该类主要提供了错误消息的支持和国际化支持。
在工程类路径下创建struts.xml文件,这是Struts2的配置文件,类似于Struts1.x中的struts-config.xml,在struts.xml文件中可以配置Action、Bean、Interceptor等组件。
代码清单3:struts.xml
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="struts-default.xml"></include>
<package name="a" extends="struts-default">
<action name="helloworld" class="com.lizanhong.action.HelloWorldAction">
<result>/result.jsp</result>
</action>
</package>
</struts>
注:WEB应用程序的类路径是指WEB-INF/classes目录,在Eclipse中,创建在src目录下的文件最终发布后会自动复制到WEB-INF/classes目录下。
1.深入Struts2的配置文件
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- struts2的action必须放在一个指定的包空间下定义 -->
<package name="qiujy" extends="struts-default">
<!-- 定义处理请求URL为login.action的Action -->
<action name="login" class="org.qiujy.web.struts2.action.LoginAction">
<!-- 定义处理结果字符串和资源之间的映射关系 -->
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
<package name="my" extends="struts-default" namespace="/manage">
<!-- 定义处理请求URL为login.action的Action -->
<action name="backLogin" class="org.qiujy.web.struts2.action.LoginAction">
<!-- 定义处理结果字符串和资源之间的映射关系 -->
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package></struts>
<struts>
<include file="struts-default.xml"/>
<include file="struts-user.xml"/>
<include file="struts-book.xml"/>
<include file="struts-shoppingCart.xml"/>
......
</struts>
<struts>
......
<constant name="struts.custom.i18n.resources" value="messages"/>
</struts>
表示指定了资源文件的放置在classes目录下,基本名是messages,则在classes目录下您就应该放置类似messages_zh_CN.properties,message_en.properties名的文件。
package org.qiujy.web.struts2.action;
import com.opensymphony.xwork2.ActionSupport;
/**
*@authorqiujy
*@version1.0
*/
publicclass LoginAction extends ActionSupport{
private String userName;
private String password;
private String msg; //结果信息属性
/**
*@returnthemsg
*/
public String getMsg() {
returnmsg;
}
/**
*@parammsgthemsgtoset
*/
publicvoid setMsg(String msg) {
this.msg = msg;
}
/**
*@returntheuserName
*/
public String getUserName() {
returnuserName;
}
/**
*@paramuserNametheuserNametoset
*/
publicvoid setUserName(String userName) {
this.userName = userName;
}
/**
*@returnthepassword
*/
public String getPassword() {
returnpassword;
}
/**
*@parampasswordthepasswordtoset
*/
publicvoid setPassword(String password) {
this.password = password;
}
/**
*处理用户请求的excute()方法
*@return结果导航字符串
*@throwsException
*/
public String execute() throws Exception{
if("test".equals(this.userName) &&
"test".equals(this.password)){
msg = "登录成功,欢迎" + this.userName;
returnthis.SUCCESS;
}else{
msg = "登录失败,用户名或密码错";
returnthis.ERROR;
}
}
}
往success.jsp和error.jsp页面中添加 EL表达式来显示结果信息。则最终效果跟以前一样。
public String execute() throws Exception{
if("test".equals(this.userName) && "test".equals(this.password)){
msg = "登录成功,欢迎" + this.userName;
//获取ActionContext实例,通过它来访问Servlet API
ActionContext context = ActionContext.getContext();
//看session中是否已经存放了用户名,如果存放了:说明已经登录了;
//否则说明是第一次登录成功
if(null != context.getSession().get("uName")){
msg = this.userName + ":你已经登录过了!!!";
}else{
context.getSession().put("uName", this.userName);
}
returnthis.SUCCESS;
}else{
msg = "登录失败,用户名或密码错";
returnthis.ERROR;
}
}
<form method="post" action="userOpt!login.action"> |
package org.qiujy.web.struts2.action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
*@authorqiujy
*@version1.0
*/
publicclass LoginAction extends ActionSupport{
private String userName;
private String password;
private String msg; //结果信息属性
/**
*@returnthemsg
*/
public String getMsg() {
returnmsg;
}
/**
*@parammsgthemsgtoset
*/
publicvoid setMsg(String msg) {
this.msg = msg;
}
/**
*@returntheuserName
*/
public String getUserName() {
returnuserName;
}
/**
*@paramuserNametheuserNametoset
*/
publicvoid setUserName(String userName) {
this.userName = userName;
}
/**
*@returnthepassword
*/
public String getPassword() {
returnpassword;
}
/**
*@parampasswordthepasswordtoset
*/
publicvoid setPassword(String password) {
this.password = password;
}
/**
*处理用户请求的login()方法
*@return结果导航字符串
*@throwsException
*/
public String login() throws Exception{
if("test".equals(this.userName) && "test".equals(this.password)){
msg = "登录成功,欢迎" + this.userName;
//获取ActionContext实例,通过它来访问Servlet API
ActionContext context = ActionContext.getContext();
//看session中是否已经存放了用户名,如果存放了:说明已经登录了;
//否则说明是第一次登录成功
if(null != context.getSession().get("uName")){
msg = this.userName + ":你已经登录过了!!!";
}else{
context.getSession().put("uName", this.userName);
}
returnthis.SUCCESS;
}else{
msg = "登录失败,用户名或密码错";
returnthis.ERROR;
}
}
public String regist() throws Exception{
//将用户名,密码添加到数据库中
//...
msg = "注册成功。";
returnthis.SUCCESS;
}
}
2. struts.xml文件:没有什么变化,跟以前一样配置
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="my" extends="struts-default" namespace="/manage">
<!-- 定义处理请求URL为login.action的Action -->
<action name="userOpt" class="org.qiujy.web.struts2.action.LoginAction">
<!-- 定义处理结果字符串和资源之间的映射关系 -->
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
<%@ page language="java" pageEncoding="UTF-8"%>
<html>
<head>
<title>用户登录页面</title>
</head>
<body>
<h2>用户入口</h2>
<hr>
<form action="manage/userOpt!login.action" method="post">
<table border="1">
<tr>
<td>用户名:</td>
<td><input type="text" name="userName"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value=" 确定 "/>
</td>
</tr>
</table>
</form>
</body>
</html>
regist.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<html>
<head>
<title>用户注册页面</title>
</head>
<body>
<h2>用户注册</h2>
<hr>
<form action="manage/userOpt!regist.action" method="post">
<table border="1">
<tr>
<td>用户名:</td>
<td><input type="text" name="userName"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value=" 注册 "/>
</td>
</tr>
</table>
</form>
</body>
</html>
4. 运行结果:
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="my" extends="struts-default" namespace="/manage">
<action name="userLogin" class="org.qiujy.web.struts2.action.LoginAction" method="login">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="userRegist" class="org.qiujy.web.struts2.action.LoginAction" method="regist">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
如上,把LoginAction中的login和regist方法都配置成逻辑Action。要调用login方法,则相应的把index.jsp中表单元素的action设置为"manage/userLogin.action";要调用regist方法,把regist.jsp中表单元素的action设置为"manage/userRegist.action"。
<action name="user_*"
class="org.qiujy.web.struts2.action.UserAction" method="{1}">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
如上,<action name=”user_*”>定义一系列请求URL是user_*.action模式的逻辑Action。同时method属性值为一个表达式{1},表示它的值是name属性是根据实际调用的Action来的。例如:用户请求URL为user_login.action时,将调用到UserAction类的login方法;用户请求URL为user_regist.action时,将调用到UserAction类的regist方法。
<global-results>
<result name="error">/Error.jsp</result>
<result name="invalid.token">/Error.jsp</result>
<result name="login" type="redirect-action">Logon!input</result>
</global-results>
当一个Action返回的String没有相应的<result>与之对应,Struts2就会查找全局的<result>。
名字
|
说明
|
chain
|
用来处理Action链
|
dispatcher
|
用来转向页面,通常处理JSP,这是默认的结果类型
|
freeMarker
|
处理FreeMarker模板
|
httpHeader
|
用来控制特殊的Http行为
|
redirect
|
重定向到一个URL
|
redirect-action
|
重定向到一个Action
|
stream
|
向浏览器发送InputSream对象,通常用来处理文件下载
|
velocity
|
处理Velocity模板
|
xslt
|
处理XML/XLST模板
|
plaintext
|
显示原始文件内容,例如文件源代码
|
tiles
|
结合Tile使用
|
private String nextAction;
public String getNextAction() {
return nextAction;
}
在strutx.xml配置文件中,我们可以使用来引用到Action中的属性,通过表示的内容来动态的返回结果,例如:
<action name="fragment" class="FragmentAction">
<result name="next" type="redirect-action"></result>
</action>
上述Action的execute方法返回next的时候,还需要根据nextAction的属性来判断具体定位到哪个Action。
package org.qiujy.domain;
publicclass User {
private String userName;
private String password;
/**
*@returntheuserName
*/
public String getUserName() {
returnuserName;
}
/**
*@paramuserNametheuserNametoset
*/
publicvoid setUserName(String userName) {
this.userName = userName;
}
/**
*@returnthepassword
*/
public String getPassword() {
returnpassword;
}
/**
*@parampasswordthepasswordtoset
*/
publicvoid setPassword(String password) {
this.password = password;
}
}
2. 业务控制器:UserAction.java
package org.qiujy.web.struts2.action;
import org.qiujy.domain.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
publicclass UserAction extends ActionSupport{
//定义用于封装请求参数的模型对象
private User user = new User();
private String msg; //结果信息属性
/**
*@returntheuser
*/
public User getUser() {
returnuser;
}
/**
*@paramusertheusertoset
*/
publicvoid setUser(User user) {
this.user = user;
}
/**
*@returnthemsg
*/
public String getMsg() {
returnmsg;
}
/**
*@parammsgthemsgtoset
*/
publicvoid setMsg(String msg) {
this.msg = msg;
}
/**
*处理用户请求的login()方法
*@return结果导航字符串
*@throwsException
*/
public String login() throws Exception{
String userName = user.getUserName();
String password = user.getPassword();
if("test".equals(userName) && "test".equals(password)){
msg = "登录成功,欢迎" + userName;
//获取ActionContext实例,通过它来访问Servlet API
ActionContext context = ActionContext.getContext();
//看session中是否已经存放了用户名,如果存放了:说明已经登录了;否则说明是第一次登录成功
if(null != context.getSession().get("uName")){
msg = userName + ":你已经登录过了!!!";
}else{
context.getSession().put("uName", userName);
}
returnthis.SUCCESS;
}else{
msg = "登录失败,用户名或密码错";
returnthis.ERROR;
}
}
public String regist() throws Exception{
//将用户名,密码添加到数据库中
//...
msg = "注册成功。";
returnthis.SUCCESS;
}
}
3. 配置文件:struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="my" extends="struts-default" namespace="/manage">
<action name="userOpt" class="org.qiujy.web.struts2.action.UserAction">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
<%@ page language="java" pageEncoding="UTF-8"%>
<html>
<head>
<title>用户登录页面</title>
</head>
<body>
<h2>用户入口</h2>
<hr>
<form action="manage/userOpt!login.action" method="post">
<table border="1">
<tr>
<td>用户名:</td>
<td><input type="text" name="user.userName"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="user.password"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value=" 确定 "/>
</td>
</tr>
</table>
</form>
</body>
</html>
public String regist() throws Exception{
//将用户名,密码添加到数据库中
//...
//msg = "注册成功。";
if(true){
throw new java.sql.SQLException("没有数据库驱动程序");
}
return this.SUCCESS;
}
2) 修改struts.xml文件:
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="my" extends="struts-default" namespace="/manage">
<!-- 定义全局处理结果 -->
<global-results>
<!-- 逻辑名为sql的结果,映射到/exception.jsp页面 -->
<result name="sql">/exception.jsp</result>
</global-results>
<global-exception-mappings>
<!-- 当Action抛出SQLException异常时,转入名为sql的结果 -->
<exception-mapping exception="java.sql.SQLException" result="sql"/>
</global-exception-mappings>
<action name="userOpt" class="org.qiujy.web.struts2.action.UserAction">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
3) 新增一页面:exception.jsp
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>异常信息</title>
</head>
<body>
<h2>
出现异常啦
</h2>
<hr/>
<h3 style="color:red">
<!-- 获得异常对象 -->
<s:property value="exception.message"/>
</h3>
<br/>
<!-- 异常堆栈信息 -->
<s:property value="exceptionStack"/>
</html>