我已经在doGet下调用了这个方法。请帮助我摆脱困境。 这是我自己的方法,我想调用它。
public void doYourThingHere(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String[] checkedQues = request.getParameterValues("ttom");
List<String> checkedQuesList = Arrays.asList(checkedQues);
Map<String, String> preferences = new LinkedHashMap<String, String>();
if (session.getAttribute("username") != null) {
List<Question> questionsList = (List<Question>) session
.getAttribute("restaurantQuestionList");
List<Question> questionsListTemp1 = new ArrayList<>();
for (int i = 2; i < 4; i++) {
questionsListTemp1.add(questionsList.get(i));
}
session.setAttribute("tomtomRestaurantQuestionList1",
questionsListTemp1);
for (Question question : questionsList) {
String questionId = String.valueOf(question.getId());
if (checkedQuesList.contains(questionId)) {
String answerId = request.getParameter(questionId);
// PreferenceDAO.storePreferences(questionId, answerId,
// CATEGORY);
preferences.put(questionId, answerId);
System.out.println("queid : " + questionId + "answerid : "
+ answerId);
}
}
String username = (String) session.getAttribute("username");
PreferencesProcessor.process(preferences, username);
RequestDispatcher requestdp = request
.getRequestDispatcher("WEB-INF/jsp/table.jsp");
requestdp.forward(request, response);
} else {
RequestDispatcher requestdp = request
.getRequestDispatcher("WEB-INF/jsp/login.jsp");
requestdp.forward(request, response);
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
/**
* @see HttpServlet doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
最佳答案
Servlet 将 HTTP 请求 header 映射到预定义的方法,例如 doGet()、doPost() 等。
https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServlet.html
由于您的方法会修改数据,因此您应该使用 POST 调用它。
最简单的方法是将 doPost() 转发到此方法:
public void doPost(HttpServletRequest request, HttpServletResponse response) {
doYourThingHere(request, response);
}
通常会发生的情况是,您将向 doPost 添加一些路由逻辑,如下所示:
public void doPost(...) {
String action = request.getParameter("action");
switch (action) {
case "doSomething":
doSomething(request, response);
break;
case "somethingElse":
doSomethingElse(request, response);
break;
...
}
}
关于java - 我正在开发 servlet,只有一种 deGet 和 DoPost 方法。我在那里写了一种新方法。 。我如何直接访问该新方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40546804/