这是我的第一个问题,我不会问我是否花了很长时间在这里寻找答案。所以就这样了。
我试图制作一个简单的CRUD应用程序,因为我想学习一些基本的ajax + servlets + java web开发,我的问题可能与响应有关,我不知道如何处理它,sql插件已完成,但当它返回到应用程序时,它返回到servlet给我一个500错误代码。
所以,这是我的代码和一些照片,我希望你能帮助我!感谢。
AJAX代码
//Get XMLHTTP Object
function getXMLHTTPObject() {
var xmlhttpObject = null;
try {
// For Old Microsoft Browsers
xmlhttpObject = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
// For Microsoft IE 6.0+
xmlhttpObject = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e1) {
// No Browser accepts the XMLHTTP Object then false
xmlhttpObject = false;
}
}
if (!xmlhttpObject && typeof XMLHttpRequest != 'undefined') {
// For Mozilla, Opera Browsers
xmlhttpObject = new XMLHttpRequest();
}
// Mandatory Statement returning the ajax object created
return xmlhttpObject;
}
// Change the value of the outputText field
function setAjaxOutput() {
document.getElementById("res").innerHTML = xmlhttpObject.responseText;
}
function handleServerResponse() {
//Poner aqui un print para saber que paso con readyState
if (xmlhttpObject.readyState == 4) {
console.log("ReadyState " +xmlhttpObject.readyState);
if (xmlhttpObject.status == 200) {
setAjaxOutput();
} else {
console.log("ReadyState " +xmlhttpObject.status);
//alert("Error during AJAX call. Please try again");
}
}
}
// Implement business logic
function doAjaxCall() {
xmlhttpObject = getXMLHTTPObject();
if (xmlhttpObject != null) {
var URL = "servlet?action=ingresar&nombre=" + document.getElementById('firstname').value.toString() + "&apellido="+ document.getElementById('lastname').value.toString();
xmlhttpObject.open("POST", URL, true);
xmlhttpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
console.log(xmlhttpObject);
xmlhttpObject.onreadystatechange = handleServerResponse;
xmlhttpObject.send(null);
}
}
服务代码
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author compract
*/
public class servlet extends HttpServlet {
/**
* 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();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet servlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
// <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
*/
protected void Mensaje (HttpServletRequest request, HttpServletResponse response) throws IOException
{
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> El dato se ha insertado correctamente </h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
//hizo error porque no habia este parametro
String action = request.getParameter("action");
boolean usuarioregistrado = false;
if (action.equals("ingresar")) {
String nombre = request.getParameter("nombre");
String apellido = request.getParameter("apellido");
Usuario.Usuario u = new Usuario.Usuario();
u.setNombre(nombre);
u.setApellidoPaterno(apellido);
u.registrarUsuario();
usuarioregistrado = true;
// Mensaje(request, response);
}
if (usuarioregistrado) {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(request.getParameter("nombre"));
}
else {
//nothing to show
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
HTML JSP
<%--
Document : index
Created on : 8/07/2015, 03:37:12 PM
Author : compract
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<!-- Importamos javascript -->
<script language="JavaScript" type="text/javascript" src="ajax.js"></script>
<title>Usuarios</title>
</head>
<body>
<div id="header">
<h1>Usuarios</h1>
</div>
<!-- Inputs y comandos -->
<div id="inputsycomandos">
<!-- Hacemos llamada -->
<form action="servlet" method="POST">
<table border="0">
<thead>
<tr>
<th colspan="2">Ingrese los datos del nuevo usuario:</th>
</tr>
</thead>
<tbody>
<tr>
<td>Nombre del usuario:</td>
<td> <input type="text" name="firstname" id="firstname"> </td>
</tr>
<tr>
<td>Apellido del usuario:</td>
<td><input type="text" name="lastname" id="lastname"></td>
</tr>
<tr>
<td><button id="ingresarnuevo" type="submit">Registrar</button></td>
<td><button id="cancelar">Cancelar</button></td>
</tr>
<tr>
<td> <button id="registrarconajax" onclick="doAjaxCall()">Registrar-Ajax</button></td>
<td></td>
</tr>
</tbody>
</table>
</form>
<p id="res">
</div>
<div id="datatable">
<h1>Usuarios</h1>
</div>
<div id="footer">
</div>
</body>
</html>
类别数据库
package Usuario;
import java.sql.*;
/**
*
* @author compract
*/
public class Usuario {
String idUsuario;
String nombre;
String apellidoPaterno;
public String getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(String idUsuario) {
this.idUsuario = idUsuario;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellidoPaterno() {
return apellidoPaterno;
}
public void setApellidoPaterno(String apellidoPaterno) {
this.apellidoPaterno = apellidoPaterno;
}
public void registrarUsuario()
{
SingletonConectar.singletonConectar sin = SingletonConectar.singletonConectar.getDbCon();
try {
String query = "INSERT INTO USUARIOS(ID_USUARIO, NOMBRE_USUARIO,APELLIDO_USUARIO) VALUES (null, ?,?)";
PreparedStatement preparedStmt = sin.db.conn.prepareStatement(query);
preparedStmt.setString (1, nombre);
preparedStmt.setString (2, apellidoPaterno);
preparedStmt.execute();
} catch (Exception e) {
{
}
}
}
}
WEB XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>servlet</servlet-name>
<servlet-class>servlet.servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet</servlet-name>
<url-pattern>/servlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>