1.搭建第一个struts2 app.
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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <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> </web-app>
注:struts1框架由servlet启动,strust2框架由filter启动
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts>
<!-- Add packages here -->
<package name="alibaba" extends="struts-default" namespace="/alibaba">
<action name="helloWorld" method="excute" class="com.alibaba.struts2.HelloWorld">
<result name="success">/WEB-INF/page/helloWorld.jsp</result>
</action>
</package>
</struts>
注:extends="struts-default",是关键。使用struts2框架核心功能,比如说文件上传等。需要继承struts2-default 这个包
在struts-default.xml文件中可以看到
<package name="struts-default" abstract="true">
....
<interceptor name="alias" class="com.opensymphony.xwork2.interceptor.AliasInterceptor"/>
.....
拦截器是struts的核心。
action
package com.alibaba.struts2; public class HelloWorld
{ private String msg; public String getMessage()
{
return msg;
} public String excute()
{
this.msg = "Hello,This is my frist struts2 app.";
return "success";
} }
jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'helloWorld.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
${message}
</body>
</html>
注:EL表达式中的参数和action中的getMessage()中的Message要一致。