request.getParameter returns null in servlet - java

I have the following code and the problem is that out.println("Clave= " +request.getParameter("clave")+"."); writes null.
I have been searching a solution in this forum but I can't find anything.
HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registro de votante</title>
<link href="estilos.css" rel="stylesheet" type="text/css">
</head>
<body>
<form method="post" action="CreaVotante">
<div id="reg">
<table>
<tr>
<td colspan="2">
<h1>Regístrate para votar</h1>
</td>
</tr>
<tr>
<td>
<p>NIF</p>
</td>
<td>
<input type="text" name="nif">
</td>
</tr>
<tr>
<td>
<p>Clave</p>
</td>
<td>
<input type="text" name="clave">
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" name="registro">
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Servlet:
package Controlador;
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 Lux
*/
public class CreaVotante 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");
try (PrintWriter out = response.getWriter()) {
/* 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 CreaVotante</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Nif= " +request.getParameter("nif")+ "</h1>");
out.println("<h1>Clave= " +request.getParameter("clave")+ "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <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);
}
}

Related

HTTP Status 500 – Internal Server Error. Problem with JSP servlet

I'm new to NetBeans and JSP Servlet and I'm trying to create a Web Application using JSP Servlet in Apache NetBeans 11.1 and I keep getting this error:
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Error instantiating servlet class [controller.NewServlet]
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: Error instantiating servlet class [controller.NewServlet]
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
I tried uninstalling Netbeans and Tomcat server and reinstall them but still, got the same error.
This is what my Web.xml looks like:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>controller.NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
My servlet
package controller;
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 sagarluitel
*/
public class NewServlet 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");
try ( PrintWriter out = response.getWriter()) {
/* 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 NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet NewServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <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>
}
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Sign up here</h1>
<form action="NewServlet" method="post" onsubmit="return validateForm();">
<input type="hidden" name="action" value="signup">
<label>First Name</label>
<input type="text" id="firstName" name="firstName" placeholder="First Name" required><br>
<label>Last Name</label>
<input type="text" id="lastName" name="lastName" placeholder="Last Name" required><br>
<label>Email</label>
<input type="email" id="email" name="email" placeholder="Email" required><br>
<label>Password</label>
<input type="password" id="password" name="password" placeholder="Password" required><br>
<i>Use 8 or more characters with a mix of letters, numbers & symbols</i><br>
<input type="submit" value="Submit"><br>
</form>
</body>
</html>
File path:
WebApplication
Web Pages
META-INF
WEB-INF
web.xml
index.jsp
Source Packages
controller
NewServlet.java
My problem is not same as this (HTTP Status 500 - Error instantiating servlet class pkg.coreServlet) because My src folder is not in the WEB-INF directory.
Can someone please help me with this, I don't know what am I missing or doing wrong. I'm using macOS Catalina, got the same error while using the previous version of Mac as well.

Sending a request through Ajax to a servlet (non spring) [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 4 years ago.
I have a CRUD table that lists a bunch of products, what I need is that when I click on a button, Ajax automatically sends a request to the servlet telling it that I want to change the state (instead of deleting the product) in the database, then after that is done it should reload the table.
I already have most of the code done, here is the AJAX that I had (Which I suppose is the part that is wrong), I was working on it trying to get it to work when I clicked on a row so ignore that part, there's a delete button per row).
<script>
$("#test").on('click','tr',function() {
var id = $(this).find("td:first-child").text();
console.log(id);
$.ajax({
url: "statecontroller.do",
type: 'POST',
data: { id : id},
success: function() {
}
});
});
</script>
And here is the servlet code:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
ProductDAO productBD = new ProductDAO();
Product products = productBD.selectById(id);
if(products.getState() == "Active"){
Product product = new Product(id,"Not Active");
productBD.update(product);
ArrayList<Product> productList = new ArrayList<>();
productList = productBD.selectAll();
request.getSession().setAttribute("productList", productList);
request.getRequestDispatcher("/wproduct/listing.jsp").forward(request, response);
}else if(products.getState() == "Not Active"){
Product product = new Product(id,"Active");
productBD.update(product);
ArrayList<Product> productList = new ArrayList<>();
productList = productBD.selectAll();
request.getSession().setAttribute("productList", productList);
request.getRequestDispatcher("/wproduct/listing.jsp").forward(request, response);
}
}
I tried looking it up but only found how to do this with Spring
(Here is the full servlet code, it has Spanish names on it which is why I translated it for the original post):
package controladores;
import daos.ClienteDAO;
import dtos.Cliente;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author lycan
*/
#WebServlet(name = "ControladorEstado", urlPatterns = {"/controladorestado.do"})
public class ControladorEstado 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 {
int id = Integer.parseInt(request.getParameter("id"));
ClienteDAO clientebd = new ClienteDAO();
Cliente clientes = clientebd.selectById(id);
if(clientes.getEstado() == "Activo"){
Cliente cliente = new Cliente(id,"No Activo");
clientebd.update(cliente);
ArrayList<Cliente> lista = new ArrayList<>();
lista = clientebd.selectAll();
request.getSession().setAttribute("lista", lista);
request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);
}else if(clientes.getEstado() == "No Activo"){
Cliente cliente = new Cliente(id,"Activo");
clientebd.update(cliente);
ArrayList<Cliente> lista = new ArrayList<>();
lista = clientebd.selectAll();
request.getSession().setAttribute("lista", lista);
request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);
}
}
// <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>
}
And here is the listing code:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%--
Document : listar
Created on : 19-oct-2018, 11:00:29
Author : lycan
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%#include file="../WEB-INF/jspf/estilos.jspf"%>
<title>Sistema Ventas</title>
</head>
<body>
<div class="container-fluid">
<%#include file="../WEB-INF/jspf/header.jspf"%>
<%#include file="../WEB-INF/jspf/nav.jspf"%>
<section>
<table id="test" class="table table-bordered">
<thead class="thead-dark">
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Descripcion</th>
<th>Categoria</th>
<th>Estado</th>
<th><i class="fas fa-binoculars"></i></th>
<th><i class="fas fa-pen-alt"></i></th>
<th><i class="fas fa-user-times"></i></th>
</tr>
</thead>
<tbody>
<c:forEach var="clientes" items="${sessionScope.lista}">
<tr>
<td>${clientes.id}</td>
<td>${clientes.nombre}</td>
<td>${clientes.descripcion}</td>
<td>${clientes.categoria}</td>
<td>${clientes.estado}</td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=detalle&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Detalle</a></td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=actualizar&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Actualizar</a></td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=eliminar&id=${clientes.id}" class="btn btn-primary btn-lg eliminar" role="button" >Eliminar</a></td>
</tr>
</c:forEach>
</tbody>
</table>
Registrar
Buscar
</section>
<%#include file="../WEB-INF/jspf/footer.jspf"%>
</div>
<%#include file="../WEB-INF/jspf/js.jspf"%>
<script>
$("#test").on('click','tr',function() {
var id = $(this).find("td:first-child").text();
console.log(id);
$.ajax({
url: "controladorestado.do",
type: 'POST',
data: { id : id},
success: function() {
}
});
// Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
</script>
</body>
</html>
okay i see what you are doing now, thanks for including more information. The reason why nothing happens is because in your servlet you are trying to return the same page you are making the ajax call from. (and you're not even handling the response)
From the looks of it, you want to return a table through the ajax method, but in order to do that you need to create a separate jsp that you will return.. For example:
create a new jsp called user-table inside /wcliente/
user-table.jsp
<?xml version="1.0" encoding="UTF-8"?>
<%#page contentType="application/xml" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<data>
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Descripcion</th>
<th>Categoria</th>
<th>Estado</th>
<th><i class="fas fa-binoculars"></i></th>
<th><i class="fas fa-pen-alt"></i></th>
<th><i class="fas fa-user-times"></i></th>
</tr>
</thead>
<tbody>
<c:forEach var="clientes" items="${lista}">
<tr>
<td>${clientes.id}</td>
<td>${clientes.nombre}</td>
<td>${clientes.descripcion}</td>
<td>${clientes.categoria}</td>
<td>${clientes.estado}</td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=detalle&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Detalle</a></td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=actualizar&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Actualizar</a></td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=eliminar&id=${clientes.id}" class="btn btn-primary btn-lg eliminar" role="button" >Eliminar</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</data>
Now in your servlet, instead of this:
request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);
do this:
request.getRequestDispatcher("/wcliente/user-table.jsp").forward(request, response);
For the ajax in your listar.jsp do this instead:
<script>
$("#test").on('click','tr',function() {
var id = $(this).find("td:first-child").text();
$.post("controladorestado.do", {id : id}, function(responseXml) { // Execute Ajax POST request on URL of "controladorestado.do" and execute the following function with Ajax response XML...
$("#test").html($(responseXml).find("data").html()); // Parse XML, find <data> element and append its HTML to HTML DOM element with ID "test".
});
});
</script>
Reference:
How to use Servlets and Ajax?

Java Servlet redirect to page auto calls its form servlet

the problem to when I fill in the form it calls a servlet, which displays the correct information, when the user clicks the back button it seems to call the servlet on that page with the value null. How do i make it so it reloads the page so the user can refill in the form.
SetTimeZone.xhtml
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>SetTimeZone</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div>
<form name ="SetTimeZone" method="post" action="SetTimeZoneServlet">
Set Time Zone: <input type="text" name="timeZone"/><br></br><br></br>
<input type ="submit" value="Submit" name="submit"/>
</form>
</div>
</body>
public class SetTimeZoneServlet extends HttpServlet {
/**
* 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 {
TimeZoneBean bean = new TimeZoneBean();
String city = request.getParameter("timeZone");
bean.setCity(city);
String temp = bean.checkCity();
String value = "";
if ("error".equals(temp)) {
value = "Sorry no information is availible for " + city;
} else {
value = "The current time in " + city + " is " + bean.getTime();
}
try (PrintWriter out = response.getWriter()) {
response.setContentType("text/html;charset=UTF-8");
/* 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 OrderFormServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>" + value + "</p>");
out.println("<form name=\"SetTimeZone.xhtml\" method=\"post\" name=\""
+ "SetTimeZoneRedirectServlet\"> ");
out.println("<input type =\"submit\" value=\"Back\"/ name=\"back\">");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
}
public class SetTimeZoneRedirectServlet 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.sendRedirect("SetTimeZone.xhtml");
}
}
The output i get after the redirect back to the page is;
Sorry no information is available for null.
Try Using the GET Instead of POST
This may solve your problem
By using the POST method for your form you may encounter this problem. As #visray suggested, you need to override the doGet() Servlet method for the GET method to work correctly.
POST method should be used when dealing with database changes, so in your case GET is appropriate.

java servlet getparameter return null

I have a page that uses a servlet
<!DOCTYPE html>
<!--
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.
-->
<html>
<head>
<title>Estoque Online - Registro</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/js/materialize.min.js"></script>
</head>
<body>
<div>
<FORM ACTION="ValidaRegistro" method="post">
<label>
<font size="6">
Cadastro de Usuários
</font>
</label><br>
<label for="Nome">
<font size ="4">
Nome
</font>
</label>
<input autocomplete="on" type="Text" name="inNome" id="Nome">
<label for="Email">
<font size="4">
Email
</font>
</label>
<input autocomplete="on" type="Text" name="inEmail" id="Email">
<label for="Senha">
<font size="4">
Senha
</font>
</label>
<input type="password" name="inSenha" id="Senha">
<label for="Tipo">
<font size="4">
Tipo
</font>
</label>
<input type="Text" name="inTipo" id="Tipo">
<input type="submit" id="Submeter" value="Submeter" class="btn waves-effect waves-light col s12">
</FORM>
</div>
</body>
</html>
This is the page
/*
* 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.
*/
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;
import javax.swing.JOptionPane;
import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.annotation.WebServlet;
/**
*
* #author Rafael
*/
/**
*
* #author Rafael
*/
public class ValidaRegistro 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");
try (PrintWriter out = response.getWriter()) {
/* 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 ValidaRegistro</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet ValidaRegistro at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <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 {
String Nome = (String)request.getParameter("Nome");
String Email =(String)request.getParameter("Email");
String Senha =(String)request.getParameter("Senha");
int Tipo = Integer.parseInt(request.getParameter("Tipo"));
DAO.main(null);
try {
Inserir(Nome,Email,Senha,Tipo);
} catch (SQLException ex) {
Logger.getLogger(ValidaRegistro.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
public void Inserir(String Nome,String Email,String Senha,int Tipo) throws SQLException{
DAO.Inserir(Nome,Email,Senha,Tipo);
}
}
And this is the servlet, but in doPost Method request.getParameters always return null and i don't know why.
I tried to change to request.getAtributes but the result is the same.
Please help me.
Hi can you try the below
String Nome = (String)request.getParameter("inNome");
String Email =(String)request.getParameter("inEmail");
String Senha =(String)request.getParameter("inSenha");
int Tipo = Integer.parseInt(request.getParameter("inTipo"));
Form parameters are identified by name, not by ID. You should use the same value for both name and ID and in the getParameter() method.

Unable to send Client's timestamp to the server

Please check the below code
JSP
<%--
Document : index
Created on : Sep 8, 2015, 10:13:49 AM
Author : Yohan
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page contentType="text/html" import="java.util.Date" %>
<%#page contentType="text/html" import="java.sql.Timestamp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
function time()
{
var elem = document.getElementById("hiddenTxt");
elem.value = "<%= new Date().getTime()%>";
}
</script>
<script type="text/javascript">
function time2()
{
var elem = document.getElementById("hiddenTxt");
elem.value = Date.now();
}
</script>
<script type="text/javascript">
function time3()
{
alert(<%= new Date().getTime()%>);
}
</script>
</head>
<body>
<button onclick="time3()" value="click" >Click</button>
<form action="TimestampClass" method="post" onsubmit="time2()">
Name: <input type="text" name="nameTxt">
<input type="hidden" name="hiddenTxt" id="hiddenTxt" >
<input type="submit" value="Submit">
</form>
</body>
</html>
Servlet
package test;
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;
import java.sql.*;
/**
*
* #author Yohan
*/
public class TimestampClass 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");
// long currentTimeMillis = System.currentTimeMillis();
// Timestamp timestamp = new Timestamp(currentTimeMillis);
// System.out.println(currentTimeMillis);
// System.out.println(timestamp);
String name = request.getParameter("nameTxt");
long timeStampLong = Long.parseLong(request.getParameter("hiddenTxt"));
PrintWriter out = response.getWriter();
out.println(name);
out.println("<br>");
out.println("Script Time: "+getSQLCurrentTimeStamp( timeStampLong));
out.println("<br>");
out.println("Normal Time: "+getSQLCurrentTimeStamp());
}
public static java.sql.Timestamp getSQLCurrentTimeStamp(long timeStampLong)
{
Timestamp t2= new Timestamp(timeStampLong);
return t2;
}
public static java.sql.Timestamp getSQLCurrentTimeStamp()
{
java.util.Date date= new java.util.Date();
Timestamp t= new Timestamp(date.getTime());
System.out.println(t);
return t;
}
// <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>
}
All I want is to send the current time of the client PC to the server. I have tried both Javascript and Java inside JSP.
But there is an issue with the Javascript. I have my server in amazon EC2 US-West and I am in Sri Lanka. The time difference is +5.30GMT
When I deploy the code, the javascript simply gets the time of the server, not the time in my computer.
I tried using Java inside JSP and it is having another issue. That is, no matter where I place the new Date.getTime(), it is always getting the time the web page was loaded and it won't change even after minutes.
What am I doing here wrong? All I want is to send the current time of the client to the Server side Servlet.
The snippet:
<%= new Date().getTime()%>
will always get the server time, so forget about using that.
To get the client timestamp you need to use JavaScript. In your HEAD section add this (within script tags of course):
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
This sets up the Date.now function in case the client uses Internet Explorer 8, which doesn't know Date.now
I don't know how JavaScript optimizes code. Maybe you could try this to see if it makes a difference if the Date is determined inside a function or not:
<form action="TimestampClass" method="post" onsubmit="document.getElementById('hiddenTxt') = Date.now();">
Name: <input type="text" name="nameTxt">
<input type="hidden" name="hiddenTxt" id="hiddenTxt" >
<input type="submit" value="Submit">
</form>
Try to use JS function to get time
function time3(){
alert(new Date().getTime());
}

Categories

Resources