我刚刚开始使用Servlets并设法使用一些servlet作为单独的URL来填充数据库以进行一些虚拟测试.形式的东西:
public class Populate_ServletName extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
//Insert records
//Print confirmation
}
}
Run Code Online (Sandbox Code Playgroud)
我有大约6个这样的servlet,我想按顺序执行.我正在考虑使用setLocation来设置要重定向的下一页,但不确定这是否是正确的方法,因为重定向应该在插入记录之后发生.具体来说,我正在寻找这样的东西:
public class Populate_ALL extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
//Call Populate_1
//Call Populate_2
//Call Populate_3
//...
}
}
Run Code Online (Sandbox Code Playgroud)
有什么建议?
RequestDispatcher#include()在url-pattern与Servlet 匹配的URL上使用.
public class Populate_ALL extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
request.getRequestDispatcher("/populateServlet1").include(request, response);
request.getRequestDispatcher("/populateServlet2").include(request, response);
request.getRequestDispatcher("/populateServlet3").include(request, response);
//...
}
}
Run Code Online (Sandbox Code Playgroud)
注意:如果这些小服务程序不能用于独立,那么这是错误的做法,你应该使用独立的Java类此不延伸HttpServlet.在您的具体情况下,我认为Builder模式可能会引起关注.
的RequestDispatcher#forward(),因为它会引发不适合这里IllegalStateException的时候响应头已经提交.当您通过多个servlet传递请求/响应时,无疑会出现这种情况,每个servlet都会写入响应.
这HttpServletResponse#sendRedirect()绝对不适合,因为它隐含地创造了一个全新的,request并response因此摒弃了原始的.
| 归档时间: |
|
| 查看次数: |
1990 次 |
| 最近记录: |