我知道这里已经讨论了至少一百万次但是每个servlet在调用forward()之前重定向或刷新输出。我有同样的问题,但我没有做任何输出。我的servlet只接受请求参数并提交到数据库并在请求上设置属性。然后,它将请求转发给它们显示属性的jsp。我在Tomcat 7上使用Servlet 3.0。这是我的servlet doPost方法,然后是转发到的jsp:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doPost(req, resp);
DAOFactory daoFactory = DAOFactory.getFactory();
daoFactory.getCompanyDAO().beginTransaction();
Company company = new Company();
company.setName(req.getParameter("companyName"));
company.setContactEmail(req.getParameter("companyEmail"));
company.setContactPhone(new Long(req.getParameter("companyMobile")));
company.setAddressLine1(req.getParameter("companyAddressLine1"));
company.setAddressLine2(req.getParameter("companyAddressLine2"));
company.setCity(req.getParameter("companyCity"));
company.setZipcode(Integer.parseInt(req.getParameter("companyZip")));
company.setState(req.getParameter("companyState"));
company = daoFactory.getCompanyDAO().save(company);
daoFactory.getCompanyDAO().commitTransaction();
Employee owner = new Employee();
owner.setFirstname(req.getParameter("ownerFirstName"));
owner.setLastname(req.getParameter("ownerLastName"));
owner.setEmail(req.getParameter("ownerEmail"));
owner.setMobileNum(new Long(req.getParameter("ownerCellPhone")));
owner.setZipcode(Integer.parseInt(req.getParameter("ownerZip")));
owner.setRole("Employer");
owner.setCompany(company);
daoFactory.getEmployeeDAO().beginTransaction();
owner = daoFactory.getEmployeeDAO().save(owner);
daoFactory.getEmployeeDAO().commitTransaction();
company.addEmployee(owner);
company.setOwnerId(owner.getId());
daoFactory.getCompanyDAO().beginTransaction();
company = daoFactory.getCompanyDAO().save(company);
daoFactory.getCompanyDAO().commitTransaction();
req.setAttribute("company", company);
RequestDispatcher rd = getServletConfig().getServletContext().getRequestDispatcher("/jsp/companyConfirmation.jsp");
rd.forward(req, resp);
}
JSP:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>The Company was saved successfully</h3>
<p>
Company name: ${company.name}
</p>
</body>
</html>
我相信我可能错过了一些非常微不足道的事情。我无法弄清楚它是什么,特别是当我在转发请求之前没有向输出写任何内容时。
PS:我也尝试在前进后添加return;
语句,但没有变化。
谢谢!
答案 0 :(得分:4)
您应该删除super.doPost(req, resp)
方法调用。 HTTPServlet的doPost方法的默认实现返回HTTP 405状态代码,意思是“不支持方法”,这是已提交的响应。因此,您无法将您的请求转发给其他jsp。
这是RequestDispatcher.forward(ServletRequest req, ServletResponse resp)
方法描述的一部分:“应该在将响应提交给客户端之前调用forward(在刷新响应主体输出之前)。如果响应已经提交,则此方法抛出IllegalStateException。响应缓冲区中的未提交输出在转发前自动清除。