Home  >  Article  >  Java  >  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

巴扎黑
巴扎黑Original
2017-06-26 11:46:232150browse

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

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

}

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>

4. Data label

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

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>

6. Non-form tags

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

Remove error message

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

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"?><!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>

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>

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