JavaEE struts2框架
创建一个struts2框架一般有如下三个步骤:
1.导入需要的jar包
2.配置web.xml文件
3.创建struts.xml文件并配置
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_3_1.xsd" id="WebApp_ID" version="3.1">
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
struts.xml的配置一般如下:
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- package:包,struts2使用package来组织模块 name 属性:必须,用于其它的包引用当前包 extends:当前包继承哪个包,继承的,即可以继承其中的所有配置。通常情况下继承struts-default namespace:可选,如果没给出,则默认“/”为默认值 若namespace有一个非默认值,则要想调用这个包里的action,就必须把这个属性所定义的命名空间添加到有关的URI字符串里 http://localhost:8080/contextPath/namespace/actionName.action --> <package name="helloWorld" extends="struts-default" namespace="/"> <!-- 配置一个action:一个struts2的请求就是一个action name对应一个struts请求的名字(或者对应servletPath但去除“/”和扩展名),不包含扩展名 class 的默认值为:com.opensymphony.xworks.ActionSupport method的默认值为:execute() --> <action name="product-input"> <!-- result:结果 表示action方法执行后可能返回的一个结果,所以一个action节点可能会有多个result子节点。 多个result子节点使用name来区分。 name:标识一个result,和action方法的返回值对应,默认为success type:标示结果的类型,默认值为dispatcher(转发到结果) --> <result>/pages/input.jsp</result> </action> <action name="product-save" class="com.atguigu.strutsHelloWorld.Product" method="save"> <result name="details">/pages/details.jsp</result> </action> </package> </struts>
action VS Action类
action:代表一个struts2的请求
Action类:能够处理Struts2请求的类(因为result绑定了Person类的save方法的返回值,所以Person类就是一个Action类)
> 属性的名字必须遵守与JavaBeans属性名相同的命名规则
属性的类型可以是任意类型,从字符串到非字符串(基本数据库类型)之间的数据转换可以自动发生
> 必须有一个不带参的构造器(因为action里面的class属性是通过类名的反射创建的)
>至少有一个供struts2在执行这个action时调用的方法(一个Action类可以应答多个请求)
>同一个Action类可以包含多个action方法
>Struts2会为每一个HTTP请求创建一个新的Action实例,即Action不是单例的,是线程安全的。



浙公网安备 33010602011771号