本文介绍了如何使用Jquery将多个值传递给servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 < div class =ulogin> 
< h2>登入< / h2>
< div id =error>< / div>
< form action =Loginmethod =postid =spsignin>
< input type =textname =unameclass =text validate [required]id =nameplaceholder =Username/>
< input type =passwordname =passclass =text validate [required]id =passwordplaceholder =Password/>
< input type =submitvalue =id =memberlogin/>
< / form>
< / div>

我的javascript文件是

 
//停止提交请求
$(#spsignin {
e.preventDefault();
});

//检查按钮点击事件
$(#memberlogin)。click(function( e){

//获取表单数据,然后序列化
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,

//如果收到服务器的响应
成功:function(data,textStatus,jqXHR){
if(data.success)
{
$(#error)。html(< div>< b> success!< / b>< / div> + data);
}
//显示错误信息
else {
$(#error)。html(< div>< b>信息无效!< b个;< / DIV>中+数据);
}
},

//如果服务器没有响应
error:function(jqXHR,textStatus,errorThrown){
console。日志(发生的事情真的很糟糕+ textStatus);
$(#error)。html(jqXHR.responseText);
},

//在将请求发送到服务器之前捕获请求
beforeSend:function(jqXHR,settings){
//禁用按钮直到我们获得响应
$('#memberlogin')。attr(disabled,true);
$,

完成:function(jqXHR,textStatus){
//启用按钮
$('#memberlogin')。attr(disabled,假);
}

});
});
});

而且servlet是

 包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;
$ b $ **
* Servlet实现类登录
* /
@WebServlet(/ Login)
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
布尔成功= true;
$ b $ **
* @ see HttpServlet#HttpServlet()
* /
public Login(){
super();
// TODO自动生成的构造函数存根
}

public static Connection prepareConnection()抛出ClassNotFoundException,SQLException
{
String dcn =oracle。 jdbc.OracleDriver;
String url =jdbc:oracle:thin:@ // localhost:1521 / skypark;
String usname =system;
String pass =tiger;
Class.forName(dcn);
返回DriverManager.getConnection(url,usname,pass); (HttpServletRequest请求,HttpServletResponse响应)
* /
protected void doPost(HttpServletRequest请求,HttpServletResponse响应)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);
布尔suc;
尝试{
suc = check(uname,pass);
out.println(suc);
} catch(ClassNotFoundException | SQLException e){
// TODO自动生成的catch块
e.printStackTrace();
}


out.flush();
out.close();

public Boolean check(String uname,String pass)throws SQLException,ClassNotFoundException
{
ResultSet rs = null;
int i = 0;
连接con = prepareConnection();
String Query =select uname,passmanager pass from pass =?;
PreparedStatement ps = con.prepareStatement(Query);

尝试
{
ps.setString(1,pass);
rs = ps.executeQuery(); $(rs.next())
{
if(uname.equalsIgnoreCase(rs.getString(uname))|| uname.equalsIgnoreCase(rs.getString( email)))
{
rs.close();
ps.close();
ps = null; con.close();
con = null;
成功= true;
i = 1;
休息;
}
}
}
catch(Exception e)
{
System.out.println(e);
}

if(i == 0)
{
success = false;
}
返回成功;

$ b保护无效doGet(HttpServletRequest请求,HttpServletResponse响应)抛出ServletException,IOException
{
doPost(request,response);
}
}

我认为jquery是错误的。请任何一位帮助我克服这一点......

解决方案

问题出在这一行:



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



应该是

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



请注意, + code> encodeURIComponent(uname)


I have an Html form from that i need to pass values to servlet using jquery and there it will validates the information and returns the result.But when i try to pass the data using jQuery.The servlet showing that null value received.

<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>

My javascript file is

 $(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);
            }

        });       
 });
});

And the servlet is

  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);
}
  }

I think error is with jquery. please any one help me to overcome from this...

解决方案

The problem is with this line:

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

which should be

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

note the missing + after encodeURIComponent(uname)

这篇关于如何使用Jquery将多个值传递给servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 19:07