`
jianson_wu
  • 浏览: 65844 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

综合getOutputStream() has already been called for this response 出错示例

 
阅读更多

AJAX验证jsp页面验证码

 

在做登录的时候往往会加上验证码,然后提交form表单到action验证,然而,传统的这种做法往往验证不通过,返回INPUT页面时,出现验证码图片不显示,并抛出空指针异常,遇到这种情况,通常的解决方法是将action页面跳转到input页面的时候定义成重定向,这样则可以解决图片不显示的问题,并不会抛异常,但验证错误信息和文本框输入信息却不会显示在返回页面,这只是我在实际中遇到的问题,当然,传统做法很可能还会带来诸多各种各样问题,AJAX的使用则彻底解决上述种种问题,下面是一个简易登录页面验证流程:images.jsp

<%@ page language="java" contentType="image/jpeg ; charset=UTF-8"
    pageEncoding="UTF-8" import="java.awt.*,
java.awt.image.*,javax.imageio.*,java.io.*"%>
<%@ page import ="com.CreatImage"%>
<%@ taglib uri="/webwork" prefix="ww" %>
<!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>
<%
    response.setHeader("Pragma","No-cache");
    response.setHeader("Cache-Control","no-cache");
    response.setDateHeader("Expires", 0);

    CreatImage c = new CreatImage();
    BufferedImage  image = c.creatImage();
    OutputStream b = response.getOutputStream();
%>
<%ImageIO.write(image, "JPEG", response.getOutputStream());
 
    //必须添加以下两行否则tomcat下jsp出现getOutputStream() has already been called for this response异常
    out.clear();
    out = pageContext.pushBody();
%>
</body>
</html>

上面页面没有验证图片生成代码,验证图片生成代码写在com.CreatImage中,然后再jsp页面<%@ page import ="com.CreatImage"%>导入;
CreatImage.java:

package com;

import java.awt.*;
import java.awt.image.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.ActionSupport;

public class CreatImage extends ActionSupport{
   /**
  *
  */
    private static final long serialVersionUID = 1L;
    public String sRand="";
   Image image = null;
   public Color getRandColor(int fc,int bc){//给定范围获得随机颜色
    Random random = new Random();
    if(fc>255) fc=255;
    if(bc>255) bc=255;
    int r=fc+random.nextInt(bc-fc);
    int g=fc+random.nextInt(bc-fc);
    int b=fc+random.nextInt(bc-fc);
    return new Color(r,g,b);
    }
   public BufferedImage creatImage(){

  // 在内存中创建图象
     int width=60, height=20;
     BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

     // 获取图形上下文
     Graphics g = image.getGraphics();

     //生成随机类
     Random random = new Random();

     // 设定背景色
     g.setColor(getRandColor(200,250));
     g.fillRect(0, 0, width, height);

     //设定字体
     g.setFont(new Font("Times New Roman",Font.PLAIN,18));


          //画边框
         //g.setColor(new Color());
         //g.drawRect(0,0,width-1,height-1);

         // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
         g.setColor(getRandColor(160,200));
         for (int i=0;i<155;i++)
         {
       int x = random.nextInt(width);
       int y = random.nextInt(height);
       int xl = random.nextInt(12);
       int yl = random.nextInt(12);
       g.drawLine(x,y,x+xl,y+yl);
         }
         // 取随机产生的认证码(4位数字)
         //String rand = request.getParameter("rand");
         //rand = rand.substring(0,rand.indexOf("."));
       
         String str1=randomStr(4);// 得到随机字符
         HttpSession session = ServletActionContext.getRequest().getSession(); 
      session.setAttribute("validatenumber",str1);
         for (int i=0;i<4;i++){
       String rand=str1.substring(i,i+1);
      // 将认证码显示到图象中
        g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
        g.drawString(rand,13*i+6,16);
         }
         // 图象生效
         g.dispose();
     
         return image;
       }
  // 得到随机字符

  public  String randomStr(int n) {
      String str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
      String str2 = "";
      int len = str1.length() - 1;
      double r;
      for (int i = 0; i < n; i++) {
    r = (Math.random()) * len;
    str2 = str2 + str1.charAt((int) r);
      }
      return str2;
  }

   public void creatvalidateimage(){
    HttpSession session = ServletActionContext.getRequest().getSession(); 
          String valnumber = (String)session.getAttribute("validatenumber");   
          HttpServletResponse response = ServletActionContext.getResponse();
      response.setContentType("text/html;charset=utf-8");
      PrintWriter out;
          if(validate.equals(valnumber)){
     session.invalidate();//清空session
     message="validate success";
     try {
    out = ServletActionContext.getResponse().getWriter();
    out.println(message);
    out.flush();
          out.close();
      } catch (IOException e) {
    e.printStackTrace();
      }
    }else
     session.removeAttribute("validatenumber");
     message="validate is error";
     try {
    out = ServletActionContext.getResponse().getWriter();
    out.println(message);
    out.println("<table>");
    out.println("<tr>");
    out.println("<td>userName:<input type='text' id='name' value='"+name+"'/></td>");
    out.println("</tr>");
    out.println("<tr>");
    out.println("<td>userPassword:<input type='password' id='password' value='"+password+"'/></td>");
    out.println("</tr>");
    out.println("<tr>");
    out.println("<td>validate:<input type='text' id='validate'/><img     src=\"http://localhost:8088/uploadfile/images.jsp?a="+Math.random()+"\"/><a href='' onclick='changeCode()'>看不清,换一张?</a></td>");
    out.println("</tr>");
    out.println("</table>");
    out.flush();
          out.close();
     } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
      }
   
   }
      private String validate;
      private String message;
      private String name;
      private String password;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    //    public Image getImage() {
//        return image;
//    }
//    public void setImage(Image image) {
//        this.image = image;
//    }
    public String getValidate() {
        return validate;
    }
    public void setValidate(String validate) {
        this.validate = validate;
    }
}

登录页面:
login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="/webwork" prefix="ww" %>
<%
    String path = request.getContextPath();
%>
<!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>
        <script src="<%=path%>/js/prototype.js"></script>
    <script>
      function getXML(){
      var name = document.getElementById("name").value;
      var password = document.getElementById("password").value;
      var validate = document.getElementById("validate").value;
      var url="<%=path %>/upload/creatimage.action?password="+password+"&validate="+validate;
      var myAjax = new Ajax.Request(
      url,
      {
          method:'post',
          onComplete:showResponse,
          parameters:"name="+name,
          asynchronous:true
      }
      );
      }
      function showResponse(xmlrequest){
      var text = xmlrequest.responseText;
      document.getElementById("uploadanotherfile").innerHTML=text;
         }
     function changeCode()
      {
       document.getElementById("cc").src="<%=path%>/images.jsp?a="+Math.random();
    
      }
  </script>
</head>
<body>
<form action="<%=path %>/upload/creatimage.action" method="post">   
<div id="uploadanotherfile">
<table>
<tr>
<td>userName:<input type="text" id="name" value="<ww:property value="name"/>"/></td>
</tr>
<tr>
<td>userPassword:<input type="password" id="password" value="<ww:property value="password"/>"/></td>
</tr>
<tr>
<td>validate:<input type="text" id="validate"><img   alt=""  id="cc" src="<%=path %>/images.jsp"/><a href="#" onclick="changeCode();">看不清,换一张?</a></td>
</tr>
</table>
</div>
<input type="button" name="button" value="submit" onclick="getXML();"/>
</form>
</body>
</html>

 

 

 

分享到:
评论

相关推荐

    getOutputStream() has already been called for this response 错误解决

    在Java Web开发中,"getOutputStream() has already been called for this response" 是一个常见的错误,通常出现在使用Servlet或JSP时。这个错误意味着在HTTP响应中,`getOutputStream()`已经被调用,然后尝试再次...

    tomcat6下jsp出现getOutputStream() has already been called for this response异常的原因和解决方法

    1.在tomcat6.0下jsp出现getOutputStream() has already been called for this response异常的原因和解决方法  在tomcat6.0下jsp中出现此错误一般都是在jsp中使用了输出流(如输出图片验证码,文件下载等),没有...

    验证码出现getOutputStream()问题解决

    验证码出现getOutputStream() has already been called for this response错误解决

    java.lang.IllegalStateException: getOutputStream() has already解决办法

    纠结了半天的 java.lang.IllegalStateException: getOutputStream() has already。这个问题困扰了半天,在网上查阅了大量资料 出这个错误一般就是下面2个.....

    JSP彩色验证码

    解决了getOutputStream() has already been called for this response. 并将产生验证码的逻辑从JSP页面中分离出来,单独写了一个类 便于重用。

    Cannot forward after response has been committed

    "Cannot forward after response has been committed" 是一个在Java Web开发中常见的错误,通常与Servlet、Filter或控制器逻辑有关。这个错误表明服务器已经完成了对HTTP响应的处理,并将其发送到客户端,然后试图...

    handleStream ServletOutputStream out = response.getOutputStream(); InputStream i

    ServletOutputStream out = response.getOutputStream(); out.write("&lt;html&gt;&lt;body&gt;Hello, World!&lt;/body&gt;&lt;/html&gt;".getBytes()); out.flush(); out.close(); ``` 描述中的"InputStream i" 提到了输入流`InputStream`...

    response设置的实例源码

    七、示例代码 以下是一个简单的Servlet实例,展示了上述各种设置: ```java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class ResponseDemoServlet extends HttpServlet { ...

    java.lang.IllegalStateException: OutputStream already obtain

    标题 "java.lang.IllegalStateException: OutputStream already obtain" 涉及到的是Java编程中的一个常见错误,特别是当处理I/O流时。这个异常通常在尝试获取已经存在的OutputStream实例时抛出,表明该输出流已经被...

    Response-Headers详解

    ### Response-Headers详解 #### HTTP响应报头的基本概念与作用 HTTP响应报头是Web服务器向客户端(通常是浏览器)发送响应时附带的信息。这些报头提供了关于响应本身的元数据,如响应的内容类型、长度等,对于正确...

    Java BIO Socke示例

    在这个"Java BIO Socke示例"中,我们将探讨如何使用Java BIO API来实现简单的Socket通信,以及如何进一步优化处理多客户端连接,通过线程池来提升效率。 首先,让我们从基础的Socket通信开始。在Java中,`java.net....

    response生成图片验证

    这里使用了Servlet的`HttpServletResponse`对象,调用其`setContentType`方法设置响应的MIME类型为`image/jpeg`或`image/png`,然后使用`getOutputStream`获取输出流,并调用`ImageIO.write`方法将图片写入。...

    servlet2.4doc

    Returns a boolean indicating whether the named response header has already been set. contextDestroyed(ServletContextEvent) - Method in interface javax.servlet.ServletContextListener Notification ...

    java中文件上传下载示例

    IOUtils.copy(fis, response.getOutputStream()); fis.close(); } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } } ``` 以上就是Java中文件上传和下载的基本原理和实现方式。实际开发中...

    java response 下载文件方法

    ### Java Response 下载文件方法详解 在Web应用开发过程中,经常需要实现文件的上传与下载功能。其中,通过`java response`实现文件下载是常见需求之一。本文将深入解析如何利用Java中的`HttpServletResponse`对象...

    HttpServletRequest-response方法总结

    HttpServletRequest-response方法总结 HttpServletRequest和HttpServletResponse是Servlet编程中两个最重要的接口,它们提供了对HTTP请求和响应的控制和处理。下面是对HttpServletRequest和HttpServletResponse的...

    Request&Response-授课

    ServletOutputStream sos = response.getOutputStream(); //解决中文乱码问题 response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); sos.write(str.getBytes()); } ...

    WEB、php、C#、JAVA短信发送示例代码

    try(OutputStream os = connection.getOutputStream()) { os.write(data.getBytes()); } int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 处理响应 ...

    response中文乱码解决的代码

    3. 使用`FileInputStream`读取文件内容,并通过`response.getOutputStream().write()`将内容写入响应流。 通过以上方法,我们可以在处理中文文件名的文件下载时,有效避免乱码问题,确保用户能够正确下载并识别文件...

Global site tag (gtag.js) - Google Analytics