如何将用户输入从JSP文件调用到Java文件中

时间:2013-12-12 22:44:09

标签: java javascript jsp

我正在使用JSP编写程序。我有一个包含几个方法的.java文件,除了一些javascript方法之外,我还有一个包含以下内容的.jsp文件:

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> 
<div id="nameDiv"></div>
<div id="nameInput">
    <input type="text" name="nameOne" value="Enter a Name" onClick="if(this.value == 'Enter a Name'){this.value = '';}" /> 
    <input type="text" name="nameTwo" value="Enter a Name" onClick="if(this.value == 'Enter a Name'){this.value = '';}" /> 
    <input type="text" name="nameThree" value="Enter a Name" onClick="if(this.value == 'Enter a Name'){this.value = '';}" /> 
    <input type="button" name="btnUpdate" value="Update Name" />
</div>

我的问题是:如何在java文件中调用这些文本框中的用户输入?或者更好地说,如何将这些位于单独文件(JSP)上的输入调用到我的其他单独的java文件中并使用用户在文本框中输入的值?

1 个答案:

答案 0 :(得分:0)

使用servlet作为.java文件,您可以在此servlet类中编写方法

public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("nameOne");
        System.out.println("<form action='Myservlet.do' method='get'>");
        System.out.println("nameOne is " + name);
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("nameThree");
        System.out.println("<form action='Myservlet.do' method='post'>");
        System.out.println("nameThree is " + name);
    }

}

并将其添加到WebContent / WEB-INF中的web.xml:

  <servlet>
    <!--whatever-->
    <servlet-name>MyServlet</servlet-name>
    <!--the position of your own servlet-->
    <servlet-class>com.stackoverflowquizz.servlet.MyServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <!--the same as the one in <servlet>-->
    <servlet-name>MyServlet</servlet-name>
    <!--the action or the url that you can access this servlet-->
    <url-pattern>/Myservlet.do</url-pattern>
  </servlet-mapping>

在.jsp文件中使用<form action = "xx" method="get/post"> <input type="submit">将args传递给.java(servlet文件)

    <form action="Myservlet.do" method="get">
        <input type="text" name="nameOne" value="Enter a Name" onClick="if(this.value == 'Enter a Name'){this.value = '';}" /> 
        <input type="text" name="nameTwo" value="Enter a Name" onClick="if(this.value == 'Enter a Name'){this.value = '';}" />
        <input type="submit">
    </form> 
    <form action="Myservlet.do" method="post">
        <input type="text" name="nameThree" value="Enter a Name" onClick="if(this.value == 'Enter a Name'){this.value = '';}" /> 
        <input type="submit">
    </form>