Member Avatar for by89

Sorry this is the first time posting so if there is any wrong placement of thing, i apologize.

Basically I'm trying to retrieve all the field of the food by typing the foodname and display it into the addfood.jsp. There are 2 class and 1 jsp which is foodmanage.java where i declare my method, searchfood.java which is the servlet to call the class and addfood.jsp to display the data retrieve from the database. However, when i submit i keep getting this error: java.lang.IllegalStateException: Cannot forward after response has been committed.

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class foodmanage extends dbconnect{
	
	private static foodmanage c_This;
	private static final String FOOD_TABLE = "food";
	
	
user u_user;
	
	public foodmanage(user us)
	{
		u_user = us;
		
	}

	
	 public food[] getFood(String foodname)
		{
			String sql = "SELECT * FROM " + FOOD_TABLE;
			sql += " WHERE foodname=?";
			Connection con = null;
			try {
				
				
				con = getConnection();
				PreparedStatement ps = con.prepareStatement(sql);
				ps.setString(1, foodname);
			
				ResultSet rs = ps.executeQuery();
				List<food> lst = new ArrayList<food>(); 
				while(rs.next())
					lst.add(readFood(rs));

				food[] vfd = new food[lst.size()];
				return lst.toArray(vfd);
		
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
				return null;
			}
			finally {
				try {con.close();}catch(Exception e) {;}
			}
			
		}


	public food readFood(ResultSet rs) throws SQLException
		{
			food fd = new food();
			fd.setFoodname(rs.getString("foodname"));
				fd.setSatfat(rs.getDouble("satfat"));
				fd.setMonofat(rs.getDouble("monofat"));
				fd.setPolyfat(rs.getDouble("polyfat"));
				fd.setProtein(rs.getInt("protein"));
				fd.setCarb(rs.getInt("carb"));
			    fd.setPerserving(rs.getString("perserving"));
			return fd;
		}
	
	
}
import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 * Servlet implementation class searchfood
 */
public class searchfood extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
	private static final long serialVersionUID = 1L;
	private String foodname;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public searchfood() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		user us = (user)request.getSession().getAttribute("USER");
		if(us == null)
			response.sendRedirect("./login.html");
		
		
String foodname = request.getParameter("foodname");
		
		
		try {

			
			//Retrieve an instance of the EmployeeManager
			foodmanage fmgr = new foodmanage(us);
			
			//Retrieve all the employees with the submitted name
			food[] food_array = fmgr.getFood(foodname);
			
request.getSession().setAttribute("FOOD", food_array[0]);
			
			//Redirect the user to the index.jsp page
			response.sendRedirect("./addfood.jsp");
		}
		
		catch (Exception ex)
		{
			
			request.getRequestDispatcher("./error.html").forward(request, response);
			return;
		}
		
	}
		
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Company Name</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
 
<body>

<%
	//Retrieve the leave applied
	food[] foods = (food[])request.getAttribute("FOOD_ENTER");
	if(foods == null)
		foods = new food[0]; //so there is will be an error, just an empty list
	
	
%>


<table width="779" border="0" align="center" cellpadding="0" cellspacing="0">


<form name="form1">
<table width="520" border="0">
  <tr>
  <th scope="col"><div align="left">  Date </div></th>
    <th scope="col"><div align="left">Food Name</div></th>
     <th scope="col"><div align="left">Per Serving</div></th>
    </tr>
     
     
       <%
  	for(int i = 0; i < foods.length; i++) {
  %>
  
  
       <tr>
       <td><input type="text" name="enterdate" id="enterdate"></td>
    <td><input type="text" value="<%=foods[i].getFoodname()%>"/></td>
    <td><input type="text" value="<%=foods[i].getPerserving()%>" /></td>
    </tr>
    
     <tr>
    <th  scope="col"><div align="left">Saturated Fat</div></th>
    <th  scope="col"><div align="left">Monosaturated Fat</div></th>
    <th scope="col"><div align="left">Polysaturated Fat</div></th>
   
      </tr>
    
 


    <tr>
    <td><input type="text" value="<%=foods[i].getSatfat()%>" /></td>
    <td><input type="text" value="<%=foods[i].getMonofat()%>" /></td>
    <td><input type="text" value="<%=foods[i].getPolyfat()%>"  /></td>

  </tr>
  
  <tr>
    <th scope="col"><div align="left">Protein</div></th>
      <th scope="col"><div align="left">Carbonhydrate</div></th>
      </tr>

<tr>    
<td><input type="text" value="<%=foods[i].getProtein()%>"  /></td>
    <td><input type="text" value="<%=foods[i].getCarb()%>"  /></td>
 
 </tr>
  
  
 
  <tr></tr>
   <tr></tr>
    <tr></tr>
        <tr></tr>
            <tr></tr>
                <tr></tr>
  
</table>


  <p> </p>
  <p>
  
  </p>
</form>

 
</body>
</html>

when you 'forward' or 'include', the same request and response is passed to that resource. If you close the output stream, it cannot be used by the JSP to return the data. As soon as any data gets written to the client, the response is 'committed', and if you check the API, closing the Writer also flushes it (ie sends the data). Since you set the content type first it also ensures that there is data to be sent.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.