struts2入门

2017-05-16  本文已影响0人  長又长

[TOC]

struts2

直译:支柱

在Struts1和webwork框架基础上发展的全新的框架

Struts2核心功能:

1、允许POJO(Plain Old Java Object)对象作为Action
2、Action的execute方法不再与ServletAPI耦合,更易测试
3、支持更多的视图技术(JSP、FreeMarker、Velocity)
4、基于SpringAOP思想的拦截器机制,更易扩展
5、更强大、更易用输入校验机制
6、整合Ajax支持

struts2 入门

导包

bags.png

配置Struts2核心过滤器web.xml

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <filter>
   <filter-name>strust2</filter-name>
   <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
   
  </filter>
  <filter-mapping>
  <filter-name>strust2</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

创建Action继承ActionSupport

public class UserAction extends  ActionSupport {

    
    public String exectute(){
        System.out.println("我是struts2");
        return "ok";
        
    }
    
}

配置Action的访问路径

配置文件名必须是struts.xml,必须放在src下面,xml文件需要引入dtd约束

<?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 name="default" namespace="/" extends="struts-default">
 
        <!--配置action  -->
        <action name="hello" class="com.wxb.action.UserAction"  method="exectute">
        <result name="ok">welcome.jsp</result>
        </action>
    </package>
 </struts>

对应关系

运行流程中的默认:

NOTICE:
在使用父类ActionSupport省略的时候 action里的name 必须为默认的success

异常处理


      <!-- 异常全局处理 -->
        <global-results>
      <result name="error" type="redirect">error.jsp</result>
        </global-results>
       <global-exception-mappings>
        <exception-mapping result="error" exception="java.lang.Exception"></exception-mapping>
        </global-exception-mappings>

拦截器

<1>自带拦截器 modelDriven** Exceptioon等

<2>自定义拦截器
场景举例:统计方法运行时间

-创建自定义拦截器 需继承AbstructInterceptor

-配置 Interceptors

-相应的action方法加上自定义拦截器

-相应的action方法补上default-Stack默认拦截器

动态访问

<action name="user" class="com.wxb.action.UserAction">
      <result name="insertUser" type="redirectAction">user!selectUser</result>
      <result name="deleteUser" type="redirectAction">user!selectUser</result>
      <result name="updateUser" type="redirectAction">user!selectUser</result>
      <result name="selectUser">index.jsp</result>
      </action>
      
上一篇 下一篇

猜你喜欢

热点阅读