从jscript获取字符串值到servlet

时间:2012-11-29 10:34:04

标签: java javascript html servlets

我对此有点怀疑......如何在servlet中设置/检索来自名为“z”的jsp页面jscript字符串中的值。我需要在servlet中使用它...我正在探索新事物对我来说是一件新事物,因为我对这些事情不熟悉...感谢您的快速帮助....如果pass1和pass2相同,我需要密码的值,然后我需要检索它servlet if pass1 == pass2 ...告诉我一个方法...因为我写了一个jscript来检查pass1 == pass2 ..

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>New User Registration</title>
    <script>
    function myFunction(){
        var x = document.forms["newForm"]["pass1"].value;
        var y = document.forms["newForm"]["pass2"].value;
    if(x==y){
        document.newForm.submit();var z=x;
        return true;
        }
        else {
        alert("Passwords not matching!!!");}
        }

    </script>
    </head>
    <body>
    <h1>Form</h1>
    <fieldset>
    <form name=newForm action="RegServlet">Username:<input
        type="text" name="username"><br>
    Password:<input type="text" name="pass1" id="pass1"><br>
    Confirm Password:<input type="text" name="pass2" id="pass2"><br>
    <input type="submit" onclick=myFunction() value="Create"></input></form>
    </fieldset>

    </body>
    </html>

的servlet

package myPack;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RegServlet
 */
public class RegServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String s1=request.getParameter("username");
        System.out.println(s1);

        String s2=request.getParameter("");//HERE I NEED THE PAssword value if PASS!==PASS2
        System.out.println(s2);

        String c="jdbc:mysql://localhost:3306/test";

        Connection con=null;
        System.out.println("Connection OK");
        try{
        Class.forName("com.mysql.jdbc.Driver").newInstance();
            System.out.println("Done2");

            con = DriverManager.getConnection(c, "root", "MyNewPass");
            System.out.println("Done3");

            PreparedStatement ps=null;
            System.out.println("Done4");

            String qs = "insert into userinfo values(?,?);";
            ps = con.prepareStatement(qs);
            ps.setString(1,s1);
            ps.setString(2,s2);
            System.out.println("Success");
            ps.execute();
            con.close();

        }
        catch (Exception e) {
            System.out.println("Failed: " + e.toString());
        // TODO: handle exception
            System.out.println("Failed");}}


    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

2 个答案:

答案 0 :(得分:1)

在表单中创建隐藏字段;然后在“onsubmit”事件中将该字段的值设置为z。

 <input type="hidden" name="zValue" id="zValue">

onsubmit事件

document.getElementById("zValue").value="The value I want to send";

并在servlet中检索任何其他参数。

答案 1 :(得分:0)

以下是我在tomcat中使用的示例。它将获取在POST或GET请求中发送的所有参数。请注意,这不包括多播请求(文件传输所需的)。
我不知道它是否适合您,因为您没有指定servlet容器。

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.util.*;


@WebServlet(description = "A simple request test.", urlPatterns = { "/requesttest" })

public class RequestTest extends HttpServlet {

public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Reading All Request Parameters";
    out.println("<BODY BGCOLOR=\"#FDF5E6\">\n" +
                "<H1 ALIGN=CENTER>" + title + "</H1>\n" +
                "<TABLE BORDER=1 ALIGN=CENTER>\n" +
                "<TR BGCOLOR=\"#FFAD00\">\n" +
                "<TH>Parameter Name<TH>Parameter Value(s)");
    Enumeration<String> paramNames = request.getParameterNames();
    while(paramNames.hasMoreElements()) {
      String paramName = (String)paramNames.nextElement();
      out.println("<TR><TD>" + paramName + "\n<TD>");
      String[] paramValues = request.getParameterValues(paramName);
      if (paramValues.length == 1) {
        String paramValue = paramValues[0];
        if (paramValue.length() == 0)
          out.print("<I>No Value</I>");
        else
          out.print(paramValue);
      } else {
        out.println("<UL>");
        for(int i=0; i<paramValues.length; i++) {
          out.println("<LI>" + paramValues[i]);
        }
        out.println("</UL>");
      }
    }
    out.println("</TABLE>\n</BODY></HTML>");

  }

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}

修改
看到您使用servlet代码编辑问题时,答案应该非常简单。

 String s2=request.getParameter("pass1");

这应该可以获得密码字段中传输的值。这与使用String s1=request.getParameter("username");

获取用户名没有什么不同