I am trying to add data to a sql database by entering info in text boxes and clicking a submit button. However, I cant get the submit button to work right. I am not real familiar with html so I may be doing something wrong. Here is some code. This is my jsp page with the submit button.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Student Page</title>
</head>
<body>
<table border="1" align="center">
<tr><td>Student ID</td><td>First Name</td><td>Last Name</td><td>Degree Program</td><td>Gender</td></tr>
<%
List<Student> students = (List) request.getAttribute("student");
for (Student student : students) { %>
<tr><td><%=student.getStudentId()%></td><td><%=student.getFirstname()%></td><td><%=student.getLastname()%></td><td><%=student.getDegreeprogram()%></td><td><%=student.getGender()%></td></tr>
<% }
%>
<tr><td> </td><td> </td><td>Go To Home Page</td><td> </td><td> </td></tr>
</table>
<form name="student" action="process" method="post">
<input type="hidden" name="view" value="addStudent" />
<table>
<tr><td> </td><td><Strong>Add a Student</Strong></td></tr>
<tr><td>Student ID: </td><td><input type="text" name="studentid" id="studentid"/></td></tr>
<tr><td>First Name: </td><td><input type="text" name="firstname" id="firstname"/></td></tr>
<tr><td>Last Name: </td><td><input type="text" name="lastname" id="lastname"/></td></tr>
<tr><td>Degree Program: </td><td><input type="text" name="degreeprogram" id="degreeprogram"/></td></tr>
<tr><td>Gender: </td><td><input type="text" name="gender" id="gender"/></td></tr>
<tr><td> </td><td><input type="submit"/></td></tr>
</table>
</form>
<form name="exit" action="process" method="post">
<input type="hidden" name="view" value="home" />
<p align="center"><input type="button" value="Exit"/></p>
</form>
</body>
</html>
This is my servlet where the query is made and where the data should be saved to the database.
#WebServlet(name="regservlet", urlPatterns={"/registrar"})
public class regservlet 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 {
String view = request.getParameter("view");
if (view != null) {
String jspName="/index.jsp";
HibernateUtil util = new HibernateUtil();
Session hibernateSession = (Session) util.getHibernateSession();
String tableName = "";
if (view.equalsIgnoreCase("Student")) {
tableName="Student";
Query q = hibernateSession.createQuery("from " + tableName);
List<Student> students = q.list();
jspName="/student.jsp";
request.setAttribute("student", students);
} else if (view.equalsIgnoreCase("Course")) {
tableName="Course";
Query q = hibernateSession.createQuery("from " + tableName);
List<Course> courses = q.list();
request.setAttribute("course", courses);
jspName="/course.jsp";
}
else if (view.equalsIgnoreCase("Enrollment")) {
tableName="Enrollment";
Query q = (Query) hibernateSession.createQuery("from " + tableName);
List<Enrollment> enrollment = q.list();
request.setAttribute("enrollment", enrollment);
jspName="/enrollment.jsp";
}
else if (view.equalsIgnoreCase("addStudent")) {
String studentid = request.getParameter("studentid");
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String degreeprogram = request.getParameter("degreeprogram");
String gender = request.getParameter("gender");
Student myStudent = new Student(studentid, firstname, lastname, degreeprogram, gender);
hibernateSession.saveOrUpdate(myStudent);
Transaction t = hibernateSession.beginTransaction();
t.commit();
jspName="/index.jsp";
}
else if (view.equalsIgnoreCase("addCourse")) {
String courseid = request.getParameter("courseid");
String coursename = request.getParameter("course");
String coursesection = request.getParameter("coursesection");
String instructorId= request.getParameter("instructorid");
Course myCourse = new Course (courseid, coursename, coursesection, instructorId);
hibernateSession.saveOrUpdate(myCourse);
Transaction t = hibernateSession.beginTransaction();
t.commit();
jspName="/index.jsp";
}
else if (view.equalsIgnoreCase("addEnrollment")) {
String enrollmentid = request.getParameter("enrollmentid");
String course = request.getParameter("course");
String student = request.getParameter("student");
String semester= request.getParameter("semester");
Enrollment myEnrollment = new Enrollment(enrollmentid, course, student, semester);
hibernateSession.saveOrUpdate(myEnrollment);
Transaction t = hibernateSession.beginTransaction();
t.commit();
jspName="/index.jsp";
}
else if (view.equalsIgnoreCase("home")) {
jspName="/index.jsp";
}
hibernateSession.close();
System.out.println("JSP NAME "+jspName);
this.getServletContext().getRequestDispatcher(jspName).forward(request, response);
}
}catch (Exception ex) {
ex.printStackTrace();
System.err.println("Initial SessionFactory creation failed." + 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>
}
Any suggestions?
Your form has its action set to "process". Your servlet is configured to be invoked as "registrar", so it never gets invoked.
Action in HTML form is "process". The servlet is mapped to URL "registrar"
These two should match. Otherwise application server does not know where to send your HTTP request.
Search for simple Servlet tutorial first. It will take you 15 minutes to read it and become the world level specialist in servlets. Good luck!
Related
Edit:
I pointed the post request to /vault/Login but the servlet was on /vault/index and vault/login
when pointing it towards index it worked.
I'm trying to make a login system.
I have an html file which a post method is requested from but the doPost method is never fired when requested.
When the submit button is clicked the url changes with the parameters in it but nothing happens.
Every time the doPost() is executed the first statement writes something to the console but neither does that happen.
public class Login extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
System.out.println("fired");
HttpSession session = request.getSession();
session.setAttribute("loginFailed", false);
RequestDispatcher rd = request.getRequestDispatcher("Login.jsp");
rd.forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("this is another test");
HttpSession session = request.getSession();
String username = (String)session.getAttribute("username");
String password = (String)session.getAttribute("password");
System.out.println(username + " " + password);
boolean succes = false;
if (!"".equals(username) && !"".equals(password)){
try {
succes = Authentication.checkCredentials(username, password);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
switch ((String)session.getAttribute("platform")){
case "browser":
RequestDispatcher rd = request.getRequestDispatcher("Lobby.jsp");
rd.forward(request, response);
break;
case "desktop":
int id = Tracker.getIdByUsername(username);
List vaults = (List)VaultManagement.getVaultsByUserId(id);
int[] vaultIds = new int[vaults.size()];
if (vaults.isEmpty()){
vaultIds[0] = -1;
}else{
int x = 0;
for (Object vault : vaults){
Vault v = (Vault)vault;
vaultIds[x] = v.getId();
x++;
}
}
DAL.Entities.Account account = AccountManagement.getAccountByUsername(username);
LoginPackage pack = new LoginPackage(username, password, account.getEmail(), vaultIds);
String json = JSON.dataPackageToJson(pack);
PrintWriter writer = response.getWriter();
writer.print(json);
break;
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Post
<div class="jumbotron" width="10%">
<form id="form" action="/vault/Login.jsp">
<h6>Username:</h6>
<input type="text" class="form-control" id="username" name="username">
<h6>Password:</h6>
<input type="password" class="form-control" id="password" name="password"><br>
<button type="button" onclick="location.href='vault/Register.jsp'" class="btn btn-secondary">Register</button>
<input type="hidden" name="platform" value="browser"/>
<input type="submit" value="Login"/>
</form>
</div>
You forgot to specify the method attribute to be post:
<form id="form" action="/vault/Login.jsp" method="post">
<!-- Here ---------------------------------^ -->
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.
I want to retrieve record from database by clicking on the option selected from drop down list and it as a table on the web page. But after implementing following code the web page is blank now what should I do? Any type of help will be appreciable. Here is my index.jsp page:
<%#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>
<form name="f1" action="portal" method="POST">
<h3>Name of the Book : </h3>
<select name="book" id="book">
<option value="">Select</option>
<option value="1">The Pilgrims Progress</option>
<option value="2">Robinson Crusoe</option>
<option value="3">Gullivers Travels</option>
<option value="4">Clarissa</option>
<option value="5">Tom Jones</option>
<option value="6">The Life and Opinions of Tristram Shandy, Gentleman</option>
<option value="7">Emma</option>
<option value="8">Frankenstein</option>
<option value="9">Nightmare Abbey</option>
<option value="10">The Narrative of Arthur Gordon Pym of Nantucket</option>
<option value="11">Sybil</option>
<option value="12">Jane Eyre</option>
<option value="13">Wuthering Heights</option>
<option value="14">Vanity Fair</option>
<option value="15">David Copperfield</option>
<option value="16">The Scarlet Letter</option>
<option value="17">Moby-Dick</option>
<option value="18">Alices Adventures in Wonderland</option>
<option value="19">The Moonstone</option>
<option value="20">Little Women</option>
<option value="21">Middlemarch</option>
</select>
<input type="submit" value="submit" />
</form>
</body>
</html>
And here is my servlet page for retrieving data from database
package com;
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.ResultSetMetaData;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class portal 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 {
String book = request.getParameter("book");
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "password");
PreparedStatement pt = conn.prepareStatement("Select * from book where Book_Name = ?");
pt.setString(1, book);
out.print("<table width = 75%>");
out.print("<center><h1>Welcome To The Portal</h1></center>");
ResultSet rs = pt.executeQuery();
ResultSetMetaData rsd = rs.getMetaData();
while (rs.next()) {
out.print("<tr>");
out.print("<td>" + rsmd.getColumnName(1) + "</td>");
out.print("<td>" + rs.getString(1) + "</td></tr>");
out.print("<tr><td>" + rsmd.getColumnName(2) + "</td>");
out.print("<td>" + rs.getString(2) + "</td></tr>");
out.print("<tr><td>" + rsmd.getColumnName(3) + "</td>");
out.print("<td>" + rs.getString(3) + "</td></tr>");
out.print("<tr><td>" + rsmd.getColumnName(4) + "</td>");
out.print("<td>" + rs.getString(4) + "</td></tr>");
RequestDispatcher rd = request.getRequestDispatcher("logout.jsp");
rd.include(request, response);
}
out.println("</table>");
}
catch (Exception e) {
out.println(e);
}
}
// <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>
}
now I don't know where I miss something.
I suggest that you use your servlet as a controller that control the data in your application and not as a vue where you write html tags
this example may help you :
Firstly, create a serialisable java class where you put communicate with database :
public class BookData implements Serializable {
private String ISBN;
private String titre;
private String auteur;
private int ID;
private String editeur;
// ADD GETTER AN SETTER METHODS
public BookData(String titre, String auteur, int ID, String editeur, String ISBN) {
this.titre = titre;
this.auteur = auteur;
this.ID = ID;
this.editeur = editeur;
this.ISBN = ISBN;
}
public List<BookData> loadData(String book) {
List<BookData> actorList = new ArrayList<BookData>();
com.mysql.jdbc.PreparedStatement ps = null;
ResultSet rs = null;
String url = "jdbc:mysql://127.0.0.1:3306/DATABASENAME";// CHANGE
String name = "NAME";// CHANGE
String pw = "PWD";// CHANGE
String driver = "com.mysql.jdbc.Driver";
Connection connexion = null;
try {
Class.forName(driver).newInstance();
connexion = DriverManager.getConnection(url, name, pw);
String q = "Select * from book where Book_Name ='" + book + "'";
Statement commande = connexion.createStatement();
rs = commande.executeQuery(q);
while (rs.next()) {
BookData bk = new BookData(rs.getString("Book_Title"), rs.getString("Book_Author"), rs.getInt("ID"),
rs.getString("Publisher"), rs.getString("ISBN"));/* CHANGE COLUMN NAMES */
actorList.add(bk);
}
return actorList;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
rs.close();
connexion.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Secondly the servlet :
public class EXAMPLE_SERVLET extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String option = request.getParameter("book");
BookData dao = new BookData();
List<BookData> list = dao.loadData(option);
request.setAttribute("booklist", list);
RequestDispatcher view = request.getRequestDispatcher("test.jsp");
view.forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
then the JSP ((test.jsp))
<table>
<thead>
<tr>
<th>titre</th> //...COLUMNS
</tr>
</thead>
<tbody>
<c:forEach var="employee" items="${booklist}">
<tr>
<td style="width: 110px; color: #3278b3;">${employee.titre}</td>
//...ROWS
</tr>
</c:forEach>
</tbody>
</table>
i solved my question thanks to everyone who helped me but not i get it where i was doind a mistake it was in option tag value attribute i took the value as 1 , 2 and 3 .. so on but it should be same as the text and in servlet page i've changed the while loop to if & else so it is working fine.. thanku soo much for all your help
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());
}
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