1. 概述
-
官网
https://struts.apache.org/ -
下载
-
特点
在用户请求,模块化处理和页面展现方面发挥强大作用。 -
解压后包中的src/中存放的就是源码。
2. Hello World项目搭建
- 新建项目
- struts2核心包
包名:struts-2.3.16.3-all
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
commons-lang3-3.1.jar
freemarker-2.3.19.jar
javassist-3.11.0.GA.jar
ognl-3.0.6.jar
struts2-core-2.3.16.3.jar
xwork-core-2.3.16.3.jar <----在2.5版本中合并入struts2-core中
- 在web.xml中配置过滤器(拦截所有请求)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>HelloStruts2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.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>
在struts2.5中核心控制器改为了:
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
如果出现如下错误
cvc-complex-type.2.3: Element 'filter-mapping' cannot have character [children], because the type's content type is element-only.
表示在web.xml配置文件中有中文全角空白符,需删除并改为英文半角空格。
- 引入struts.xml配置文件
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>
</struts>
- 编写测试类
程序结构如下:
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>
<package name="helloworld" extends="struts-default">
<!-- 浏览器请求 /hello -->
<!-- action标签将浏览器对/hello的请求映射到HelloWorldAction处理类上(默认的处理方法为execute(),除非用method属性指定处理方法名,如method="add")。 -->
<action name="hello" class="com.bee.action.HelloWorldAction">
<result name="success">helloworld.jsp</result>
</action>
</package>
</struts>
测试类HelloWorldAction
package com.bee.action;
import com.opensymphony.xwork2.Action;
public class HelloWorldAction implements Action {
@Override
public String execute() throws Exception {
System.out.println("执行了Action的默认处理方法");
return SUCCESS; // public static final String SUCCESS = "success";
}
}
helloworld.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
你好Struts2
</body>
</html>
- 运行程序(启动Tomcat server)
打开控制台窗口
添加并部署应用
运行应用(开发期调试)
对应用进行配置
- 程序的运行结果