下载Struts2的开发包,并解压开发包
- apps :Struts2提供一些项目。
- docs :Struts2提供的开发规范和文档
- lib :Struts2提供的开发jar包
- src :Struts2提供的源代码
打开apps,把struts2-blank.war文件的后缀变为rar
解压struts2-blank.rar文件
创建web工程把struts2-blank\WEB-INF\lib里面的jar包导入项目
创建一个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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/hello">我的第一个Strut2程序</a>
</body>
</html>
在项目中/Struts2/WebContent/WEB-INF/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>Struts2_01</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>
编写Action类
public class Hello {
public String execute() {
System.out.println("第一个Struts2程序");
return "hello";
}
}
配置Action
在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">
<struts>
<!--
配置package包
* name :包的名称
* extends :继承其他的包
* namespace :名称空间
-->
<package name="com.it.test" extends="struts-default" namespace="/">
<!--
配置Action
* name :访问路径
* class :Action类的全路径
-->
<action name="hello" class="com.it.test.Hello">
<!-- name属性 要和action返回的别名(逻辑视图名)进行匹配
标签体内容 要跳转的页面地址
type属性 设置是用重定向还是用请求转发
默认是请求转发 -->
<result name="hello">/HelloStruts2.jsp</result>
</action>
</package>
</struts>
在/Struts2/WebContent/下创建一个jsp界面来实现转发:HelloStruts2.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Hello Struts2~~</h1>
</body>
</html>
把项目部署到tomcat服务器
在浏览器输入地址http://localhost:8080/Struts2/
点击连接
完成~~
一般出错都是配置action的时候地址写的不对,注意你的连接地址和你的<action name="hello" class="com.it.test.Hello">要匹配
最终的项目结构