**自定义拦截器和配置**
1.编写拦截器,需要实现Interceptor接口,实现接口中的三个方法。
* interceptor接口有很多的实现类,编写最简单的方式就是继承AbstractInterceptor实现类。
* 代码例如:
public String intercept(ActionInvocation invocation) throws Exception {
User user = (User) ServletActionContext.getRequest().getSession().getAttribute("existUser");
if(user == null){
ActionSupport as = (ActionSupport) invocation.getAction();
as.addActionError("您没有登陆!");
return as.LOGIN;
}else{
// 放行
return invocation.invoke();
}
}
* 需要在struts.xml中进行拦截器的配置,配置一共有两种方式:
> 第一种方式
* 在<package>包中定义拦截器,出现在<package>包的上方
<interceptors>
<interceptor name="loginInterceptor" class="cn.itcast.interceptor.LoginInterceptor"></interceptor>
</interceptors>
* 在某个action中引入拦截器
<interceptor-ref name="loginInterceptor"></interceptor-ref>
* 注意:如果引入了自己定义的拦截器,那么Struts2框架默认的拦截器就不会再执行了,所以需要引入Struts2默认的拦截器。
<interceptor-ref name="defaultStack"></interceptor-ref>
> 第二种方式
* 在<package>包中定义拦截器的时候,自己直接定义一个拦截器栈
<interceptors>
<interceptor name="loginInterceptor" class="cn.itcast.interceptor.LoginInterceptor"/>
<interceptor-stack name="myStack">
<interceptor-ref name="loginInterceptor"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
* 在Action包中引入自己定义的拦截器栈
<action name="book_*" class="cn.itcast.action.BookAction" method="{1}">
<interceptor-ref name="myStack"/>
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>
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<!-- 用户的模块 -->
<package name="user" extends="struts-default" namespace="/">
<!-- 自定义拦截器 -->
<!-- <interceptors>
<interceptor name="UserInterceptor" class="interceptor.UserInterceptor"></interceptor>
</interceptors> -->
<!-- 自定义拦截器栈,引入自己的拦截器和默认栈的拦截器 -->
<interceptors>
<interceptor name="UserInterceptor" class="interceptor.UserInterceptor"></interceptor>
<!-- 自定义拦截器栈 -->
<interceptor-stack name="myStack">
<interceptor-ref name="UserInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="user_*" class="action.UserAction" method="{1}">
<result name="input">/pages/login.jsp</result>
<result name="success" type="redirect">/pages/suc.jsp</result>
</action>
<!-- 配置图书的action -->
<action name="book_*" class="action.BookAction" method="{1}">
<result name="input">/pages/login.jsp</result>
<!-- 引入拦截器,默认的栈不执行了-->
<!-- <interceptor-ref name="UserInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref> -->
<!-- 引入自己定义的拦截器栈 -->
<interceptor-ref name="myStack"></interceptor-ref>
</action>
</package>
</struts>
login.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>用户登录></h3>
<s:fielderror/>
<s:actionerror/>
<form action="${ pageContext.request.contextPath }/user_login.action" method="post">
姓名:<input type="text" name="username" /><br/>
密码:<input type="password" name="password" /><br/>
<input type="submit" value="登录" />
</form>
</body>
</html>
UserAction:
package action;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import domain.User;
import service.UserService;
/**
* 用户的控制器
* @author mjl
*
*/
public class UserAction extends ActionSupport implements ModelDriven<User>{
private User user=new User();
public User getModel() {
return user;
}
public String login(){
//调用业务层
UserService us=new UserService();
User existUser=us.login(user);
//判断是否登录
if(existUser==null){
//登录失败
this.addActionError("用户名和密码不匹配");
return INPUT;
}else{
//成功,把用户存入session
ServletActionContext.getRequest().getSession().setAttribute("existUser", existUser);
return SUCCESS;
}
}
}
UserDao:
package dao;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import domain.User;
import utils.MyJdbcUtils;
public class UserDao {
public User login(User user) {
QueryRunner runner=new QueryRunner(MyJdbcUtils.getDataSource());
String sql="select * from user where username=? and password=?";
try {
return runner.query(sql, new BeanHandler<User>(User.class),user.getUsername(),user.getPassword());
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
自定义拦截器:判断用户是否已经登录
package interceptor;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import domain.User;
/**
* 自定义的拦截器(判断用户是否已经登录)
* @author mjl
*
*/
public class UserInterceptor extends AbstractInterceptor {
/**
* 做拦截的
*/
public String intercept(ActionInvocation ai) throws Exception {
/**
* 判断用户是否已经登录
*/
User user = (User) ServletActionContext.getRequest().getSession().getAttribute("existUser");
if(user==null){
//说明用户没有登录,手动跳转到登录页面
//获取到目标action
ActionSupport as=(ActionSupport) ai.getAction();
//向异常的区域中存入信息
as.addActionError("请您登录!!");
//跳转到当前的action的input视图
return as.INPUT;
}else{
//说明用户已经登录,调用下一个拦截器
return ai.invoke();
}
}
}
校验器:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="username">
<field-validator type="requiredstring">
<message>亲,用户名不能为空</message>
</field-validator>
</field>
<field name="password">
<field-validator type="requiredstring">
<message>亲,密码不能为空的!</message>
</field-validator>
<field-validator type="stringlength">
<param name="minLength">2</param>
<param name="maxLength">6</param>
<message>亲,密码需要在2到6位之间</message>
</field-validator>
</field>
</validators>
suc.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>系统的主页</h2>
<c:if test="${not empty existUser }">
<h3>登录成功页面:${ existUser.username }</h3>
</c:if>
<c:if test="${empty existUser }">
<h3><a href="${pageContext.request.contextPath }/pages/login.jsp">请登录</a></h3>
</c:if>
<h4>图书管理</h4>
<h3><a href="${pageContext.request.contextPath }/book_del.action">删除图书</a></h3>
<h3><a href="${pageContext.request.contextPath }/book_sel.action">查看图书</a></h3>
</body>
</html>
BookAction:
package action;
import com.opensymphony.xwork2.ActionSupport;
public class BookAction extends ActionSupport{
public String del(){
return NONE;
}
public String sel(){
return NONE;
}
}