这是我的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());``
}
}
这是我的javascript
$(document).ready(function() {
$(window).keydown(function(event){//impedisco l'invio del form premendo invio
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
$("#bottone").click(function(){
$("#risultato").attr("style", "color: black;");
$("#risultato").html("Caricamento...");
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type: "POST",
url: "Register",
//data: {"username" : username, "password": password},
data: "username=" + username + "&password=" + password,
dataType: "text",
success: function(msg)
{
var result = $.parseJSON(msg);
if(result.error){
switch (result.error) {
case 1:
Step();
break;
default:
$("#risultato").html(msg);
break;
}
}else{
$("#bottone").prop('disabled', true);
$("#risultato").attr("style", "color: black;");
$("#risultato").html("Benvenuto " + username + "!");
}
},
error: function()
{
$("#risultato").attr("style", "color: red;");
$("#risultato").html("Errore di connessione!");
}
});
});
});
function Step() {
$("#risultato").attr("style", "color: red;");
$("#risultato").html("Username già esistente!<br>");
$("#risultato").append("<p>Inserisci la tua password : <input type='password' name='passwordV' id='passwordV'> <input type='button' id='bottone1' value='Login'> </p>");
$("#bottone1").click(function(){
$("#res").attr("style", "color: black;");
$("#res").html("Caricamento...");
var username = $("#username").val();
var password = $("#passwordV").val();
$.ajax({
type: "POST",
url: "Login",
data: "usernameV=" + username + "&passwordV=" + password,
dataType: "text",
success: function(msg)
{
var resulto = $.parseJSON(msg);
if(resulto.ris){
switch (resulto.ris) {
case 1:
$("#res").attr("style", "color: red;");
$("#res").html("Benvenuto " + username + "!");
break;
default:
$("#res").html(msg);
break;
}
}else{
$("#bottone1").prop('disabled', true);
$("#res").attr("style", "color: black;");
$("#res").html("password errata:"+ password);
$("#stack").attr("style", "color: black;");
$("#stack").html(msg);
}
},
error: function()
{
$("#res").attr("style", "color: red;");
$("#res").html("Errore di connessione!");
}
});
});
}
&#13;
<%@ 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 servlet ..这个工作正常,而且,正如您所看到的,它几乎与登录的一样。
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来处理寄存器部分并且它工作正常。 我整个晚上都试着让它发挥作用,我很确定这是一个我无法看到的愚蠢错误,这就是我来这里的原因。 我希望有人能够帮助我。 谢谢
答案 0 :(得分:0)
改变这个:
@WebServlet("/Login")
到
@WebServlet(name = "Login", urlPatterns = { "/Login" })
它会起作用相信我