如何使用Jquery将多个值传递给servlet

时间:2013-01-23 10:50:04

标签: java jquery html servlets

我有一个Html表单,我需要使用jquery将值传递给servlet,然后它将验证信息并返回结果。但是当我尝试使用jQuery传递数据时。 servlet显示接收到空值。

<div class="ulogin">
<h2>Login</h2>
<div id="error"></div>
        <form action="Login" method="post" id="spsignin">
        <input type="text" name="uname" class="text validate[required]" id="name" placeholder="Username"/>
        <input type="password" name="pass" class="text validate[required]" id="password" placeholder="Password"/>
        <input type="submit" value="" id="memberlogin"/>
        </form>
</div>

我的javascript文件是

 $(document).ready(function() {

//Stops the submit request
$("#spsignin").submit(function(e){
       e.preventDefault();
});

//checks for the button click event
$("#memberlogin").click(function(e){

        //get the form data and then serialize that
        dataString = $("#spsignin").serialize();
        dataString1 = $("#spsignin").serialize();

        var uname = $("input#name").val();
        var pass = $("input#password").val();
         $.ajax({
            type: "POST",
            url: "Login",
            data:'uname=' +encodeURIComponent(uname) &'pass=' + encodeURIComponent(pass),
            dataType: "json",

            //if received a response from the server
            success: function( data, textStatus, jqXHR) {
                 if(data.success)
                 {
                     $("#error").html("<div><b>success!</b></div>"+data);
                  }
                 //display error message
                 else {
                     $("#error").html("<div><b>Information is Invalid!</b></div>"+data);
                 }
            },

            //If there was no resonse from the server
            error: function(jqXHR, textStatus, errorThrown){
                 console.log("Something really bad happened " + textStatus);
                 $("#error").html(jqXHR.responseText);
            },

            //capture the request before it was sent to server
            beforeSend: function(jqXHR, settings){
                 //disable the button until we get the response
                $('#memberlogin').attr("disabled", true);
            },

            complete: function(jqXHR, textStatus){
                //enable the button
                $('#memberlogin').attr("disabled", false);
            }

        });       
 });
});

servlet是

  package skypark;

  import java.io.IOException;
  import java.io.PrintWriter;
  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;
  import java.sql.SQLException;

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

 /**
 * Servlet implementation class Login
  */
 @WebServlet("/Login")
  public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
Boolean success=true;

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

public static Connection prepareConnection()throws ClassNotFoundException,SQLException
{
    String dcn="oracle.jdbc.OracleDriver";
    String url="jdbc:oracle:thin:@//localhost:1521/skypark";
    String usname="system";
    String pass="tiger";
    Class.forName(dcn);
    return DriverManager.getConnection(url,usname,pass);
}
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    String uname,pass;
    response.setContentType("text/html");
    PrintWriter out=response.getWriter();
    response.setContentType("text/html");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");

     uname=request.getParameter("uname");
    pass=request.getParameter("pass");
    Boolean suc;
    try {
        suc = check(uname,pass);
            out.println(suc);
        } catch (ClassNotFoundException | SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    out.flush();
      out.close();
}
   public Boolean check(String uname,String pass) throws SQLException, ClassNotFoundException
   {
 ResultSet rs = null;
 int i=0;
 Connection con=prepareConnection();
 String Query="select uname,email from passmanager where pass=?";
 PreparedStatement ps=con.prepareStatement(Query);

  try
  {
    ps.setString(1,pass);
    rs=ps.executeQuery();

        while(rs.next())
        {
            if (uname.equalsIgnoreCase(rs.getString("uname")) || uname.equalsIgnoreCase(rs.getString("email"))) 
            {
    rs.close();                                                              
            ps.close();                                                            
            ps = null;               con.close();                                                            
         con = null;  
        success=true;
        i=1;
       break;
    }
    }
  }
  catch(Exception e)
      {
      System.out.println(e);
      }

  if(i==0)
  {
      success=false;
  }
return success;

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

我认为错误与jquery有关。请任何人帮助我克服这个......

3 个答案:

答案 0 :(得分:1)

问题在于这一行:

data:'uname=' +encodeURIComponent(uname) &'pass=' + encodeURIComponent(pass)

应该是

data: 'uname='+encodeURIComponent(uname)+'&'+'pass='+encodeURIComponent(pass)

请注意+

后遗失的encodeURIComponent(uname)

答案 1 :(得分:0)

我在你的Ajax脚本上发现了一个小错误,你的&符号不是字符串的一部分:

data:'uname=' + encodeURIComponent(uname) &'pass=' + encodeURIComponent(pass),

应该是

data:'uname=' + encodeURIComponent(uname) + '&pass=' + encodeURIComponent(pass),

如果这不能解决问题,那么您可以查看以下几项内容:

  • 检查您的html
  • 上只有一个id为'name'的输入元素
  • 检查您的请求是否在您的servlet映射上转到了正确的servlet
  • 检查您没有任何拦截和修改/重定向请求的过滤器

除了你的代码看起来很好

答案 2 :(得分:0)

这个问题已经被清除了,但除了一个一个地传递值之外你可以一次提交整个表格,看看这个。

<script>
    // wait for the DOM to be loaded
    $(document).ready(function() 
    {
        // bind 'myForm' and provide a simple callback function
       $("#tempForm").ajaxForm({
       url:'../calling action or servlet',
       type:'post',
       beforeSend:function()
       {
         alert("perform action before making the ajax call like showing spinner image");
       },
       success:function(e){
        alert("data is"+e);
            alert("now do whatever you want with the data");
       }
       });
    });
</script>

你的表格就像这样

<form id="tempForm" enctype="multipart/form-data">
<input type="text" name="" id="" />
<input type="text" name="" id="" />
<input type="file" name="" id="" />
</form>

您可以在enter link description here

中找到插件