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

servlet异常:Cannot forward after response has been committed(转)

阅读更多

今天在用servlet 测试的时候 出现

java.lang.IllegalStateException: Cannot forward after response has been committed

主要原因是servlet 方法中 出现了两次 转向,即

request.getRequestDispatcher("/login.jsp").forward(request, response);   这个出现了两次

 

解决办法:

在任意一个 request.getRequestDispatcher("/login.jsp").forward(request, response); 这个后面加上一个

return; 就行啦

 

而我由于使用是myeclipse导出重写方法(extends HttpServlet后里面的方法):

@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {	
		super.doGet(request, response);
}

@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		super.doPost(request, response);
}

 当我处理完Post请求时想返回时,总是出现异常,我按上面的方式加入return;后仍然是出现这个异常,代码如下:

@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		super.doPost(request, response);
		
		
		request.setCharacterEncoding("UTF-8");
        String word = request.getParameter("word");
        //String word = new String(request.getParameter("word").getBytes("ISO-8859-1"),"UTF-8");
        System.out.println(word);
        try {
            FileReader fr= new FileReader("D:\\OldWTBWorldSpace\\ww\\testFile\\test.txt");
            //可以根据服务器端不同的字典或者数据库修改。此处仅是示例而已......
            BufferedReader br = new BufferedReader(fr);
            ArrayList<String> qlist = new ArrayList<String>();
            String row;
            while((row=br.readLine())!=null){
                if(row.startsWith(word)){
                    qlist.add(row);
                    if(qlist.size()==10){
                        break;
                    }
                }
            }
            
            fr.close();
            request.setAttribute("words", qlist);
            request.setAttribute("word",word);
            RequestDispatcher rd = request.getRequestDispatcher("wordxml.jsp");
            
            try {
				rd.forward(request, response);
	            return ; 
			} catch (Exception e) {
				System.out.println("异常啦!");
				e.printStackTrace();
			}
            
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        
	}
 后来我将super.doPost(request, response);注释掉后,才正确消除了异常,以此写下这文章,希望能帮到有需要的人。
分享到:
评论
1 楼 rodneytt 2012-02-13  
谢谢,帮了我大忙

相关推荐

Global site tag (gtag.js) - Google Analytics