1.struts2 简介
Struts2 是一种基于MVC模式的轻量级WEB框架,是在Struts1和WebWork技术的基础上进行合并后的全新框架。Struts2 是以WebWork为核心,采用拦截器的机制来处理用户的请求。
1.1 Struts2 入门案例 HelloWorldAction
处理流程如下
(1)创建Web项目
File----->new------->Web Project,项目名暂定chapter
(2)导入Struts2的JAR包
(3)在WEB-INF目录下新建web.xml文件,用于配置Struts2核心过滤器(我是使用的是MyEclipse,是自动创建的)
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 配置Struts2 核心控制器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
在web.xml文件中,filter标签配置的就是核心过滤器,过滤器名为Struts2,过滤器类为
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter,filter-mapping标签配置的是该过滤器的映射
(4) 定义处理类Action
在src下新建一个HelloWorldAction的类,并继承ActionSupport类
package com.songdan.action;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport {
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
}
(5)编写Struts2 配置文件
在src下新建一个struts.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<!-- struts2根元素配置 -->
<struts>
<!-- Struts2 的action 必须放在指定的包空间下定义 -->
<package name="hello" namespace="/" extends="struts-default">
<!-- 定义action,该action 对应类为HelloWorldAction -->
<action name="helloWorld" class="com.songdan.action.HelloWorldAction">
<!-- 定义处理结果和视图资源之间的映射关系 -->
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
(6)创建视图文件
在WebRoot下创建一个index.jsp页面,编写超链接用于访问Action对象,此链接指向的地址为helloWorldAction.action
index.jsp
<%@ page language="java" import="java.util.*"
contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<title>HelloWorld Action</title>
</head>
<body>
<h1>Welcome to Struts2!</h1>
<!-- ${pageContext.request.contextPath}指向工程的WebRoot -->
<a href="$ {pageContext.request.contextPath }/helloWorld.action" >Hello World</a>
</body>
</html>
创建success.jsp,成功后返回的页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>success</title>
</head>
<body>
Hello Struts2
</body>
</html>
启动MyEclispe的tomcat,并把chapter01添加到tomcat上,然后通过浏览器访问http://localhost:8080/chapter01/index.jsp