所有的学习我们必须先搭建好Struts2的环境(1、导入对应的jar包,2、web.xml,3、struts.xml)
第一节:拦截器简介
(百度百科Struts2)
Struts2 拦截器是在访问某个Action 或Action 的某个方法,字段之前或之后实施拦截,并且Struts2 拦截器是可
插拔的,拦截器是AOP的一种实现.
优点:通用功能的封装,提供了可重用性;
第二节:Struts2 预定义拦截器&拦截器栈
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="manage" namespace="/" extends="struts-default"> <interceptors>
<interceptor name="myInterceptor" class="com.wishwzp.interceptor.MyInterceptor"></interceptor>
</interceptors> <action name="hello" class="com.wishwzp.action.HelloAction">
<result name="success">success.jsp</result> <interceptor-ref name="myInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
</package> </struts>
struts.xml
package com.wishwzp.interceptor; import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor; public class MyInterceptor implements Interceptor{ @Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("MyInterceptor销毁");
} @Override
public void init() {
// TODO Auto-generated method stub
System.out.println("MyInterceptor初始化");
} @Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("在Action执行之前");
String result=invocation.invoke();
System.out.println("result:"+result);
System.out.println("在Action执行之后");
return result;
} }
MyInterceptor.java
package com.wishwzp.action; import com.opensymphony.xwork2.ActionSupport; public class HelloAction extends ActionSupport{ /**
*
*/
private static final long serialVersionUID = 1L; private String name; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Override
public String execute() throws Exception {
System.out.println("执行了HelloAction的默认方法");
return SUCCESS;
} }
HelloAction.java
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
Name:${name }
</body>
</html>
success.jsp
url:http://localhost:8080/Struts2Chap03/hello?name=Struts2
我们需要注意的是在MyInterceptor.java中的:
String result=invocation.invoke();
第三节:自定义拦截器简单实例
我们在第二节中“MyInterceptor.java”中已经是自己定义的拦截器了
第四节:自定义拦截器-登录验证拦截器
struts.xml
1 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="manage" namespace="/" extends="struts-default"> <interceptors>
<interceptor name="loginInterceptor" class="com.wishwzp.interceptor.LoginInterceptor"></interceptor>
</interceptors> <action name="user" class="com.wishwzp.action.UserAction">
<result name="success">success.jsp</result>
<result name="error">error.jsp</result>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action> <action name="gril" class="com.wishwzp.action.GrilAction">
<result name="success">success.jsp</result>
<result name="error">error.jsp</result>
<interceptor-ref name="loginInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
</package> </struts>
User.java
1 package com.wishwzp.model; public class User { private String userName;
private String password; public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserService.java
1 package com.wishwzp.service; import com.wishwzp.model.User; public class UserService { public boolean login(User user){
if("wishwzp".equals(user.getUserName())&&"123".equals(user.getPassword())){
return true;
}else{
return false;
}
}
}
UserAction.java
1 package com.wishwzp.action; import java.util.Map; import com.wishwzp.model.User;
import com.wishwzp.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport{ /**
*
*/
private static final long serialVersionUID = 1L; private UserService userService=new UserService();
private User user;
private String error; public User getUser() {
return user;
} public void setUser(User user) {
this.user = user;
} public String getError() {
return error;
} public void setError(String error) {
this.error = error;
} @Override
public String execute() throws Exception {
if(userService.login(user)){
ActionContext actionContext=ActionContext.getContext();//获取上下文,去获取actionContext
Map<String, Object> session=actionContext.getSession();//通过actionContext去获取session
session.put("currentUser", user);//将用户存放在session中,就是放到了currentUser
return SUCCESS;//返回到SUCCESS
}else{
this.error="用户名或密码错误";
return "error";
}
} }
GrilAction.java
1 package com.wishwzp.action; import com.opensymphony.xwork2.ActionSupport; public class GrilAction extends ActionSupport{ /**
*
*/
private static final long serialVersionUID = 1L;
@Override
public String execute() throws Exception {
System.out.println("看美女");
return SUCCESS;
} }
LoginInterceptor.java
1 package com.wishwzp.interceptor; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor; public class LoginInterceptor implements Interceptor{ @Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("LoginInterceptor销毁");
} @Override
public void init() {
// TODO Auto-generated method stub
System.out.println("LoginInterceptor初始化");
} @Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("在Action执行之前");
ActionContext actionContext=invocation.getInvocationContext();//获取actionContext,这样就可以获取session了
Map<String, Object> session=actionContext.getSession();//获取session
Object currentUser=session.get("currentUser");//获取前面的的用户有没有
String result=null;
if(currentUser!=null){
result=invocation.invoke();//不是空的话,说明已经登录过了
}else{//否则没有登录
//获取request
HttpServletRequest request=(HttpServletRequest)invocation.getInvocationContext().get(ServletActionContext.HTTP_REQUEST);
request.setAttribute("error", "请先登录!");
result="error";
}
System.out.println("result:"+result);
System.out.println("在Action执行之后");
return result;
} }
login.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<form action="user" method="post">
用户名:<input type="text" name="user.userName"/>
密码:<input type="password" name="user.password"/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
success.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
当前用户:${currentUser.userName }
</body>
</html>
error.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
错误信息:${error } <a href="login.jsp">登录</a>
</body>
</html>
url:http://localhost:8080/Struts2Chap03/login.jsp
url:http://localhost:8080/Struts2Chap03/gril
我们再上面的代码中优化一下strut.xml。
其他什么地方都不变
struts.xml
1 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="manage" namespace="/" extends="struts-default"> <interceptors>
<!-- 配置loginInterceptor拦截器 -->
<interceptor name="loginInterceptor" class="com.wishwzp.interceptor.LoginInterceptor"></interceptor> <!-- 拦截器栈 -->
<!-- 配置一个名为myStack的拦截器栈,里面有拦截器loginInterceptor和默认的拦截器 -->
<interceptor-stack name="myStack">
<interceptor-ref name="loginInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors> <!-- 配置使用自己配置的默认拦截器myStack -->
<default-interceptor-ref name="myStack"></default-interceptor-ref> <!-- 使用全局错误信息,就不需要去一个个写error了 ,所有的action都会找到这个全局error的-->
<global-results>
<result name="error">error.jsp</result>
</global-results> <action name="user" class="com.wishwzp.action.UserAction">
<result name="success">success.jsp</result> <!-- 这个默认拦截器栈这里必须有,不然的话这里的登录也被拦截掉了 -->
<interceptor-ref name="defaultStack"></interceptor-ref>
</action> <action name="gril" class="com.wishwzp.action.GrilAction">
<result name="success">success.jsp</result>
</action>
</package> </struts>