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
Related
I'm trying to print out a table of a student's name, id, age, and course. I have created all this data in a WAMP server and the idea is that I am to grab the data from the database and print it out using a .JSP file.
Here is my code:
Student Class:
package Servlets;
import java.io.Serializable;
/**
*
* #author Harry
*/
public final class Students implements Serializable{
public String Name;
public String gender;
public int age;
public int idnumber;
public Students(String Name, String gender, int age, int idnumber) {
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getID(){
return idnumber;
}
public void setID(int idnumber){
this.idnumber = idnumber;
}
public String getGender(){
return gender;
}
public void setGender(String gender){
this.gender = gender;
}
}
getStudents.java class which should grab the data from the database and forward it to the .JSP
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Servlets;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
#WebServlet(name = "getStudents", urlPatterns =
{
"/getStudents"
})
public class getStudents 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
{
List<Students> students = new ArrayList<Students>();
try
{
String dbURL = "jdbc:mysql://localhost:3306/students";
String username = "root";
String password = "Nitram8151";
Connection connection = (Connection) DriverManager.getConnection(
dbURL, username, password);
Statement statement = (Statement) connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM students");
while (rs.next())
{
String Name = rs.getString("Name");
String gender = rs.getString("Gender");
int idnumber = rs.getInt("ID Number");
int age = rs.getInt("Age");
Students s = new Students(Name, gender, idnumber, age);
students.add(s);
}
connection.close();
} catch (SQLException e)
{
}
HttpSession session = request.getSession();
session.setAttribute("index", students);
RequestDispatcher dispatcher = request.getRequestDispatcher("listStudents.jsp");
dispatcher.forward(request, response);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
#Override
public String getServletInfo()
{
return "Short description";
}// </editor-fold>
}
listStudents.jsp which should grab the data forwarded from the getStudents.java class and print out the data in a table format:
<%--
Document : listStudents
Created on : 07-Mar-2017, 12:23:12
Author : Martin Laptop
--%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Students</title>
</head>
<body>
<h1>Student Information</h1>
<table style="border: 4px solid #dddddd;padding: 8px;width: 25%;">
<thead>
<tr>
<td style="border: 2px solid #dddddd;padding: 4px;"><b><u>Student Name </u></b></td>
<td style="border: 2px solid #dddddd;padding: 4px;"><b><u> Student Gender</u></b></td>
<td style="border:2px solid #dddddd;padding: 4px; "><b><u>Student ID Number</u></b></td>
<td style="border:2px solid #dddddd;padding: 4px; "><b><u>Student Age</u></b></td>
</tr>
</thead>
<c:forEach var="student" items="${students}">
<tr>
<td>${students.Name}</td>
<td>${students.gender}</td>
<td>${students.idnumber}</td>
<td>${students.age}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Can anyone help me as to why the data is not printing out on the jsp? I'm at my wits end with this
Several reasons.
First, you're doing
catch (SQLException e)
{
}
That means that if the code inside the try block throws an exception, you can't know anything about it. Don't, ever do that.
Replace it by
catch (SQLException e) {
throw new RuntimeException(e);
}
Second, you're storing the students, in the session (althought there is no reason to store them in the session: they should be stored in the request), using
session.setAttribute("index", students);
But your JSP uses
<c:forEach var="student" items="${students}">
So you store them in an attribute named "index", and retrieve them in an attribute names "students".
Finally,
${students.Name}
should be
${student.name}
You want to get the name property of the current student in the loop, not the name of the list.
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
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.
I am doing my final year college project. I am not good at coding. I am interested in Java and hence chose it. My project is a Placement Management System. It is a just a simple system for adding, viewing, deleting and updating data. I got the source code from Internet. But, when I run it, the first page appears. clicking any button will move it to HTTP Status 500.
I am providing the code below so that you can easily help me to fix this issue.
Server Error Screenshot.
Just to know the structure of the project
index.jsp
<%--
Document : index
Created on : 30-Jan-2016, 12:38:44
Author : krish_000
--%>
<%#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>Hello World!</h1>
edit page
</body>
</html>
studentinfo.jsp
<%--
Document : index
Created on : 20-Jan-2013, 22:16:54
Author : Joseph
--%>
<%#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>Student Information</title>
</head>
<body>
<h1>Student Information</h1>
<form action="./StudentServlet" method="POST">
<table>
<tr>
<td>Student ID</td>
<td><input type="text" name="studentId" value="${student.studentId}" /></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name="firstname" value="${student.firstname}" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastname" value="${student.lastname}" /></td>
</tr>
<tr>
<td>Year Level</td>
<td><input type="text" name="yearLevel" value="${student.yearLevel}" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="action" value="Add" />
<input type="submit" name="action" value="Edit" />
<input type="submit" name="action" value="Delete" />
<input type="submit" name="action" value="Search" />
</td>
</tr>
</table>
</form>
<br>
<table border="1">
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Year Level</th>
<c:forEach items="${allStudents}" var="stud">
<tr>
<td>${stud.studentId}</td>
<td>${stud.firstname}</td>
<td>${stud.lastname}</td>
<td>${stud.yearLevel}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
source package
com.joseph.controller
studentServlet.jav
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.joseph.controller;
import com.joseph.dao.StudentDaoLocal;
import com.joseph.model.Student;
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;
/**
*
* #author Joseph
*/
#WebServlet(name = "StudentServlet", urlPatterns = {"/StudentServlet"})
public class StudentServlet extends HttpServlet {
#EJB
private StudentDaoLocal studentDao;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
String studentIdStr = request.getParameter("studentId");
int studentId=0;
if(studentIdStr!=null && !studentIdStr.equals("")){
studentId=Integer.parseInt(studentIdStr);
}
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String yearLevelStr = request.getParameter("yearLevel");
int yearLevel=0;
if(yearLevelStr!=null && !yearLevelStr.equals("")){
yearLevel=Integer.parseInt(yearLevelStr);
}
Student student = new Student(studentId, firstname, lastname, yearLevel);
if("Add".equalsIgnoreCase(action)){
studentDao.addStudent(student);
}else if("Edit".equalsIgnoreCase(action)){
studentDao.editStudent(student);
}else if("Delete".equalsIgnoreCase(action)){
studentDao.deleteStudent(studentId);
}else if("Search".equalsIgnoreCase(action)){
student = studentDao.getStudent(studentId);
}
request.setAttribute("student", student);
request.setAttribute("allStudents", studentDao.getAllStudents());
request.getRequestDispatcher("studentinfo.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);
}
/**
* <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>
}
com.joseph.dao
studentDAO.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.joseph.dao;
import com.joseph.model.Student;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author Joseph
*/
#Stateless
public class StudentDao implements StudentDaoLocal {
#PersistenceContext
private EntityManager em;
#Override
public void addStudent(Student student) {
em.persist(student);
}
#Override
public void editStudent(Student student) {
em.merge(student);
}
#Override
public void deleteStudent(int studentId) {
em.remove(getStudent(studentId));
}
#Override
public Student getStudent(int studentId) {
return em.find(Student.class, studentId);
}
#Override
public List<Student> getAllStudents() {
return em.createNamedQuery("Student.getAll").getResultList();
}
}
studentDAOLocal.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.joseph.dao;
import com.joseph.model.Student;
import java.util.List;
import javax.ejb.Local;
/**
*
* #author Joseph
*/
#Local
public interface StudentDaoLocal {
void addStudent(Student student);
void editStudent(Student student);
void deleteStudent(int studentId);
Student getStudent(int studentId);
List<Student> getAllStudents();
}
com.joseph.model
student.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.joseph.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
* #author Joseph
*/
#Entity
#Table
#NamedQueries({#NamedQuery(name="Student.getAll",query="SELECT e FROM Student e")})
public class Student implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column
private int studentId;
#Column
private String firstname;
#Column
private String lastname;
#Column
private int yearLevel;
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int getYearLevel() {
return yearLevel;
}
public void setYearLevel(int yearLevel) {
this.yearLevel = yearLevel;
}
public Student(int studentId, String firstname, String lastname, int yearLevel) {
this.studentId = studentId;
this.firstname = firstname;
this.lastname = lastname;
this.yearLevel = yearLevel;
}
public Student(){}
}
Enterprise Bean/
studentDao
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.joseph.dao;
import com.joseph.model.Student;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author Joseph
*/
#Stateless
public class StudentDao implements StudentDaoLocal {
#PersistenceContext
private EntityManager em;
#Override
public void addStudent(Student student) {
em.persist(student);
}
#Override
public void editStudent(Student student) {
em.merge(student);
}
#Override
public void deleteStudent(int studentId) {
em.remove(getStudent(studentId));
}
#Override
public Student getStudent(int studentId) {
return em.find(Student.class, studentId);
}
#Override
public List<Student> getAllStudents() {
return em.createNamedQuery("Student.getAll").getResultList();
}
}
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!