使用Struts 2 开发程序的基本步骤
1、加载Struts2 类库
需要的maven节点:
<dependency> <groupId>javaee</groupId> <artifactId>javaee-api</artifactId> <version>5</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-core --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.16.3</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.struts.xwork/xwork-core --> <dependency> <groupId>org.apache.struts.xwork</groupId> <artifactId>xwork-core</artifactId> <version>2.3.16.3</version> </dependency>
2、配置web.xml文件
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</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>
3、开发视图层页面
4、开发控制层Action
public class LoginAction implements Action { private String username; private String password; public String execute() throws Exception { if (username.equals("admin")&&password.equals("admin")){ return SUCCESS; }else { return LOGIN; } }
5、配置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> <!-- 配置文件中只要添加以下配置,那么以后修改配置文件不用重启tomcat --> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <!--零散属性装配--> <action name="islogin" class="cn.happy.day01.LoginAction"> <result name="success">day01/index.jsp</result> <result name="login">day01/login.jsp</result> </action> </package> </struts>
web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <filter> <filter-name>struts</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
04.Struts2访问Servlet API
在servlet中可以通过servlet API来获取Session,在Struts中如何获取Session呢?
解析:将用户名放入session 两种方案
1. 与Servlet API解耦的访问方式
--->01.使用ActionContext类获取ServletAPI对象对应的Map对象
--->02.Struts2向Action注入ServletAPI对象对应的Map对象
2. 与Servlet API耦合的访问方式
--->01.通过ActionContext的子类ServletActionContext实现
--->02.向Action实例注入Servlet API对象
解耦方式:
方案一: 对Servlet API进行封装 ,借助ActionContext
供了三个Map对象访问request、session、application作用域
方案二:向Action中注入ServletAPI对象对应的Map对象
耦合方式:
方案一:通过ActionContext的子类ServletActionContext实现
方案二:向Action实例注入Servlet API对象