JavaWeb三大框架之---struts2详解

从今天开始更新javaweb的SSH框架,而后再把三大框架融合。html

1.准备工做java

  从网上下载struts2的源码包,web

2.创建一个web项目。apache

  导入刚刚下载的structs2文件的lib目录下的jar主要有这几个必须包:浏览器

   

3.而后配置web.xml 和strutsxml文件。服务器

在lib目录下创建一个web.xml文件,用来配置过滤器app


<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.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>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
过滤器的名称struts和过滤事物/* 一般都是不用更改。 


而后配置structs文件:框架


<?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>
<constant name="struts.devMode" value="true"></constant>
<!-- 
package元素:定义一个struts的包,面向对象的思想 
name属性:指定包名
extends:当前包的父类,继承


-->
<package name="p1" extends="struts-default">
<action name="hello" class="com.itheima.web.action.HelloAction" method="sayhello">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
jsp

在struts.xml中一般都是利用面向对象的思想来配置事物动做方法和结果。url

action就是拦截器须要加载的动做类和执行的方法。最后经过执行方法返回的结果来执行是否响应。


四、实现一个普通类,以及一个index.jsp和success.jsp文件

类中方法注意事项:

一、必须是返回值为String的

二、必须是无参数的

三、必须是public的,由于拦截器要实例化这个类。私有的话就不能继承执行。

public class HelloAction {//动做类


/*
* 在动做类中制定的动做方法
* 动做方法书写要求
*    1.都是public
*    2.返回必须String,参数必须没有
* @return
*/
public String sayhello(){

System.out.println("HellAction方法执行了");

return "success";//与struts.xml配置文件中的name取值一致
}
}

action动做类有3种实现方式

     1.普通类

     2.implement Action,实现Action接口

     3.继承 ActionSupport(含有一个默认的execute方法)


5.经过index.jsp中响应一个action,而后就会跳转到success.jsp界面


6.分析struts2的启动过程执行过程

     1.启动服务器,服务器会加载项目的web.xml  struts2.xml文件,实现web中的过滤器

     2.浏览器请求-->Tomcat-->拦截器(过滤器)会检测到这个请求,若是有action则拦截,没有则放行---->根据拦截到的action在struts配置文件中去找,找到以后实现该action对应的类,而后执行该类的方法,--->经过方法返回的结果,来决定是否跳转,

通常结果定义如下几种:

*  Action接口中的常量:*  SUCCESS"success" 当执行成功后,前往指定的位置*  NONE"none"不返回任何结果视图,和 return null是同样的*  ERROR"error"当执行动做方法,出现异常后,前往指定的位置*  INPUT"input"数据回显*  LOGIN"login"通常用于返回登陆页面*/