Struts2 自定义Result-Type 实现跳转页面是弹出提示框

来源:互联网 发布:windows oracle主备 编辑:程序博客网 时间:2024/05/19 20:42

Struts自带的resulttype类型只能直接跳转到制定页面或action,如果想实现跳转是弹出提示框,类似于使用Servlet的时,利用response往页面打印js实现弹提示框与跳转

response.getWriter().print("<script>alert('提示信息!');location.href='跳转地址'</script>");

那么我们可以自定义一个Resulttype类型,来实现这个效果

  • 首先创建一个类,继承自ServletRedirectResult
    • 这个类是我查看struts源码,反正struts自带的redirect类型所对应的类就是这个类,那么我们可以继承这个类,然后重写其中的跳转方法
  • 重写方法:sendRedirect
    @Override    protected void sendRedirect(HttpServletResponse response,            String finalLocation) throws IOException {        response.setContentType("text/html;charset=utf-8");        response.getWriter().print("<script>alert('提示信息!');location.href='跳转地址'</script>");    }
  • 在struts配置文件里添加自定义的result-type
<result-types>            <result-type name="mytype" class="test.MyResultType"></result-type></result-types>
  • 那么我们在跳转的时候,在结果里就可以使用我们新建的result-type
<action name="test">            <result type="mytype">index.jsp</result></action>
  • 但是我们这样写的话,弹出的提示信息无法改变,那么可以通过定义result-type的参数来将提示信息传递进去
  • 那么首先去MyResultType里定义一个msg来存储消息
<action name="test">    <result type="mytype">        <param name="location">index.jsp</param>        <param name="msg">提示消息!</param>    </result></action>
    private String msg;    @Override    protected void sendRedirect(HttpServletResponse response,            String finalLocation) throws IOException {        response.setContentType("text/html;charset=utf-8");        response.getWriter().print("<script>alert('"+msg+"');location.href='跳转地址'</script>");    }    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }

OK,我们可以实现struts跳转弹窗了!!

0 0
原创粉丝点击