一、Struts2简介
Struts2以WebWork优秀的设计思想为核心,吸收了Struts1的部分优点,建立了一个基于WebWork和Struts1的MVC框架。
二、搭建Struts2开发环境
2.1、通过官网下载最新版:http://struts.apache.org/download.cgi
建议下载struts-xx.all.zip包,压缩包中不仅包含struts2的jar还包含了示例、源码以及帮助文档。
2.2、在项目中导入Struts2需要的jar包
2.3、修改web.xml文件
在web.xml文件的
struts.xml是Struts2的核心配置文件,该文件通常放在src目录下,编译部署以后,他就到了应用程序的WEB-INF\classes目录下。
三、使用struts2输出Hello World
3.1、新建web项目,并导入struts的jar包
3.2、添加Action类
实现Action可以有三种方法:
1.使用普通的Java类,编写public String execute()方法
2.实现Action接口,实现execute()方法
3.继承ActionSupport类,重写execute()方法。
package com.lxx.action;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport {
private String name;
private String message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
/**
* 这个方法名可以随便写
*
* @return
*/
public String execute() {
System.out.println(name + "-----------------");
message = "Hello World" + name;
return "abc";
}
}
3.3、修改web.xml
index.jsp
contextConfigLocation
classpath*:config/applicationContext.xml
org.springframework.web.context.ContextLoaderListener
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
3.4、在src目录下添加struts.xml,并添加相应的配置
/error.jsp
index.jsp
3.5、修改index.jsp文件
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="/struts-tags" prefix="s" %>
My JSP 'index.jsp' starting page
3.6、将项目添加到tomcat中启动项目,在浏览器中输入:localhost:8080/S2SI(自己的项目名)/testAction就可以看到页面跳转到index.jsp页面,然后在文本框中输入lixiaoxi提交后,在下边输出message。
四、总结
4.1、在浏览器中请求testAction时会经过Struts的核心过滤器“StrutsPrepareAndExecuteFilter”。
4.2、核心过滤器会根据请求在struts.xml中匹配name相同的action,然后会跳转到相应action处理类TestAction类。
4.3、会在TestAction寻找与struts.xml中配置的
4.4、执行完execute()方法后根据返回值String,寻找匹配struts.xml中
4.5、根据类型跳转相应的请求中,上示例定义跳转到index.jsp中,所以会在页面中看到userAction类中execute方法中返回的message值“Hello world ”+name,name是页面提交表单中的值。