Spring学习笔记(三十二):在java后台alert()消息

来源:互联网 发布:花泽香菜 知乎 编辑:程序博客网 时间:2024/06/03 07:30

实现在后台alert()消息,而不是在前台
用下面的代码即可实现,注意:要设置contentType,否则乱码

response.setContentType("text/html; charset=utf-8");PrintWriter out = response.getWriter();out.print("<script>alert('test alert()');</script>");

问题1:

  • 问题描述:如果控制器的方法最后是重定向到另一个方法,那么alert就会无效:
  • 原因:因为在重定向之前,必须先保证没有任何的输出包括:
    • 1、Cookie;
    • 2、resp.getWriter()写文本信息;
    • 3、已经发送过重定向。
      而alert中就有resp.getWriter()的输出;
      比如:下面因为重定向到/adminUser/list,导致不能alert;
response.setContentType("text/html; charset=utf-8");PrintWriter out;out = response.getWriter();out.print("<script>alert('操作成功');</script>");return "redirect:/adminUser/list";

解决办法:在out.print中进行页面跳转,后面的return “”只是为了让程序不报错,并没有其他意义
见代码:

response.setContentType("text/html; charset=utf-8");PrintWriter out;out = response.getWriter();out.print("<script>alert('操作成功');</script>");out.print("<script>location='http://www.baidu.com';</script>");out.flush();//有了这个,下面的return就不会执行了return "";//这里因为是控制器中要有返回值String,所以加了这么一句,但是并没有用到;后台日志会报错,提示该模版""不存在,但是不影响程序的正常使用;因为实际起作用的是上的location定位
0 0
原创粉丝点击