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

1. Custom interceptor

1. Architecture

 

2. Interceptor creation

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

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

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

3. Interceptor api

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

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

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

    <package><interceptors><!-- 1.注册拦截器 --><interceptor></interceptor><!-- 2.注册拦截器栈 --><interceptor-stack><!-- 自定义拦截器引入(建议放在20个拦截器之前) --><interceptor-ref><!-- 指定哪些方法不拦截
                 <param name="excludeMethods">add,delete</param> --> <!-- 指定哪些方法需要拦截 --> <param>add,delete</interceptor-ref><!-- 引用默认的拦截器栈(20个) --><interceptor-ref></interceptor-ref></interceptor-stack>    </interceptors><!-- 3.指定包中的默认拦截器栈 --><default-interceptor-ref></default-interceptor-ref><action><!-- 为Action单独指定走哪个拦截器(栈) 
            <interceptor-ref name="myStack"></interceptor-ref>--><result>/index.jsp</result></action></package>

        <!-- 补充知识:定义全局结果集 --><global-results><result>/login.jsp</result></global-results>

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

}</string>

Start practicing control tags:

 <!-- 遍历标签 iterator --><!-- ------------------------------------- --><iterator><property></property><br></iterator><!-- ------------------------------------- --><hr><iterator><property></property><br></iterator><!-- ------------------------------------- --><hr><iterator><property></property>|</iterator><!-- ------------------if else elseif------------------- --><hr><if>list长度为4!</if><elseif>list长度为3!</elseif><else>list不3不4!</else>

4. Data label

<!-- ------------------property 配合ognl表达式页面取值 ------------------- --><hr><property></property><property></property>

5. Form label

    <!-- struts2表单标签 --><!-- 好处1: 内置了一套样式.  --><!-- 好处2: 自动回显,根据栈中的属性  --><!-- theme:指定表单的主题
            xhtml:默认
            simple:没有主题     --><form>
<textfield></textfield><password></password><radio></radio><radio></radio><checkboxlist></checkboxlist><select></select><file></file><textarea></textarea><submit></submit>
</form>

6. Non-form tags

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

Remove error message

    <actionerror></actionerror>

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

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

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

IV. Exercise: Verify login interception Device

Core code:

Struts.xml configuration file code:

<?xml  version="1.0" encoding="UTF-8"?>nbsp;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></constant><package><interceptors><!-- 注册拦截器 --><interceptor></interceptor><!-- 注册拦截器栈 --><interceptor-stack><interceptor-ref><param>login</interceptor-ref><interceptor-ref></interceptor-ref></interceptor-stack></interceptors><!-- 指定包中的默认拦截器栈 --><default-interceptor-ref></default-interceptor-ref><!-- 定义全局结果集 --><global-results><result>/login.jsp</result></global-results><global-exception-mappings><!-- 如果出现java.lang.RuntimeException异常,就将跳转到名为error的结果 --><exception-mapping></exception-mapping></global-exception-mappings>
    <action><result>/jsp/customer/list.jsp</result><result> <param>CustomerAction_list <param>/ </result></action><action><result>/index.htm</result><result>/login.jsp</result></action></package></struts>

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

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

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
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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools