this is my first question and i wouldn't ask if i hadn't spent a long time trying to look for an answer in here. So here it goes.
I'm trying to make a simple CRUD application because i want to learn some basic ajax + servlets + java web development, the problem i have has probably got to do with the response, i have no idea of how to handle it so, the sql insert is done but when it comes back to the application it goes back to the servlet to give me a 500 error code.
So, here are my codes and some photos, i hope you can help me! Thanks.
AJAX CODE
//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);
}
}
SERVLET CODE
/*
* 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 GET
and POST
* 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("");
out.println("");
out.println("
");out.println("
Servlet servlet");out.println("");
out.println("
");out.println("
Servlet servlet at " + request.getContextPath() + "
");out.println("");
out.println("");
} finally {
out.close();
}
}
//
/**
* Handles the HTTP GET
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 POST
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("");
out.println("");
out.println("
");out.println("
Servlet servlet");out.println("");
out.println("
");out.println("
El dato se ha insertado correctamente
");out.println("");
out.println("");
} 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";
}//
}
HTML JSP
Document : index
Created on : 8/07/2015, 03:37:12 PM
Author : compract
--%>
UsuariosUsuarios
Ingrese los datos del nuevo usuario:
Nombre del usuario: Apellido del usuario:RegistrarCancelar Registrar-AjaxUsuarios
CLASS TO DO DATABASE STUFF
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
servlet
servlet.servlet
servlet
/servlet
30
index.jsp