【发布时间】:2018-08-12 17:27:29
【问题描述】:
我正在做一个关于 jsp servlet 的小项目。我想要一个示例来使用相同的 servlet 实现 doGet() 和 doPost() 方法,并通过 jsp 页面中的表单中的 ajax 调用发送和发布。
还要说明为什么不建议在同一个 servlet 中使用 doGet() 和 doPost()。如何使用两个不同的 servlet 实现相同的功能,但在同一个 jsp 页面中工作。
在此先感谢任何帮助。
我的jsp代码:-
<form action="/mamababu.do" method="POST">
<select name="command_no">
<c:forEach var="items" items="${scriptItems}">
<option value="${items.command}" name="command">${items.command}</option>
</c:forEach>
</select>
<input type="submit" value="submit"></input>
</form>
我的 servlet 类:-
package com.project.mamabhagne;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
@WebServlet("/mamababu.do")
public class mamababu extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//get the data from database ie the model class
try {
List<Script> scriptitems=modelDBUtil.getScriptList();
// String json = new Gson().toJson(scriptitems);
request.setAttribute("scriptItems", scriptitems);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*String itemsfood[]={"biriyani","rice"};
request.setAttribute("itemsfood",itemsfood)*/;
//redirect to a different page
RequestDispatcher dispatcher =request.getRequestDispatcher("scriptviewer.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//TODO Auto-generated method stub
System.out.println("hi");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML><HEAD><TITLE>Hello World!</TITLE>"+
"</HEAD><BODY>Hello World!</BODY></HTML>");
out.close();
RequestDispatcher dispatcher =request.getRequestDispatcher("scriptviewer.jsp");
dispatcher.forward(request, response);
}
}
我在发布表单数据时收到此错误:-
HTTP Status 404 - /mamababu.do
type Status report
message /mamababu.do
description The requested resource is not available.
Apache Tomcat/8.0.52
【问题讨论】:
-
在您的端点中,您正在使用调度程序 servlet 进行重定向,这在使用 ajax 时是不可能的,重定向应该在您的 ajax 请求的成功处理程序中完成。
-
我在这里使用 jstl。你可以在我的 jsp 页面中清楚地看到。但是即使我删除了请求调度程序,问题仍然存在
-
ending and posting via an ajax call in forms in a jsp page.那么为什么你的问题中有这句话。 -
是的,我想添加它,但是发布时也有问题,你能不能给我一个示例 servlet ajax 帖子并获取
-
如果要实现ajax响应应该是纯文本、JSON...等形式
标签: javascript java ajax jsp servlets