Java 如何制作一个简单的程序,让Servlet和JSP一起生成HTML文件?
我想知道是否可以同时使用Servlet和JSP发送HTML页面。不,我不希望JSP通过转发来自Servlet的请求来完成所有工作。我希望Servlet写“hello”,JSP写“用户名” 这是我的尝试,失败了: index.html:Java 如何制作一个简单的程序,让Servlet和JSP一起生成HTML文件?,java,jsp,servlets,response,Java,Jsp,Servlets,Response,我想知道是否可以同时使用Servlet和JSP发送HTML页面。不,我不希望JSP通过转发来自Servlet的请求来完成所有工作。我希望Servlet写“hello”,JSP写“用户名” 这是我的尝试,失败了: index.html: <html><body> <form action="MyServlet" method="POST"> Enter name: <input type=&q
<html><body>
<form action="MyServlet" method="POST">
Enter name: <input type="text" name="name">
<button>Submit name</button>
</form>
</body></html>
@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter pw = resp.getWriter();
pw.println("hello ");
RequestDispatcher dispatch = req.getRequestDispatcher("test.jsp");
dispatch.forward(req, resp);
}
}
<html><body>
<%= request.getParameter("name") %>
</body></html>
test.jsp:
<html><body>
<form action="MyServlet" method="POST">
Enter name: <input type="text" name="name">
<button>Submit name</button>
</form>
</body></html>
@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter pw = resp.getWriter();
pw.println("hello ");
RequestDispatcher dispatch = req.getRequestDispatcher("test.jsp");
dispatch.forward(req, resp);
}
}
<html><body>
<%= request.getParameter("name") %>
</body></html>
填写表格后:
,我希望得到hello elephant
。但我只得到大象。我试图将pw.flush()放在servlet的代码中,结果正好相反——只是hello
现在我被困住了,因为我不明白怎么了。我猜当我刷新一个流时,响应被提交了,所以其余的代码没有运行。但当我没有提交(刷新)流时,为什么用户没有收到hello
消息呢?我能做我描述的那样的事吗?看起来我缺少了一些基本的东西。使用而不是转发
。改变
dispatch.forward(req, resp);
到