开发者

Submit form through Servlet

开发者 https://www.devze.com 2023-02-15 00:08 出处:网络
Is there a way to create the Servlet (page display - form) and process it using the same Class? If the browser requests http://mypage.com/TestServlet - then the form input page is displayed, and when

Is there a way to create the Servlet (page display - form) and process it using the same Class?

If the browser requests http://mypage.com/TestServlet - then the form input page is displayed, and when the user submits the form, the same servlet action (../TestServlet) is called and it processes the input. I actually put the input processing logic in the doGet() method of the Servlet and now when I make a call to http://mypage.com/TestServlet , the logic is getting invoked automatically with null values. I know I can actually make a JSP or HTML page and then invoke the Servlet from there, but I don't want to. Is there a way to call a particular method of the Servlet? Like calling that method to process the 开发者_运维知识库user input when the Submit button is clicked and keeping the doGet() method to display the input form.


Normal practice is to use doGet() to preprocess the form and doPost() to postprocess the form. You only need to ensure that you use <form method="post">. For an example, see our Servlet wiki page.

However, if you really need a GET form (so that the request is bookmarkable, like a search form) then you need to give the submit button a name-value pair and check in the servlet whether it is present as request parameter. E.g.

<input type="submit" name="search" value="Search" />

with the following in doGet().

if (request.getParameter("search") != null) {
    // Form is submitted.
} else {
    // Form is not submitted.
}
0

精彩评论

暂无评论...
验证码 换一张
取 消