使用提交按钮获取servlet信息

时间:2015-06-25 18:04:35

标签: java html servlets

我正在尝试创建一个Servlet应用程序。当我点击提交按钮时,我想清除表单并将信息添加到无序列表并存储数据。问题是我不知道如何评估按钮的推送时间。

package org.gephi.demos;

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;


// Extend HttpServlet class
@WebServlet(name = "HelloWorld", urlPatterns = {"/test"}, loadOnStartup=1)
public class HelloWorld extends HttpServlet {

  private String message;
  private File f;
  private GephiBuilder gb;
  //private Main m;
  public void init() throws ServletException
  {
      gb = new GephiBuilder();
      System.out.println("Initialized");
      // Do required initialization
      message = "Hello World for sure";
  }

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");
      //m = new Main(gb);

      // Actual logic goes here.
        PrintWriter out = response.getWriter();
        out.println(HTMLUserInput("do you want a Nodes(n) or auto(a)", "directory", "d"));
        String directory = request.getParameter("d");
        // do some processing here...

        // build HTML code
        if(request.getParameter("button")!=null)
        {
            System.out.println("Hello");
            //response.getParameter("d").valu;
            String htmlRespone = "<html>";
            htmlRespone += "<h2>Your directory is: " + directory + "<br/>";     
            htmlRespone += "</html>";

            // return response
            out.println(htmlRespone);
        }
      //out.println(addJSCode());
  }

  public String HTMLUserInput(String question, String id, String name){
        String htmlOutput = "<form action=\"HelloWorld\"><label>"+question+"</label>"
            +"<input name = \""+name+"\" id=\""+id+"\" type=\"text\"/>"
            +"<input id=\"button\" type=\"button\">Submit</form>";
        return htmlOutput;
  }

  public void destroy()
  {
      // do nothing.
  }
}

如果我按下按钮没有任何变化,我想是因为这个代码只在启动时评估,如何在我按下提交按钮的时候对其进行评估。

2 个答案:

答案 0 :(得分:1)

1.You have to use URL for your servlet(wich was specified in servlet mapping) in action attribute . For example: <form action='/test'> 2.There is several way how to submit the form to the server. You can use <input type="submit">Submit</input> inside form tag . Or if you want to use tag button you have to set id attribute for the form (<form id='myform' .../>) and connect button with the form specifying this id in form attribute: <button type="submit" form="myform">Submit</button> And button tag does not have to be located within form tag. 3.After that you can get the content of your form using request.getParameter("input name") and handle these data.

答案 1 :(得分:0)

使用<input type="submit" />代替<button>

您的urlPatterns = {"/xxxxx"},应与form action="xxxxx"

相匹配