我使用jquery来向一个servlet发送ajax请求。
现在使用这样的GET请求时:
$("#nbtnLogin").click(function(){
login=$("#nloginIn").val();
passwd=$("#npasswdIn").val();
//alert(login + " " + passwd);
$.get(
"http://localhost:8080/EsLab2-Servlet-AsyncServerandClient/EsLab2Servlet",
{login:login, passwd:passwd, type:"i"},
function(data,stato){
alert("dati: " + data + "\n stato: " + stato);
$("#ajaxResponse1").empty().append(data +"\n");
},"text"
);
一切正常,但我得到回应,但是当我在$.get
$.post
时
$("#nbtnLogin").click(function(){
login=$("#nloginIn").val();
passwd=$("#npasswdIn").val();
//alert(login + " " + passwd);
$.post(
"http://localhost:8080/EsLab2-Servlet-AsyncServerandClient/EsLab2Servlet",
{login:login, passwd:passwd, type:"i"},
function(data,stato){
alert("dati: " + data + "\n stato: " + stato);
$("#ajaxResponse1").empty().append(data +"\n");
},"text"
);
最初保持待定状态,几秒钟后我收到错误代码500为什么?
package MyServlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="EsLab2Servlet",asyncSupported = true)
public class EsLab2Servlet extends HttpServlet {
Map<String, String> hashmap;
public EsLab2Servlet() {
hashmap=new HashMap<String, String>();
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// response.setContentType("text/html;charset=UTF-8");
//PrintWriter out = response.getWriter();
final AsyncContext context = request.startAsync();
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
final ServletInputStream input = request.getInputStream();
final ServletOutputStream output = response.getOutputStream();
System.out.println("ciao");
input.setReadListener(new ReadListenerImpl(input, output, context, hashmap));
// context.complete();
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
和
package MyServlet;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.swing.JOptionPane;
class ReadListenerImpl implements ReadListener {
private ServletInputStream input;
private ServletOutputStream output;
private AsyncContext context;
private Map<String, String> hashmap;
ReadListenerImpl(ServletInputStream input, ServletOutputStream output, AsyncContext context , Map hashmap) {
this.input = input;
this.output = output;
this.context = context;
this.hashmap = hashmap;
}
//metodi
protected synchronized String processLogin(HttpServletRequest request)throws ServletException, IOException{
String user = null;
String passwd= null;
String cont=null;
user=request.getParameter("login").toString();
passwd=request.getParameter("passwd").toString();
//cont = "Hello" + user + passwd;
if(passwd.equals("")){
cont="inserire password!";
}
else {
if((hashmap.containsKey(user))){
if((hashmap.get(user).compareTo(passwd))==0)
cont="login: OK";
else cont="login: Abort";
}
else cont="login: Abort";
/*hashmap.put(user,passwd);
cont=cont + "elemento inserito";
*/
}
return cont;
}
protected synchronized String processInsert(HttpServletRequest request)throws ServletException, IOException{
String user = null;
String passwd= null;
String cont=null;
user=request.getParameter("login").toString();
passwd=request.getParameter("passwd").toString();
//cont = "Hello" + user + passwd;
if(passwd.equals("") || user.equals("")){
cont="malformed request";
}
else {
if((hashmap.containsKey(user))){
cont="utente già presente";
}
else {
hashmap.put(user, passwd);
cont="insert: Ok";
}
}
return cont;
}
protected synchronized String processView(HttpServletRequest request)throws ServletException, IOException{
String cont = null;
String user = null;
user=request.getParameter("login").toString();
if((hashmap.containsKey(user))){
cont=hashmap.get(user);
}
else cont="utente non presente!";
return cont;
}
@Override
public void onDataAvailable() throws IOException {
System.out.println("onDataAvailable");
}
@Override
public void onAllDataRead() throws IOException {
System.out.println("ricevuti tutti i dati!...lancio il thread...");
context.start(new Runnable() {
String cont = null;
@Override
public void run() {
try {
System.out.println("Sono il thread adesso lavoro e poi ritorno disponibile...");
HttpServletRequest req = (HttpServletRequest) context.getRequest();
if (req.getParameter("type").compareTo("l") == 0 ) cont=processLogin(req);
else if (req.getParameter("type").compareTo("i") == 0) cont= processInsert(req);
else if (req.getParameter("type").compareTo("s") == 0) cont= processView(req);
output.println(cont);
output.flush();
} catch (ServletException ex) {
Logger.getLogger(ReadListenerImpl.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ReadListenerImpl.class.getName()).log(Level.SEVERE, null, ex);
} finally{
try {
input.close();
output.close();
context.complete();
} catch (IOException ex) {
Logger.getLogger(ReadListenerImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
}
@Override
public void onError(Throwable t) {
System.out.println("c'è un errore");
}
}
答案 0 :(得分:0)
如果您没有读取所有数据,则不会调用onAllDataRead上的回调。 下面是一个例子:
final ServletInputStream input = request.getInputStream();
input.setReadListener(new ReadListener() {
@Override
public void onDataAvailable() throws IOException {
byte b[]=new byte[1024];
while(input.isReady()&&input.read(b)!=-1){
}
}
@Override
public void onAllDataRead() throws IOException {
context.getResponse().getWriter().write("ciao");
context.complete();
}
@Override
public void onError(Throwable t) {
context.complete();
}
});