Struts2框架创建web项目的6个步骤
1.创建WEB项目
2.导入Struts2核心jar包
3.在web.xml文件中配置前端控制器filter
※如果Struts2框架是2.1.3之后的版本,版本核心控制器为org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter。
※如果Struts2框架是2.1.3之前的版本,版本核心控制器为org.apache.struts2.dispatcher.FilterDispatcher。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0"><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>
4.编写Jsp前端页面
5.编写处理请求的Action类
1.创建Action类
2.编写业务方法
6.配置Struts.xml
1.体现请求与Action的关系
2.体现Action与Jsp的关系
<?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="default" namespace="/" extends="struts-default"><action name="helloWorld" class="action.HelloWorldAction" method="sayHelloWorld"><result name="ok">/hello.jsp</result></action></package>
</struts>
1.<package>元素:定义包,用于封装action
<package name="default" namespace="/default" extends="struts-default">
</package>
name:包名,用于识别这个包,下可以有多个,它们的名称不要重复。
namespace:包的命名空间,用于URL进行访问的,注意以/开头。
extends:包的继承,可以继承其它的包。当继承其他包时,相当于把继承的包下定义的内容全部copy到当前包下了。
2.<action>元素:定义action,用于注册业务控制器
<action name="helloWorld" class="action.HelloWorldAction" method="sayHelloWorld">
</action>
name:action的名称,用于访问action,每个package下可以有多个action,这些action之间不要重名。
class:action对应的类。
method:要调用的业务方法名。
3.<result>元素:定义result,找到Jsp页面
<result name="ok">/hello.jsp</result>
name:result的名称,根据Action类的返回值,Struts2会自动在此action配置下找到与之对应的result,从而找到result下定义的Jsp页面
我寻见一片海 碧蓝且耀着光
大片船只航行其上 都向着远方
Shared by Foriver_江河