Cannot call sendError() after the response has been committed

论坛 期权论坛 脚本     
匿名技术用户   2021-1-4 01:06   28   0

开发的时候,有时候报错:

java.lang.IllegalStateException: Cannot call sendError() after the response has been committed

字面上是参数异常, 在response已经提交之后 不能发送错误请求。

1.

  1. @Test
  2. public void testSave() {
  3. ApplicationContext cxt = new ClassPathXmlApplicationContext("/applicationContext.xml");
  4. buyerService = (BuyerService)cxt.getBean("buyerService");
  5. Buyer buyer = new Buyer("dengmingti","123456","test@sina.com");
  6. ContactInfo contactInfo = new ContactInfo();
  7. contactInfo.setAddress("百色市朝阳区左家庄");
  8. contactInfo.setMobile("13671323507");
  9. contactInfo.setPhone("010-64469090-9");
  10. contactInfo.setPostalcode("531500");
  11. buyer.setContactinfo(contactInfo);
  12. buyer.setGender("男");
  13. buyer.setRealname("刘德华");
  14. buyer.setRegTime(new Date());
  15. buyerService.save(buyer);
  16. }

解决方法:

(1)从你的文件来看,你应该是使用了spring;
(2)你说用getHibernateTemplate().save(o)可以成功,而getSession.save(o)却不行。有理由怀疑你是在spring的配置文件中配置了事务,而getHibernateTemplate()是Spring的方法,支持声明式事务管理,所以如果你配置了事务,它会自动调用事务并在操作完毕后自动关闭session;而单独的getSession()却与spring没有关系,它是由hibernate控制的,并不支持声明式事务管理,所以你必须调用session.flush()或transaction.commit()才可以成功保存。
 (3)我怎样才能使用buyerService.save(buyer)存到数据库中呀?不妨把你的applicationContext.xml文件贴出来,看看你的service和dao关联起来了没(就是在service里有没有引用你配置的dao).现在你的dao里到底是使用哪种方式保存的,都没有说清楚

2.下面看个例子就一目了然了:

  1. response.setContentType("text/html;charset=UTF-8");
  2. PrintWriter out = response.getWriter();
  3. out.print("上传成功!上传文件为:"+fileName+"<br/>保存的地址为"+filePath+ "!!");
  4. out.close();
  5. response.sendRedirect("index.jsp");

首先,利用reponse.getWrite()获得输出流对象,close()之后,这里reponse其实已经提交了。注释下面的sendRedirect代码,执行之后发现response已经进行已经跳转了,只不过url没有发生改变,并且页面上已经有输出上面指定的字符串。

所以当执行上面代码之后 ,reponse 会提交两次,服务器就不知道该怎么办了,所以抛出异常。

解决方案: 去掉out.close() 这里不会因为PrintWriter 输出对象没有关闭而占用资源的。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP