這是我的servlet不能與這個servlet
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.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import org.json.JSONObject;
import org.json.simple.JSONObject;
import com.mysql.jdbc.Statement;
/**
* Servlet implementation class Login
*/
@WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection connection;
/**
* @see HttpServlet#HttpServlet()
*/
public Login() {
super();
// TODO Auto-generated constructor stub
}
public void init(ServletConfig config) throws ServletException {
ServletContext context = config.getServletContext();
String url = context.getInitParameter("dbUrl");
String dbUser = context.getInitParameter("dbUser");
String dbPassword = context.getInitParameter("dbPassword");
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url, dbUser, dbPassword);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void destroy() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
}
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("plain/text");
JSONObject json = new JSONObject();
PrintWriter out = response.getWriter();
String usernameV = request.getParameter("usernameV");
String passwordV = request.getParameter("passwordV");
json.put("ris", 0);
try {
String sql = "SELECT * FROM user WHERE username = ? AND password = ? ";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, usernameV);
stmt.setString(2, passwordV);
json.put("password", usernameV);
json.put("username", usernameV);
out.print(json.toJSONString());
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
json.replace("ris", 1);
out.print(json.toJSONString());
stmt.close();
rs.close();
return;
}
stmt.close();
rs.close();
} catch (SQLException e) {
json.replace("err", e.getMessage());
out.print(json.toJSONString());
}
out.print(json.toJSONString());``
}
}
處理POST請求,這裏是我的javascript
$(document).ready(function() {
\t $(window).keydown(function(event){//impedisco l'invio del form premendo invio
\t \t if(event.keyCode == 13) {
\t \t \t event.preventDefault();
\t \t \t return false;
\t \t }
\t });
\t
\t $("#bottone").click(function(){
\t \t $("#risultato").attr("style", "color: black;");
\t \t $("#risultato").html("Caricamento..."); \t
\t \t var username = $("#username").val();
\t \t var password = $("#password").val();
\t \t $.ajax({
\t \t \t type: "POST",
\t \t \t url: "Register",
\t \t \t //data: {"username" : username, "password": password},
\t \t \t data: "username=" + username + "&password=" + password,
\t \t \t dataType: "text",
\t \t \t success: function(msg)
\t \t \t { \t \t \t \t
\t \t \t \t var result = $.parseJSON(msg); \t \t \t \t
\t \t \t \t if(result.error){
\t \t \t \t \t switch (result.error) {
\t \t \t \t \t case 1:
\t \t \t \t \t \t Step();
\t \t \t \t \t \t
\t \t \t \t \t \t break;
\t \t \t \t \t default:
\t \t \t \t \t \t $("#risultato").html(msg);
\t \t \t \t \t break;
\t \t \t \t \t }
\t \t \t \t }else{
\t \t \t \t \t $("#bottone").prop('disabled', true);
\t \t \t \t \t $("#risultato").attr("style", "color: black;");
\t \t \t \t \t $("#risultato").html("Benvenuto " + username + "!");
\t \t \t \t } \t \t \t \t \t
\t \t \t },
\t \t \t error: function()
\t \t \t {
\t \t \t \t $("#risultato").attr("style", "color: red;");
\t \t \t \t $("#risultato").html("Errore di connessione!");
\t \t \t }
\t \t });
\t });
});
function Step() {
\t $("#risultato").attr("style", "color: red;");
\t $("#risultato").html("Username già esistente!<br>");
\t $("#risultato").append("<p>Inserisci la tua password : <input type='password' name='passwordV' id='passwordV'> <input type='button' id='bottone1' value='Login'> </p>");
\t
\t $("#bottone1").click(function(){
\t \t $("#res").attr("style", "color: black;");
\t \t $("#res").html("Caricamento..."); \t
\t \t var username = $("#username").val();
\t \t var password = $("#passwordV").val();
\t $.ajax({
\t \t type: "POST",
\t \t url: "Login",
\t \t data: "usernameV=" + username + "&passwordV=" + password,
\t \t dataType: "text",
\t \t success: function(msg)
\t \t { \t \t \t \t
\t \t \t var resulto = $.parseJSON(msg); \t \t \t \t
\t \t \t if(resulto.ris){
\t \t \t \t switch (resulto.ris) {
\t \t \t \t case 1:
\t \t \t \t \t $("#res").attr("style", "color: red;");
\t \t \t \t \t $("#res").html("Benvenuto " + username + "!");
\t \t \t \t \t
\t \t \t \t \t break;
\t \t \t \t default:
\t \t \t \t \t $("#res").html(msg);
\t \t \t \t break;
\t \t \t \t }
\t \t \t }else{
\t \t \t \t $("#bottone1").prop('disabled', true);
\t \t \t \t $("#res").attr("style", "color: black;");
\t \t \t \t $("#res").html("password errata:"+ password);
\t \t \t \t $("#stack").attr("style", "color: black;");
\t \t \t \t $("#stack").html(msg);
\t \t \t } \t \t \t \t \t
\t \t },
\t \t error: function()
\t \t {
\t \t \t $("#res").attr("style", "color: red;");
\t \t \t $("#res").html("Errore di connessione!");
\t \t }
\t });
\t });
}
\t
\t \t \t \t
\t
\t
\t
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Chat Room</title>
<script type="text/javascript" src="jquery-3.2.0.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form name="modulo" action="">
<p>
Nome utente: <input type="text" name="username" id="username">
Password: <input type="password" name="password" id="password">
<input type="button" id="bottone" value="Registrati!">
</p>
</form>
<div id="risultato"></div>
<div id ="res"></div>
<div id="stack"></div>
</body>
</html>
我還添加Register.java s ervlet ..這個可以工作,而且,正如你所看到的,它幾乎和登錄一樣。
package it.marco.chat.servlets;
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.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import org.json.JSONObject;
import org.json.simple.JSONObject;
import com.mysql.jdbc.Statement;
/**
* Servlet implementation class Register
*/
@WebServlet("/Register")
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection connection;
/**
* @see HttpServlet#HttpServlet()
*/
public Register() {
super();
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
ServletContext context = config.getServletContext();
String url = context.getInitParameter("dbUrl");
String dbUser = context.getInitParameter("dbUser");
String dbPassword = context.getInitParameter("dbPassword");
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url, dbUser, dbPassword);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see Servlet#destroy()
*/
public void destroy() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
}
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("plain/text");
JSONObject json = new JSONObject();
PrintWriter out = response.getWriter();
json.put("error", 0);
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
String sql = "SELECT * FROM user WHERE username = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, username);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
json.replace("error", 1);
out.print(json.toJSONString());
stmt.close();
rs.close();
return;
}
stmt.close();
rs.close();
} catch (SQLException e) {
}
int uid = -1;
try {
String sql = "INSERT INTO user(username,password) VALUES(?,?)";
PreparedStatement stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, username);
stmt.setString(2, password);
stmt.execute();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
uid = rs.getInt(1);
}
stmt.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
json.put("uid", uid);
out.print(json.toJSONString());
}
}
我不明白爲什麼在servlet無法處理POST請求。我的意思是,我已經建立了一個servlet,它hanldles寄存器組成部分,它完美的作品。 我已經嘗試了所有的晚上,使其工作,我很確定有一個愚蠢的錯誤,我無法看到,這就是爲什麼我來到這裏。 我希望有人能夠幫助我。 謝謝
什麼是你得到的迴應?如果您在瀏覽器中打開檢查元素>網絡,響應是什麼? –
它打印「Errore迪CONNESSIONE!」,這是印刷時,我在$就 – cancer
錯誤,您可以將您的HTML請 – Yussef