Struts2
struts2框架应用javaee三层结构中web层框架,struts2框架在struts1和webwork基础之上发展全新的框架。
Struts2框架入门案例
第一步:导入jar包
第二步:创建action,HelloAction
import com.opensymphony.xwork2.ActionSupport;
public class HelloAction extends ActionSupport {
/*
* (1)每次访问servlet时候,都会执行service方法 - 写类继承HttpServlet,重写类里面的方法,在web.xml中配置servlet访问路径
*
* (2)访问action,每次访问action时候,默认执行名称execute方法 - 配置action访问路径
*/
@Override
public String execute() {
return "ok";
}
}
第三步:配置action类访问路径,struts2核心文件struts.xml,位置必须在src目录下
<?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
1、类似于代码包,区别不同的action,要配置action,必须首先写package标签,在package里面才能 配置action
2、package标签属性
(1)name属性
- name属性值跟功能本身没有关系的,在一个配置文件中可以写多个package标签,name属性值不能相同的
(2)extends属性
- 属性值固定的,struts-default
- 写了这个属性之后,在package里面配置的类具有action功能
(3)namespace属性
- namespace属性值和action标签里面的name属性值构成访问路径 -->
<package name="hellodemo" extends="struts-default" namespace="/">
<!-- 标签action
1、action标签配置action访问路径
2、action标签属性
(1)name属性
- namespace属性值和action标签里面的name属性值构成访问路径
- 在package标签里面写多个action标签,但是action的name属性值不能相同的
(2)class属性
- action全路径
(3)method属性
- 比如在action里面默认执行的方法execute方法,但是在action里面写其他的方法,让action里面多个方法执行,使用method进行配置 -->
<action name="hello" class="org.haiwen.action.HelloAction">
<!-- 标签result
1、根据action的方法返回值,配置到不同的路径里面
2、result标签属性
(1)name属性
- 和方法返回值一样
(2)type属性
- 配置如何到路径中(转发或者重定向),type属性默认值做转发操作 -->
<result name="ok">/hello.jsp</result>
</action>
</package>
</struts>
第四步:在web.xml配置struts2过滤器
<?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</display-name>
<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>
第五步:编写访问页面,hello.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>
欢迎光临
</body>
</html>
访问路径:http://localhost:8080/Struts2/hello
也可以在后面加action:http://localhost:8080/Struts2/hello.action
Struts2执行过程
Struts2常量配置
struts2框架帮我们实现一部分功能,struts2里面有常量,在常量里面封装一部分功能。
struts2默认的常量位置
修改struts2默认常量值
1、在struts.xml中进行配置(常用)
<constant name="struts.i18n.encoding" value="UTF-8"></constant>
2、在src下面创建 struts.properties,进行修改
3、在web.xml进行配置
分模块开发
单独写配置文件,把配置文件引入到核心配置文件struts.xml中
引入hello.xml
<include file="org/haiwen/action/hello.xml"></include>