JAVAEE——struts2_04:自定義攔截器、struts2標簽、登陸功能和校驗登陸攔截器的實現

来源:http://www.cnblogs.com/xieyupeng/archive/2017/06/18/7045904.html
-Advertisement-
Play Games

一、自定義攔截器 1.架構 2.攔截器創建 3.攔截器api 4.攔截器配置 二、struts2標簽 1.標簽體系 2.struts2標簽結構 3.控制標簽 準備Action然後再到jsp練習struts2標簽 開始練習控制標簽: 4.數據標簽 5.表單標簽 6.非表單標簽 在action中添加錯誤 ...


一、自定義攔截器

  1.架構

  

 

  2.攔截器創建

//攔截器:第一種創建方式
//攔截器生命周期:隨項目的啟動而創建,隨項目關閉而銷毀
public class MyInterceptor implements Interceptor{}

 

//創建方式2: 繼承AbstractInterceptor -> struts2的體貼
//幫我們空實現了init 和 destory方法. 我們如果不需要實現這兩個方法,就可以只實現intercept方法
public class MyInterceptor2 extends AbstractInterceptor{}

 

//創建方式3:繼承MethodFilterInterceptor 方法過濾攔截器
//功能: 定製攔截器攔截的方法.
//    定製哪些方法需要攔截.
//    定製哪些方法不需要攔截
public class MyInterceptor3 extends MethodFilterInterceptor{}

 

  3.攔截器api

        //放行
        String result = invocation.invoke();

 

        //前處理
        System.out.println("MyInterceptor3 的前處理!");
        //放行
        String result = invocation.invoke();
        //後處理
        System.out.println("MyInterceptor3 的後處理!");

 

        //不放行,直接跳轉到一個結果頁面
        //不執行後續的攔截器以及Action,直接交給Result處理結果.進行頁面跳轉
        return "success";

 

  4.攔截器配置

    <package name="inter" namespace="/" extends="struts-default" >
    <interceptors>
    <!-- 1.註冊攔截器 -->
        <interceptor name="myInter3" class="cn.itcast.a_interceptor.MyInterceptor3"></interceptor>
    <!-- 2.註冊攔截器棧 -->
        <interceptor-stack name="myStack">
            <!-- 自定義攔截器引入(建議放在20個攔截器之前) -->
            <interceptor-ref name="myInter3">
                <!-- 指定哪些方法不攔截
                 <param name="excludeMethods">add,delete</param> -->
                 <!-- 指定哪些方法需要攔截 -->
                 <param name="includeMethods">add,delete</param>
            </interceptor-ref>
            <!-- 引用預設的攔截器棧(20個) -->
            <interceptor-ref name="defaultStack"></interceptor-ref>
        </interceptor-stack>    
    </interceptors>
    <!-- 3.指定包中的預設攔截器棧 -->
        <default-interceptor-ref name="myStack"></default-interceptor-ref>
        <action name="Demo1Action_*" class="cn.itcast.a_interceptor.Demo1Action" method="{1}" >
            <!-- 為Action單獨指定走哪個攔截器(棧) 
            <interceptor-ref name="myStack"></interceptor-ref>-->
            <result name="success" type="dispatcher" >/index.jsp</result>
        </action>
    </package>

 

        <!-- 補充知識:定義全局結果集 -->
        <global-results>
            <result name="toLogin" type="redirect" >/login.jsp</result>
        </global-results>

 

二、struts2標簽

  1.標簽體系

 

 

 

  2.struts2標簽結構

 

  3.控制標簽

  準備Action然後再到jsp練習struts2標簽

public class Demo2Action extends ActionSupport {

    public String execute() throws Exception {
        
        List<String> list = new ArrayList<>();
        list.add("tom");
        list.add("jerry");
        list.add("jack");
        list.add("rose");
        list.add("hqy");
        
        ActionContext.getContext().put("list", list);
        return SUCCESS;
    }

}

  開始練習控制標簽:

 <%@ taglib prefix="s" uri="/struts-tags" %>
<!-- 遍歷標簽 iterator -->
<!-- ------------------------------------- -->
<s:iterator value="#list" >
    <s:property /><br>
</s:iterator>
<!-- ------------------------------------- --><hr>
<s:iterator value="#list" var="name" >
    <s:property value="#name" /><br>
</s:iterator>
<!-- ------------------------------------- --><hr>
<s:iterator begin="1" end="100" step="1"  >
    <s:property />|
</s:iterator>
<!-- ------------------if else elseif------------------- --><hr>

<s:if test="#list.size()==4">
    list長度為4!
</s:if>
<s:elseif test="#list.size()==3">
    list長度為3!
</s:elseif>
<s:else>
    list不3不4!
</s:else>

 

  4.數據標簽

<!-- ------------------property 配合ognl表達式頁面取值 ------------------- --><hr>
<s:property value="#list.size()" />
<s:property value="#session.user.name" />

 

  5.表單標簽

    <!-- struts2表單標簽 -->
    <!-- 好處1: 內置了一套樣式.  -->
    <!-- 好處2: 自動回顯,根據棧中的屬性  -->
    <!-- theme:指定表單的主題
            xhtml:預設
            simple:沒有主題
     -->
    <s:form action="Demo3Action" namespace="/" theme="xhtml" >
        <s:textfield name="name" label="用戶名"  ></s:textfield>
        <s:password name="password" label="密碼" ></s:password>
        <s:radio list="{'男','女'}" name="gender" label="性別" ></s:radio>
        <s:radio list="#{1:'男',0:'女'}" name="gender" label="性別" ></s:radio>
        <s:checkboxlist list="#{2:'抽煙',1:'喝酒',0:'燙頭'}" name="habits" label="愛好" ></s:checkboxlist>
        <s:select list="#{2:'大專',1:'本科',0:'碩士'}" headerKey="" headerValue="---請選擇---" name="edu" label="學歷" >
        </s:select>
        <s:file name="photo" label="近照" ></s:file>
        <s:textarea name="desc" label="個人簡介" ></s:textarea>
        <s:submit value="提交" ></s:submit>
    </s:form>

 

  6.非表單標簽

   在action中添加錯誤信息

this.addActionError("我是錯誤信息 哈哈哈");

  取出錯誤信息

    <s:actionerror/>

 

三、練習:登陸功能

  核心代碼:

  Action代碼:

public class UserAction extends ActionSupport implements ModelDriven<User> {
    private User user = new User();
    private UserService us  = new UserServiceImpl();
    
    public String login() throws Exception {
        //1 調用Service 執行登陸操作
        User u = us.login(user);
        //2 將返回的User對象放入session域作為登陸標識
        ActionContext.getContext().getSession().put("user", u);
        //3 重定向到項目的首頁
        return "toHome";
    }

    @Override
    public User getModel() {
        return user;
    }
}

  Service層代碼:

public class UserServiceImpl implements UserService {
    private UserDao ud = new UserDaoImpl();
    @Override
    public User login(User user) {
        //打開事務
        HibernateUtils.getCurrentSession().beginTransaction();
        //1.調用Dao根據登陸名稱查詢User對象
        User existU = ud .getByUserCode(user.getUser_code());
        //提交事務
        HibernateUtils.getCurrentSession().getTransaction().commit();
        
        if(existU==null){
            //獲得不到=>拋出異常提示用戶名不存在
            throw new RuntimeException("用戶名不存在!");
        }
        //2 比對密碼是否一致
        if(!existU.getUser_password().equals(user.getUser_password())){
            //不一致=>拋出異常提示密碼錯誤
            throw new RuntimeException("密碼錯誤!");
        }
        //3 將資料庫查詢的User返回
        return existU;
    }
}

  Dao層代碼:

public class UserDaoImpl implements UserDao {
    @Override
    public User getByUserCode(String user_code) {
        //HQL查詢
        //1.獲得Session
        Session session = HibernateUtils.getCurrentSession();
        //2 書寫HQL
        String hql = "from User where user_code = ? ";
        //3 創建查詢對象
        Query query = session.createQuery(hql);
        //4 設置參數
        query.setParameter(0, user_code);
        //5 執行查詢
        User u = (User) query.uniqueResult();
        return u;
    }
}

 

四、練習:校驗登陸攔截器

  核心代碼:

  攔截器代碼:

public class LoginInterceptor extends MethodFilterInterceptor {
    //指定不攔截登陸方法. 其他方法都攔截
    
    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        
        //1.獲得session
        Map<String, Object> session = ActionContext.getContext().getSession();
        //2.獲得登陸標識
        Object object = session.get("user");
        //3.判斷登陸標識是否存在
        if(object == null){
            //不存在=>沒登錄=>重定向到登錄頁面
            return "toLogin";
        }else{
            //存在=>已經登陸=>放行
            return invocation.invoke();
        }    
    }
}

  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>
    <!-- 指定struts2是否以開發模式運行
            1.熱載入主配置.(不需要重啟即可生效)
            2.提供更多錯誤信息輸出,方便開發時的調試
     -->
    <constant name="struts.devMode" value="true"></constant>
    <package name="crm" namespace="/" extends="struts-default" >
        <interceptors>
            <!-- 註冊攔截器 -->
            <interceptor name="loginInterceptor" class="cn.itheima.web.interceptor.LoginInterceptor"></interceptor>
            <!-- 註冊攔截器棧 -->
            <interceptor-stack name="myStack">
                <interceptor-ref name="loginInterceptor">
                    <param name="excludeMethods">login</param>
                </interceptor-ref>
                <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <!-- 指定包中的預設攔截器棧 -->
        <default-interceptor-ref name="myStack"></default-interceptor-ref>
        <!-- 定義全局結果集 -->
        <global-results>
            <result name="toLogin" type="redirect" >/login.jsp</result>
        </global-results>
        <global-exception-mappings>
            <!-- 如果出現java.lang.RuntimeException異常,就將跳轉到名為error的結果 -->
            <exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>
        </global-exception-mappings>
        
    
        <action name="CustomerAction_*" class="cn.itheima.web.action.CustomerAction" method="{1}" >
            <result name="list" >/jsp/customer/list.jsp</result>
            <result name="toList" type="redirectAction">
                 <param name="actionName">CustomerAction_list</param>
                 <param name="namespace">/</param>
             </result>
        </action>
        <action name="UserAction_*" class="cn.itheima.web.action.UserAction" method="{1}" >
            <result name="toHome" type="redirect" >/index.htm</result>
            <result name="error"  >/login.jsp</result>
        </action>
    </package>
</struts>

  補充知識:檢查當前頁面的父頁面是否是自己,不是的話進行跳轉,解決頁面嵌套問題。

<script type="text/javascript">
    window.onload=function(){
        
        if(window.parent != window){// 如果是在框架中
            //就讓框架頁面跳轉到登陸頁面
            window.parent.location.href = "${pageContext.request.contextPath}/login.jsp";
        }
        
    };
</script>

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1、安裝ElasticSearch https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html 這個頁面有詳細安裝步驟 2、安裝Head插件 head插件可以管理elasticsearch集群,管理 ...
  • 1.新建Netcore Web項目 2.創建簡易通訊協議 SenderID發送者ID ReceiverID 接受者ID MessageType 消息類型 Text Voice 等等 Content 消息內容 3.添加中間件ChatWebSocketMiddleware 4.在Startup.cs中使 ...
  • 現在市面上的編程語言以面向對象為主流。面向對象先要從一些最基本的做起。比如我24歲就結婚了,不然怎麼面向對象編程。然後剛結婚就生娃了,不然對象跑了咋辦?new一個?創建銷毀開銷很大的,還是生個娃持續持有對象的引用的好。 為啥有些人開口說話能說很久,有些人說話有一搭沒一搭的?據我觀察發現,動手幹活差不 ...
  • 首先要導入 包. 下載解壓後, 目錄下有三個包,使用 的話,只需要導入 ,`mchange commons java 0.2.11.jar`. 要連接 資料庫,需要導入 . 為了方便的操作資料庫鏈接進行查詢,需要導入 ,`commons collections 3.2.2.jar commons l ...
  • 原文地址http://www.cnblogs.com/xrq730/p/7003082.html,轉載請註明出處,謝謝 前言 一年半前寫了一篇文章Spring3:AOP,是當時學習如何使用Spring AOP的時候寫的,比較基礎。這篇文章最後的推薦以及回覆認為我寫的對大家有幫助的評論有很多,但是現在 ...
  • //希爾排序 加多一個gap間隔 DEV會崩潰 VC++6.0可以正常運行 #include using namespace std; void InsertSort( int k[], int n ) { int i, j,temp; int gap = n; do { gap = (gap/3)... ...
  • 開始時的首頁 點擊modules 點擊modules界面的Paths 點擊Libraries 選擇lib文件 點擊Facets 選擇項目 這就是我404的主要原因,因為小白第一次使用idea 所以很瘋狂的一直百度,到後面的google搜索,終於在經過1天半的時間找到問題了 web.xml這裡要修改, ...
  • 1.C 和 Java 都是多線程語言。( ) 2.如果線程死亡,它便不能運行。( ) 3.在 Java 中,高優先順序的可運行線程會搶占低優先順序線程。( ) 4.程式開發者必須創建一個線程去管理記憶體的分配。( ) 5.一個線程在調用它的 start 方法,之前,該線程將一直處於出生期。( ) 6.當調 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...