Struts2
struts2是一个基于MVC设计模式的Web应用框架,它本质上相当于一个servlet,在MVC设计模式中,struts2作为控制器(Controller)来建立模型与视图的数据交互。Struts2是Struts的下一代产品,是在Struts的下一代产品,是在Struts1和WebWork的技术基础上进行了合并的全新的Struts2框架,其全新的Struts2的体系结构和Struts1的体系结构差别巨大。Struts2以WebWork为核心。采用拦截器的机制来处理用户的请求。这样的设计也使得业务逻辑控制器能够与ServletAPI完全脱离开,所以Struts2可以理解为WebWork的更新产品。虽然从Struts1到Struts1有着太大的变化,但是相对于WebWork,Struts2的变化很小。
Struts2是一个基于MVC设计模式的Web层框架
常见的web层框架:
- Struts1
- Struts2
- WebWork
- SpringMVC
Web层框架的特点:前端控制器模式(核心的控制器)
入门程序
编写jsp页面
hello.jsp
<body>
<!-- struts2框架默认处理后缀名为.action的请求 -->
<a href="${pageContext.request.contextPath }/hello.action">hello请求</a>
</body>
result.jsp
<body>
<h1>hello result</h1>
</body>
编写Action
package com.feng_01_hello;
import com.opensymphony.xwork2.Action;
public class HelloAction implements Action {
//HelloAction类实现Action接口后,执行HelloAction的时候默认执行execute()方法
//类似post请求执行doPost方法,返回的String类型是返回结果集
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println("执行了HelloAction");
//返回逻辑视图
return "success";
}
}
配置web文件web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID" version="4.0">
<display-name>Struts2-1</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>
<!-- 配置struts2的过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<!-- 路径 -->
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
在src目录下新建xml文件,并命名为struts.xml(必须是struts.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<!-- <a href="${pageContext.request.contextPath }/hello.action">hello请求</a>
namespace="/"表示hello.action前的/(访问路径) -->
<package name="default" extends="struts-default" namespace="/">
<!-- name="hello" 对应请求路径中的hello.action,不用写后缀名 -->
<action name="hello"
class="HelloAction">
<!-- name="success" 对应action中的返回值 -->
<result name="success">/result.jsp</result>
</action>
</package>
</struts>
启动tomcat,运行hello.jsp程序
测试结果
相当的生气了,之前就有接触过struts2,但是今天就按照老师说的做,一直出错,一开始说找不到action,后来连hello.jsp页面都显示404,找了网上很多例子,都是检查过了并卵用,我也不是粗心之人。最后说新建个工程,然后全都复制过去。吊,运行成功了。我也是醉了。一个下午就为了搞个helloword。有点炸。再加上昨天的mybatis的逆袭工程也没搞好,以至于没做笔记记录。之后再找时间重做逆向工程