java servlet getparameter return null - java

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.

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.

request.getParameter returns null in servlet

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);
}
}

How can i get data from a servlet into a JSP page?

I am developing a small sql servlet application that takes in a SQL command from a text area in an html page, sends the command to a servlet that makes an sql connection and puts in the resultset into an arraylist. I have all of that down, and i can print column names to the browser in the java servlet class. One thing i need to do is print the results into a table using a JSP page. The JSP page will look just like the html page we first used. I can not figure out how i am going to get the arraylist from the servlet to the JSP page to be displayed to the user.
Here is the HTML page:
<html>
<head>
<title>WebApp</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="background-color:blue;">
<center>
<font color="white">
<h1> Welcome to the Project 4 Remote Database Management System</h1>
<hr>
You are connected to the Project4 database. <br>Please enter any valid SQL query or update statement.<br>
If no query/update command is given the Execute button will display all supplier information in the database. <br>All execution results will appear below.
<br>
<br>
<form action="NewServlet" method="post">
<textarea rows="10" cols="60"name="command"></textarea>
<br>
<button type="submit">Execute Query</button>
<button type="submit">Clear Command</button>
</form>
<hr>
<h1>Database Results</h1>
</font>
</body>
</html>
and here is the servlet code:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
/**
*
* #author KJ4CC
*/
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
*/
Connection connection;
Vector<String> columnNames = new Vector<String>();
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. */
String command = request.getParameter("command");
out.println("<!DOCTYPE html>");
out.println("<html>");
sqlConnection(command);
//prints out column names into the browser.
out.println(columnNames);
}
}
public void sqlConnection(String command){
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/project3";
String user = "root";
String pass = "Brandy?1994";
ResultSet rs;
try {
Class.forName(driver);
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
try {
connection = DriverManager.getConnection(url,user,pass);
} catch (SQLException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
Statement stmt;
try {
stmt = connection.createStatement();
rs = stmt.executeQuery(command);
int colNum = rs.getMetaData().getColumnCount();
for (int i = 0; i < colNum; i++) {
columnNames.add(rs.getMetaData().getColumnLabel(i+1));
}
} catch (SQLException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
// <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>
}
Here is the start of the JSP page:
<html>
<head>
<title>WebApp</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="background-color:blue;">
<center>
<font color="white">
<h1> Welcome to the Project 4 Remote Database Management System</h1>
<hr>
You are connected to the Project4 database. <br>Please enter any valid SQL query or update statement.<br>
If no query/update command is given the Execute button will display all supplier information in the database. <br>All execution results will appear below.
<br>
<br>
<form action="NewServlet" method="post">
<textarea rows="10" cols="60"name="command"></textarea>
<br>
<button type="submit">Execute Query</button>
<button type="submit">Clear Command</button>
</form>
<hr>
<h1>Database Results</h1>
<%
DO TABLE STUFF HERE TO OUTPUT SQL RESULTS
%>
</font>
</body>
</html>
I think i will create a javaBean to store the arrays so that the JSP page can access the column arraylist. Then use a for loop to iterate through the array list so that i can create the table columns. how could i link the JSP page to the servlet so that if can get the information needed?
I have to do the sql connection in the servlet and cannnot make the connection in the JSP page.
In your servlet method, set attribute in page context as below
HttpServletRequest req = (HttpServletRequest)request;
.... // find out what to put
req.getPageContext.setAttribute('some', objectYouFound);
In your jsp, use el to access the variable:
${some}
In the servlet, store the data in a request attribute:
request.setAttribute("rows", rows);
In the JSP, use the JSTL to loop over the rows:
<c:forEach var="row" value="${rows}">
...
</c:forEach>
Do NOT use Java scriptlets in your JSP.
You have few issues with your current code:
(1) A single servlet instance will be shared across all request threads, so you should NOT create the instance variables for a servlet class i.e.,
Connection connection;
Vector<String> columnNames = new Vector<String>();
These two variables should be created inside your processRequest() method so that they will be local to each request thread.
(2) You are ONLY querying the META DATA of the table, so you can display only column names, but if you wanted to fetch the data as well, you need to use resultSetObj.hasNext() and then use next() method like below:
while (rs.hasNext())
{
String X = rs.getString("empno");
//Retrieve all data
//add to a bean object
//add to list
}
//Now return the list which contains the data
You can look at here for a good example.
(3) Use the request.setAttribute to set the results to the request object and then you can retrieve to the next JSP (results) page.

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());
}

Netbeans and glassfish HTTP ERROR 404

I need your help. I had made a source code for a web appl but I have this error when I click on the "add" submit button and I have the same error on the others submit button. My source code is :
filoptwxoinfo.jsp :
<%--
Document : index
Created on : 17 Δεκ 2012, 6:39:05 μμ
Author : Editor
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Πληροφορίες Φιλοπτώχου</title>
</head>
<body>
<table border="1">
<td>Μέλη Φιλοπτώχου</td>
<td>Σύνολο Φιλοπτώχου</td>
</table>
</br>
<form action=".FiloptwxoServlet" method="POST">
<table>
<tr>
<td>Α.Φ.Μ. :</td>
<td><input type="text" name="afm" value="${filoptwxo.afm}"/></td>
</tr>
<tr>
<td>Όνομα :</td>
<td><input type="text" name="name" value="${filoptwxo.name}"/></td>
</tr>
<tr>
<td>Επώνυμο:</td>
<td><input type="text" name="lastname" value="${filoptwxo.lastname}"/></td>
</tr>
<tr>
<td>Πατρώνυμο:</td>
<td><input type="text" name="fathername" value="${filoptwxo.fathername}"/></td>
</tr>
<tr>
<td>Διεύθυνση Οικείας:</td>
<td><input type="text" name="address" value="${filoptwxo.address}"/></td>
</tr>
<tr>
<td>Τηλέφωνο:</td>
<td><input type="text" name="number" value="${filoptwxo.number}"/></td>
</tr>
<tr>
<td>Μέλη Οικογενείας:</td>
<td><input type="text" name="numberop" value="${filoptwxo.numberop}"/></td>
</tr>
<tr>
<td colspan="2"><input type="Submit" name="operation" value="Add" />
<input type="Submit" name="operation" value="Edit" />
<input type="Submit" name="operation" value="Delete" />
<input type="Submit" name="operation" value="Search" />
</tr>
</table>
</form>
</body>
</html>
Fullfiloptwxo.jsp :
<%--
Document : FullFiloptwxo
Created on : Dec 17, 2012, 6:47:52 PM
Author : Editor
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Λίστα Μελών Φιλοπτώχου</title>
</head>
<body>
<table border="1">
<td>Μέλη Φιλοπτώχου</td>
<td>Σύνολο Φιλοπτώχου</td>
</table>
<br />
<h3> Λίστα Μελών </h3>
<table border="1">
<th> Α.Φ.Μ. </th>
<th> Όνομα </th>
<th> Επώνυμο </th>
<th> Πατρώνυμο </th>
<th> Διεύθυνση Οικείας </th>
<th> Τηλέφωνο </th>
<th> Μέλη Οικογενείας </th>
<c:forEach items="${requestScope.list}" var="Filoptwxo">
<tr>
<td>${filoptwxo.afm}</td>
<td>${filoptwxo.name}</td>
<td>${filoptwxo.lastname}</td>
<td>${filoptwxo.fathername}</td>
<td>${filoptwxo.address}</td>
<td>${filoptwxo.phone}</td>
<td>${filoptwxo.numberop}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Filoptwxo.java :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model;
/**
* #author Editor
*/
public class Filoptwxo {
private String afm;
private String name;
private String lastname;
private String address;
private String fathername;
private String numberop;
private String phone;
public String getAfm() {
return afm;
}
public void setAfm(String afm) {
this.afm = afm;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getFathername() {
return fathername;
}
public void setFathername(String fathername) {
this.fathername = fathername;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getNumberop() {
return numberop;
}
public void setNumberop(String numberop) {
this.numberop = numberop;
}
public Filoptwxo(String afm, String name, String lastname, String fathername, String address, String phone, String numberop ){
this.afm = afm;
this.name = name;
this.lastname = lastname;
this.fathername = fathername;
this.address = address;
this.numberop = numberop;
this.phone = phone;
}
public Filoptwxo(){}
}
FiloptwxoDAO.java :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model.ejb;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.sql.DataSource;
import model.Filoptwxo;
/**
* #author Editor
*/
#Stateless
public class FiloptwxoDAO {
#Resource(name="jdbc/filoptwxoDB")
private DataSource ds;
public void addFiloptwxo (Filoptwxo filoptwxo) {
String sql = "INSERT INTO FILOPTWXO VALUES('"+ filoptwxo.getAfm() +"', '"+ filoptwxo.getName() +"', '"+ filoptwxo.getLastname() +"', '"+ filoptwxo.getFathername() +"', '"+ filoptwxo.getAddress() +"', '"+ filoptwxo.getPhone() +"', '"+ filoptwxo.getNumberop() +"')";
executeModifyQuery(sql);
}
public void editFiloptwxo (Filoptwxo filoptwxo) {
String sql = "UPDATE FILOPTWXO SET NAME='" + filoptwxo.getName() +"', ADDRESS" + filoptwxo.getAddress() +"', LASTNAME" + filoptwxo.getLastname() +"', FATHERNAME" + filoptwxo.getFathername() +"', PHONE" + filoptwxo.getPhone() +"', NUMBEROP" + filoptwxo.getNumberop() +"' WHERE AFM='"+ filoptwxo.getAfm() +"'";
executeModifyQuery(sql);
}
public void deleteFiloptwxo(Filoptwxo filoptwxo) {
String sql = "DELETE FROM STUDENT WHERE AFM= '"+ filoptwxo.getAfm() + "'";
executeModifyQuery(sql);
}
public Filoptwxo getFiloptwxo(String afm) {
Filoptwxo filoptwxo = new Filoptwxo();
String sql = "SELECT * FROM FILOPTWXO WHERE AFM='"+ afm+"'";
System.out.println(sql);
ResultSet rs = executeFetchQuery(sql);
try {
if (rs.next()){
filoptwxo.setAfm(rs.getString("AFM"));
filoptwxo.setName(rs.getString("NAME"));
filoptwxo.setLastname(rs.getString("LASTNAME"));
filoptwxo.setFathername(rs.getString("FATHERNAME"));
filoptwxo.setAddress(rs.getString("ADDRESS"));
filoptwxo.setPhone(rs.getString("PHONE"));
filoptwxo.setNumberop(rs.getString("NUMBEROP"));
}
} catch (Exception ex) {
System.err.println("GS" + ex.getMessage());
}
return filoptwxo;
}
public ArrayList<Filoptwxo> getFullFiloptwxo() {
ArrayList<Filoptwxo> list = new ArrayList<Filoptwxo>();
String sql = "SELECT * FROM FILOPTWXO";
ResultSet rs = executeFetchQuery(sql);
try {
while(rs.next()) {
Filoptwxo filoptwxo = new Filoptwxo();
filoptwxo.setAfm(rs.getString("AFM"));
filoptwxo.setName(rs.getString("NAME"));
filoptwxo.setLastname(rs.getString("LASTNAME"));
filoptwxo.setFathername(rs.getString("FATHERNAME"));
filoptwxo.setAddress(rs.getString("ADDRESS"));
filoptwxo.setPhone(rs.getString("PHONE"));
filoptwxo.setNumberop(rs.getString("NUMBEROP"));
list.add(filoptwxo);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return list;
}
public void executeModifyQuery(String sql) {
try {
Connection conn = ds.getConnection();
conn.createStatement().execute(sql);
conn.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public ResultSet executeFetchQuery(String sql) {
ResultSet rs = null;
try {
Connection conn = ds.getConnection();
rs = conn.createStatement().executeQuery(sql);
conn.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
return rs;
}
}
FiloptwxoServlet.java :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import java.io.IOException;
import javax.ejb.EJB;
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 model.Filoptwxo;
import model.ejb.FiloptwxoDAO;
/**
* #author Editor
*/
#WebServlet(name = "FiloptwxoServlet", urlPatterns = {"/FiloptwxoServlet"})
public class FiloptwxoServlet extends HttpServlet {
#EJB private FiloptwxoDAO filoptwxoDAO;
/**
* 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 {
String afm = request.getParameter ("afm");
String name = request.getParameter ("name");
String lastname = request.getParameter ("lastname");
String fathername = request.getParameter ("fathername");
String address = request.getParameter ("address");
String phone = request.getParameter ("phone");
String numberop = request.getParameter ("numberop");
String operation = request.getParameter ("operation");
Filoptwxo filoptwxo = new Filoptwxo(afm, name, lastname, fathername, address, phone, numberop);
if (operation.equalsIgnoreCase("Add")) {
filoptwxoDAO.addFiloptwxo(filoptwxo);
request.setAttribute("filoptwxo", filoptwxo);
} else if (operation.equalsIgnoreCase("Edit")) {
filoptwxoDAO.editFiloptwxo(filoptwxo);
Filoptwxo searchedFiloptwxo = filoptwxoDAO.getFiloptwxo(afm);
request.setAttribute("filoptwxo", searchedFiloptwxo);
} else if (operation.equalsIgnoreCase("Delete")) {
filoptwxoDAO.deleteFiloptwxo(filoptwxo);
} else if (operation.equalsIgnoreCase("Search")) {
Filoptwxo searchedFiloptwxo = filoptwxoDAO.getFiloptwxo(afm);
request.setAttribute("filoptwxo", searchedFiloptwxo);
}
request.getRequestDispatcher("filoptwxoinfo.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>
}
FullFiloptwxo.java :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import java.io.IOException;
import java.util.ArrayList;
import javax.ejb.EJB;
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 model.Filoptwxo;
import model.ejb.FiloptwxoDAO;
/**
* #author Editor
*/
#WebServlet(name = "FullFiloptwxo", urlPatterns = {"/FullFiloptwxo"})
public class FullFiloptwxo extends HttpServlet {
#EJB private FiloptwxoDAO filoptwxoDAO;
/**
* 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 {
ArrayList<Filoptwxo> list = filoptwxoDAO.getFullFiloptwxo();
request.setAttribute("list", list);
request.getRequestDispatcher("FullFiloptwxo.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>
}
GetFiloptwxo.java :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import java.io.IOException;
import javax.ejb.EJB;
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 model.Filoptwxo;
import model.ejb.FiloptwxoDAO;
/**
* #author Editor
*/
#WebServlet(name = "GetFiloptwxo", urlPatterns = {"/GetFiloptwxo"})
public class GetFiloptwxo extends HttpServlet {
#EJB private FiloptwxoDAO filoptwxoDAO;
/**
* 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 {
String afm = request.getParameter("afm");
Filoptwxo filoptwxo = filoptwxoDAO.getFiloptwxo(afm);
request.setAttribute("filoptwxo", filoptwxo);
request.getRequestDispatcher("filoptwxoinfo.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>
}
web-xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>filoptwxoinfo.jsp</welcome-file>
</welcome-file-list>
</web-app>
This was the source code which I used but I have the problem with HTTP ERROR 404, I don't know what else I must do... I am trying to find a solution 2 days now so this is the reason that I wrote the whole code.
form action=".FiloptwxoServlet" has a period in front.
you should call the servlet as you have defined it :
#WebServlet(name = "FiloptwxoServlet", urlPatterns = {"/FiloptwxoServlet"})
wrong
<form action=".FiloptwxoServlet" method="POST">
ok
<form action="FiloptwxoServlet" method="POST">
Change all links to .jsp files (in all your .java files)
"filoptwxoinfo.jsp" to
"/WEB-INF/filoptwxoinfo.jsp"
The action attribute of a HTML can point to a servlet URL and the method="post" would trigger the servlet's doPost() method where you have all the freedom to control the HTTP request and response. Put all the logic into the doPost() method.
Do NOT call a doPost() method from doGet() method on.
Do NOT let them both call some other common method like
processRequest() or something.(As you do in your code) This is plain wrong.
FiloptwxoServlet.java :
[...]
#WebServlet("/FiloptwxoServlet")
[...]
public class FiloptwxoServlet extends HttpServlet {
[...]
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
[...]
request.getRequestDispatcher("/WEB-INF/filoptwxoinfo.jsp").forward(request, response);
}
for more information look here stackoverflow :how-to-call-servlet-through-a-jsp-page and
servlets/info

Categories

Resources