1.自定义struts拦截器

  应用场景:如果用户登陆后可以访问action中的所有方法,如果用户没有登陆不允许访问action中的方法,并且提示“你没有操作权限”

  1)两个页面,一个用户登陆user.jsp,一个用户退出quit.jsp,都放在WebRoot目录下

<%@ page language="java" import="java.util.*"    pageEncoding="UTF-8"%>
<%
request.getSession().setAttribute("user","itcast");
%>
用户已经登陆
<%@ page language="java" import="java.util.*"    pageEncoding="UTF-8"%>
<%
request.getSession().removeAttribute("user");
%>
用户已经退出登陆

  2)新建一个Action用于访问

package cn.itcast.action;

import java.util.Date;

import javax.xml.registry.infomodel.PersonName;

public class HelloWorld {
private String message; public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public String execute() throws Exception{
message="execute";
return "SUCCESS";
} public String add() throws Exception{
message="add";
return "SUCCESS";
} }

  3)新建拦截器,当session中user有值的时候说明已经登陆,就调用invocation.invoke(),如果没有值,说明没有登陆,返回SUCCESS视图,将提示信息放在request范围

package cn.itcast.action;

import java.util.Date;

import javax.xml.registry.infomodel.PersonName;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;
import com.sun.xml.internal.bind.v2.model.core.ID; public class PermissionInterception implements Interceptor{ /**
*
*/
private static final long serialVersionUID = 1L; public void destroy() {
// TODO Auto-generated method stub } public void init() {
// TODO Auto-generated method stub } public String intercept(ActionInvocation invocation) throws Exception {
Object user = ActionContext.getContext().getSession().get("user");
if(user!=null){
return invocation.invoke();
}
ActionContext.getContext().put("message", "没有权限");
return "SUCCESS"; //返回到message视图
} }

  4)配置struts.xml,重点是配置拦截器栈,并引用

<?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>
<constant name="struts.action.extension" value="do,action"></constant>
<package name="itcast" namespace="/test" extends="struts-default" >
<interceptors>
<interceptor name="permission" class="cn.itcast.action.PermissionInterception"></interceptor>
<interceptor-stack name="permissionStack">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="permission"></interceptor-ref>
</interceptor-stack>
</interceptors>
<global-results>
<result name="SUCCESS">/WEB-INF/pages/message.jsp</result>
</global-results>
<action name="list_*" class="cn.itcast.action.HelloWorld" method="{1}">
<interceptor-ref name="permissionStack"></interceptor-ref>
</action>
</package>
</struts>

2.对Action中所有方法进行输入校验

  1)新建index页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%@ taglib  uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0"> </head> <body>
<s:fielderror/>
<form action="${pageContext.request.contextPath }/test/list_save.action" method="post">
用户名:<input type="text" name="username"><br/>
手机号:<input type="text" name="mobile"><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
  这里引用struts的标签<s:fielderror/><%@ taglib uri="/struts-tags" prefix="s" %>,来显示校验的信息
  2)struts.xml,配置input页面用来显示fielderror里的校验提示信息
<?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="itcast" namespace="/test" extends="struts-default" >
<action name="list_*" class="cn.itcast.action.Hello" method="{1}">
<result name="message">/WEB-INF/pages/message.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>

  3)Action的代码,action继承ActionSupport,重写validate()方法,validate()方法会校验所有与execute方法签名相同的方法,当某个数据校验失败时,我们应该调用addFieldError();方法往系统的fielderror添加校验失败信息,如果系统的fielderror包含失败信息,struts2会将请求转发到名为input的result。在input视图中通过<s:fielderror/>来显示失败信息

package cn.itcast.action;

import java.util.regex.Pattern;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport; public class Hello extends ActionSupport{
private String username;
private String mobile;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String save(){
ActionContext.getContext().put("message", "保存成功");
return "message";
}
public String update(){
ActionContext.getContext().put("message", "更新成功");
return "message";
}
@Override
public void validate() {
if(this.username==null||"".equals(this.username.trim())){
this.addFieldError("username", "用户名不能为空");
}
if(this.mobile==null||"".equals(this.mobile.trim())){
this.addFieldError("mobile", "手机号不能为空");
}else {
if(!Pattern.compile("^1[358]\\d{9}$").matcher(this.mobile).matches()){
this.addFieldError("mobile", "手机号格式不正确");
}
}
} }

  4)当请求的action改为update时也能进行校验,说明validate方法可以对action中的所有方法进行校验

3.对Action中指定方法进行校验,就是将validate方法名称改为validateXxx如:validateSave(S大写),就是对save方法进行校验

4.输入校验的流程

  1)类型转换器对请求参数执行类型转换,并把转换后的值赋给Action中的属性

  2)如果在执行类型转换的过程中出现异常,系统会将异常信息保存在ActionContext,conversionError拦截器将异常信息添加到fieldErrors里,不管类型转换是否出现异常都会进入第三步

  3)系统通过反射技术先调用action中的validateXxx方法,Xxx为方法名

  4)再调用action中的validate方法

  5)经过上面4步,如果系统的fieldErrors中存在错误信息,系统系统将请求转发至input视图。如果系统中不存在任何错误信息,系统将执行action中的处理方法

struts2笔记4的更多相关文章

  1. struts2笔记(3)

    关于回显: 如果是int型,默认就会回显为0,如果不想让回显,则Integer就好 //**************************************声明式验证************* ...

  2. struts2笔记(2)

    <context-param> <param-name>pattern</param-name> <param-value>yyyy-MM-dd hh: ...

  3. struts2笔记

    Struts2 中, HTML 表单将被直接映射到一个 POJO,通过params拦截器,类中定义对应属性,及对应set方法即可. Struts2 中,任何一个POJO都可以是一个action类. S ...

  4. struts2 笔记04 杂记

    流程: 1. StrutsPrepareAndExcuteFilter:StrutsPrepareAndExcuteFilter作为前端控制器,是整个Struts2的调度中心. 2. ActionMa ...

  5. struts2 笔记03 异常支持、防止页面刷新和后退、方法验证

    Struts2对异常支持(声明式异常.自动的异常处理), 异常处理(运行期异常事务自动回滚) 1. 自定义异常类,继承RuntimeException或Exception实现构造方法. 2. 配置异常 ...

  6. struts2 笔记02 文件上传、文件下载、类型转换器、国际化的支持

    Struts2的上传 1. Struts2默认采用了apache commons-fileupload  2. Struts2支持三种类型的上传组件 3. 需要引入commons-fileupload ...

  7. struts2 笔记01 登录、常用配置参数、Action访问Servlet API 和设置Action中对象的值、命名空间和乱码处理、Action中包含多个方法如何调用

    Struts2登录 1. 需要注意:Struts2需要运行在JRE1.5及以上版本 2. 在web.xml配置文件中,配置StrutsPrepareAndExecuteFilter或FilterDis ...

  8. Struts2笔记——利用token防止表单重复提交

    在一些项目中经常会让用户提交表单,当用户点击按钮提交后,如果再次浏览器刷新,这就会造成表单重复提交,若是提交的内容上传至服务器并请求数据库保存,重复提交的表单可能会导致错误,然后跳转到错误界面,这是一 ...

  9. Struts2笔记——struts常用标签

    使用struts标签前,首先要配置struts2架构,然后导入标签库,jsp插入如下语句: <%@taglib uri="/struts-tags" prefix=" ...

随机推荐

  1. javascrit2.0完全参考手册(第二版) 第2章第2节 语言特性

    脚本执行顺序     js代码是按照它们在html中出现的顺序一行一行被解释的.这表明把函数定义和变量声明放到<head>中会很好.这保证了函数的代码和事件相关的处理程序不会立即执行. 大 ...

  2. (转)as3效率优化

    1.改进算法无论对于那一种程序,好的算法总是非常重要的,而且能够极大地提高程序性能,所以任何性能的优化第一步就是从算法或者说程序逻辑的优化开始,检查自己的程序是否有多余的运算,是否在没有必要的时候做了 ...

  3. navicat远程连接mysql

      转载:http://blog.sina.com.cn/s/blog_84485e540101178p.html   ERROR 1130: Host '192.168.1.81' is not a ...

  4. error while loading shared libraries: libXXX.so.x: cannot open shared object file: No such file or directory .

    转载:http://www.eefocus.com/pengwr/blog/2012-02/235057_baf52.html 此时你可以locate libXXX.so.x 一下,查看系统里是否有该 ...

  5. [LintCode] Binary Tree Paths 二叉树路径

    Given a binary tree, return all root-to-leaf paths.Example Given the following binary tree: 1 /   \2 ...

  6. Pixar Shorts 皮克斯动画短片全集

    [原创短片](Theatrical Shorts)16部 <安德鲁和威利冒险记><顽皮跳跳灯><红色的梦><锡铁小兵><小雪人大行动>< ...

  7. Vim简要说明

    说明:在这篇文章里面,[C-X] 代表 Ctrl + X--就是按住 Ctrl 键然后再按 X.而且你可以在很多情况下使用 :help command 来获得大部分命令的帮助,这个是VIM的内部帮助文 ...

  8. 如何使用Jquery自定义命名空间namespace

    // 把生成命名空间的方法绑定在jQuery上 jQuery.namespace = function () { var a = arguments, o = null, i, j, d; for ( ...

  9. 使用 Grafana、collectd 和 InfluxDB 打造现代监控系统

    想打造 New Relic 那样漂亮的实时监控系统我们只需要 InfluxDB/collectd/Grafana 这三个工具,这三个工具的关系是这样的: 采集数据(collectd)-> 存储数 ...

  10. controlling the variance of request response times and not just worrying about maximizing queries per second

    http://highscalability.com/blog/2010/11/4/facebook-at-13-million-queries-per-second-recommends-minim ...