Table of Contents
1. Custom interceptor
1. Architecture
3. Control tags
Dao layer code:
Core code:
Supplementary knowledge: Check whether the parent page of the current page is itself, not If so, jump to solve the page nesting problem.
Home Java javaTutorial JAVAEE - Implementation of custom interceptors, struts2 tags, login functions and verification login interceptors

JAVAEE - Implementation of custom interceptors, struts2 tags, login functions and verification login interceptors

Jun 26, 2017 am 11:46 AM
javaee struts2 intercept customize

1. Custom interceptor

1. Architecture

 

2. Interceptor creation

//拦截器:第一种创建方式//拦截器生命周期:随项目的启动而创建,随项目关闭而销毁public class MyInterceptor implements Interceptor{}
Copy after login

//创建方式2: 继承AbstractInterceptor -> struts2的体贴//帮我们空实现了init 和 destory方法. 我们如果不需要实现这两个方法,就可以只实现intercept方法public class MyInterceptor2 extends AbstractInterceptor{}
Copy after login

//创建方式3:继承MethodFilterInterceptor 方法过滤拦截器//功能: 定制拦截器拦截的方法.//    定制哪些方法需要拦截.//    定制哪些方法不需要拦截public class MyInterceptor3 extends MethodFilterInterceptor{}
Copy after login

3. Interceptor api

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

        //前处理System.out.println("MyInterceptor3 的前处理!");//放行String result = invocation.invoke();//后处理System.out.println("MyInterceptor3 的后处理!");
Copy after login

        //不放行,直接跳转到一个结果页面//不执行后续的拦截器以及Action,直接交给Result处理结果.进行页面跳转return "success";
Copy after login
4. Interceptor configuration

    <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>
Copy after login

        <!-- 补充知识:定义全局结果集 --><global-results><result name="toLogin" type="redirect" >/login.jsp</result></global-results>
Copy after login

2. struts2 tags

1. Tag system

## 2.struts2 tag structure

3. Control tags

Prepare Action and then go to jsp to practice struts2 tags

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;
    }

}
Copy after login

Start practicing control tags:

 <%@ 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>
Copy after login

4. Data label

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

5. Form label

    <!-- 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="{&#39;男&#39;,&#39;女&#39;}" name="gender" label="性别" ></s:radio><s:radio list="#{1:&#39;男&#39;,0:&#39;女&#39;}" name="gender" label="性别" ></s:radio><s:checkboxlist list="#{2:&#39;抽烟&#39;,1:&#39;喝酒&#39;,0:&#39;烫头&#39;}" name="habits" label="爱好" ></s:checkboxlist><s:select list="#{2:&#39;大专&#39;,1:&#39;本科&#39;,0:&#39;硕士&#39;}" 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>
Copy after login

6. Non-form tags

Add error message to action
this.addActionError("我是错误信息 哈哈哈");
Copy after login

Remove error message

    <s:actionerror/>
Copy after login

3. Exercise: Login function

## Core code:

Action code:

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";
    }

    @Overridepublic User getModel() {return user;
    }
}
Copy after login

Service layer code:

public class UserServiceImpl implements UserService {private UserDao ud = new UserDaoImpl();
    @Overridepublic 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;
    }
}
Copy after login

Dao layer code:

public class UserDaoImpl implements UserDao {
    @Overridepublic User getByUserCode(String user_code) {//HQL查询//1.获得SessionSession session = HibernateUtils.getCurrentSession();//2 书写HQLString 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;
    }
}
Copy after login

IV. Exercise: Verify login interception Device

Core code:

Struts.xml configuration file code:

<?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>
Copy after login

Supplementary knowledge: Check whether the parent page of the current page is itself, not If so, jump to solve the page nesting problem.

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

The above is the detailed content of JAVAEE - Implementation of custom interceptors, struts2 tags, login functions and verification login interceptors. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to quickly set up a custom avatar in Netflix How to quickly set up a custom avatar in Netflix Feb 19, 2024 pm 06:33 PM

An avatar on Netflix is ​​a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

How to view Struts2 historical vulnerabilities from a protection perspective How to view Struts2 historical vulnerabilities from a protection perspective May 13, 2023 pm 05:49 PM

1. Introduction The Struts2 vulnerability is a classic series of vulnerabilities. The root cause is that Struts2 introduces OGNL expressions to make the framework flexible and dynamic. With the patching of the overall framework improved, it will now be much more difficult to discover new Struts2 vulnerabilities than before. Judging from the actual situation, most users have already repaired historical high-risk vulnerabilities. Currently, when doing penetration testing, Struts2 vulnerabilities are mainly left to chance, or it will be more effective to attack unpatched systems after being exposed to the intranet. Online analysis articles mainly analyze these Struts2 vulnerabilities from the perspective of attack and exploitation. As the new H3C offense and defense team, part of our job is to maintain the rule base of ips products. Today we will review this system.

How to customize background image in Win11 How to customize background image in Win11 Jun 30, 2023 pm 08:45 PM

How to customize background image in Win11? In the newly released win11 system, there are many custom functions, but many friends do not know how to use these functions. Some friends think that the background image is relatively monotonous and want to customize the background image, but don’t know how to customize the background image. If you don’t know how to define the background image, the editor has compiled the steps to customize the background image in Win11 below. If you are interested If so, take a look below! Steps for customizing background images in Win11: 1. Click the win button on the desktop and click Settings in the pop-up menu, as shown in the figure. 2. Enter the settings menu and click Personalization, as shown in the figure. 3. Enter Personalization and click on Background, as shown in the picture. 4. Enter background settings and click to browse pictures

How to create and customize Venn diagrams in Python? How to create and customize Venn diagrams in Python? Sep 14, 2023 pm 02:37 PM

A Venn diagram is a diagram used to represent relationships between sets. To create a Venn diagram we will use matplotlib. Matplotlib is a commonly used data visualization library in Python for creating interactive charts and graphs. It is also used to create interactive images and charts. Matplotlib provides many functions to customize charts and graphs. In this tutorial, we will illustrate three examples to customize Venn diagrams. The Chinese translation of Example is: Example This is a simple example of creating the intersection of two Venn diagrams; first, we imported the necessary libraries and imported venns. Then we create the dataset as a Python set, after that we use the "venn2()" function to create

How to create custom pagination in CakePHP? How to create custom pagination in CakePHP? Jun 04, 2023 am 08:32 AM

CakePHP is a powerful PHP framework that provides developers with many useful tools and features. One of them is pagination, which helps us divide large amounts of data into several pages, making browsing and manipulation easier. By default, CakePHP provides some basic pagination methods, but sometimes you may need to create some custom pagination methods. This article will show you how to create custom pagination in CakePHP. Step 1: Create a custom pagination class First, we need to create a custom pagination class. this

render function in Vue3: custom rendering function render function in Vue3: custom rendering function Jun 18, 2023 pm 06:43 PM

Vue is a popular JavaScript framework that provides many convenient functions and APIs to help developers build interactive front-end applications. With the release of Vue3, the render function has become an important update. This article will introduce the concept and purpose of the render function in Vue3 and how to use it to customize the rendering function. What is the render function? In Vue, template is the most commonly used rendering method, but in Vue3, you can use another method: r

How to customize shortcut key settings in Eclipse How to customize shortcut key settings in Eclipse Jan 28, 2024 am 10:01 AM

How to customize shortcut key settings in Eclipse? As a developer, mastering shortcut keys is one of the keys to improving efficiency when coding in Eclipse. As a powerful integrated development environment, Eclipse not only provides many default shortcut keys, but also allows users to customize them according to their own preferences. This article will introduce how to customize shortcut key settings in Eclipse and give specific code examples. Open Eclipse First, open Eclipse and enter

How to enable and customize crossfades in Apple Music on iPhone with iOS 17 How to enable and customize crossfades in Apple Music on iPhone with iOS 17 Jun 28, 2023 pm 12:14 PM

The iOS 17 update for iPhone brings some big changes to Apple Music. This includes collaborating with other users on playlists, initiating music playback from different devices when using CarPlay, and more. One of these new features is the ability to use crossfades in Apple Music. This will allow you to transition seamlessly between tracks, which is a great feature when listening to multiple tracks. Crossfading helps improve the overall listening experience, ensuring you don't get startled or dropped out of the experience when the track changes. So if you want to make the most of this new feature, here's how to use it on your iPhone. How to Enable and Customize Crossfade for Apple Music You Need the Latest

See all articles