关于request.getRequestDispatcher("######").forward(req, resp)

java web 报错:java.lang.IllegalStateException: Cannot forward after response has been committed…

不知不觉又掉进一个坑里面…反思之后,觉得还是总结不到位,因为最终结局的时候会突然想起来自己以前已经知道这么回事。。。感觉好蠢……


比如:(一些逻辑省略…)

	public void checkPass(HttpServletRequest req, HttpServletResponse resp,UserService userService)  {
		 User user = null;
		
         String name = req.getParameter("username");
         String pass = req.getParameter("pass");
         
         log.debug("pass"+pass);
         
         //***************获取user逻辑省略***************
         //
         if(user == null){
        	 loginMsg = "账号不存在";
			 req.getSession().setAttribute("loginMsg", loginMsg);
			 try {
				req.getRequestDispatcher("login.jsp").forward(req, resp);
			} catch (ServletException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
         }
         else{
        	 if(!user.getPassword().equals(pass)){
        		 loginMsg = "密码错误";
    			 req.getSession().setAttribute("loginMsg", loginMsg);
    			 try {
					req.getRequestDispatcher("login.jsp").forward(req, resp);
				} catch (ServletException | IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	 }
        	 else{
        		 req.getSession().setAttribute("user", user);
        		
					try {
						req.getRequestDispatcher("index.jsp").forward(req, resp);
					} catch (ServletException | IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			
        	 }
        	//若不注释掉,这一句始终会执行,那么这个方法就会执行两次forward(),就会报错
//        	 try {
//				req.getRequestDispatcher("login.jsp").forward(req, resp);
//			} catch (ServletException | IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
         }
	}




阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/efine_dxq/article/details/53991772
文章标签: web java web tomcat
个人分类: java web
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭