How can I get my .JSP to print out my database data? - java

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.

Related

Retrieving record from database in Java by using select option tag

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

PROJECT NOT WORKING.adding deleting updating and searching in java web app

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

Servlet won't redirect to receipt page

So I am stuck at the point where the user clicks a submit button and the page should go to a receipt page and display there information.
Am I blind or should this work?
All of the other redirects work just fine using the method I am using but for some reason it wont go to the receipt page.
Servlet
package edu.witc.Assignment03.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//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;
import edu.witc.Assignment03.model.Customer;
import edu.witc.Assignment03.model.Phone;
import edu.witc.Assignment03.model.States;
#WebServlet(description = "servlet to get act as controller between form and models", urlPatterns = { "/customerServlet","/addCustomer","/addPet" })
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public CustomerServlet() {
super();
}
private void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
Phone phone = new Phone();
States state = new States();
Collection<Phone> phones = phone.getPhoneCollection();
Collection<States> states = state.getStateCollection();
session.setAttribute("phones", phones);
session.setAttribute("states", states);
//}
}
private List<edu.witc.Assignment03.model.Customer> customers = new ArrayList<Customer>();
private void addCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/customerManagement.jsp";
processRequest(request, response);
request.getRequestDispatcher(url).forward(request,response);
}
private void addPet(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/pets.jsp";
request.getRequestDispatcher(url).forward(request,response);
}
private Customer getCustomer(int customerId) {
for (Customer customer : customers) {
if (customer.getCustomerId() == customerId) {
return customer;
}
}
return null;
}
private void makeCustomerReceipt(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String url = "/receipt.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if("addCustomer".equals(action)) {
addCustomer(response, request);
}
else if("addPet".equals(action)) {
addPet(response, request);
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// update customer
int customerId = 0;
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setFirstName(request.getParameter("firstName"));
customer.setLastName(request.getParameter("lastName"));
customer.setEmail(request.getParameter("email"));
customer.setPhone(request.getParameter("phone"));
customer.setAddress(request.getParameter("address"));
customer.setCity(request.getParameter("city"));
customer.setZip(request.getParameter("zip"));
makeCustomerReceipt(request, response);
}
}
}
CustomerManagement.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.ArrayList" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Customer Management</title>
</head>
<body>
<form action="customerServlet" method="post">
First Name:<br>
<input type="text" name="firstName"/><br>
Last Name:<br>
<input type="text" name="lastName"/><br>
Email:<br>
<input type="text" name="email"/><br>
Phone Number:<br>
<input type="text" name="phone"/><br>
Phone Type:<br>
<select name="thePhones" id="selectPhones">
<option selected value="choose">
Select a Phone
</option>
<c:forEach items="${sessionScope.phones}" var="current" >
<option>${current.getPhoneName()}</option>
</c:forEach>
</select><br>
Street Address:<br>
<input type="text" name="streetAddress"/><br>
Apartment Number:<br>
<input type="text" name="apartmentNumber"/><br>
City:<br>
<input type="text" name="city"/><br>
State:<br>
<select name="states" id="states">
<option selected value="Wisconsin">
Select a State
</option>
<c:forEach items="${sessionScope.states}" var="current" >
<option>${current.getStates()}</option>
</c:forEach>
</select>
<input type="submit" value="submit">
</form>
</body>
</html>
To troubleshoot, add response.getWriter().write("..."); return; to the two possible problem places where you are doing nothing now:
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// update customer
int customerId = 0;
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
response.getWriter().write("Error: Customer ID could not be parsed to a number");
return; //to exit the function: we don't want to do anything more if we encounter this error
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setFirstName(request.getParameter("firstName"));
customer.setLastName(request.getParameter("lastName"));
customer.setEmail(request.getParameter("email"));
customer.setPhone(request.getParameter("phone"));
customer.setAddress(request.getParameter("address"));
customer.setCity(request.getParameter("city"));
customer.setZip(request.getParameter("zip"));
makeCustomerReceipt(request, response);
return; //to exit the function: you should always do this after forward or redirect
}
else
{
response.getWriter().write("Error: customer is null");
return; //to exit the function
}
}
}

unable to select complete list from table using servlet and jstl

Hey guys I am trying to retrieve complete list of users in the table from database but unfortunately unable to do it. Here is the code
1.> Deleteuser.java
package roseindia.net;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
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;
/**
* Servlet implementation class Deleteuser
*/
#WebServlet("/Deleteuser")
public class Deleteuser extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Deleteuser() {
super();
// TODO Auto-generated constructor stub
}
//String msg=" ";
String fname=" ";
String mname=" ";
String lname=" ";
String uname=" ";
String emailid=" ";
String mobno=" ";
String address=" ";
//String password1=" ";
//String password2=" ";
String usertype=" ";
String id=" ";
public void setFname(String fname) {
this.fname = fname;
}
public void setMname(String mname) {
this.mname = mname;
}
public void setLname(String lname) {
this.lname = lname;
}
public void setUname(String uname) {
this.uname = uname;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public void setMobno(String mobno) {
this.mobno = mobno;
}
public void setAddress(String address) {
this.address = address;
}
public void setUsertype(String usertype) {
this.usertype = usertype;
}
public void setId(String id) {
this.id = id;
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public static List<Deleteuser> list() throws Exception {
Connection conn=null;
String url="jdbc:mysql://localhost:3306/";
String dbName="userlogindb";
String driver="com.mysql.jdbc.Driver";
String dbUserName="root";
String dbPassword="root";
//List<String> dataList = new ArrayList<String>();
List<Deleteuser> users = new ArrayList<Deleteuser>();
try{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,dbUserName,dbPassword);
String strQuery="select * from registerutable";
System.out.println("The sql is " +strQuery);
Statement st= conn.createStatement();
ResultSet rs= st.executeQuery(strQuery);
while(rs.next())
{
Deleteuser user = new Deleteuser();
user.setFname(rs.getString("fname"));
user.setMname(rs.getString("mname"));
user.setLname(rs.getString("lname"));
user.setUname(rs.getString("uname"));
user.setEmailid(rs.getString("emailid"));
user.setMobno(rs.getString("mobno"));
user.setAddress(rs.getString("address"));
user.setUsertype(rs.getString("usertype"));
user.setId(rs.getString("id"));
users.add(user);
}
rs.close();
st.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return users;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("We are in the doPost method of Deleteuser");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
try{
List<Deleteuser> users = Deleteuser.list();
request.setAttribute("users",users);
}
catch(Exception e)
{
System.out.println(e);
}
//Disptching request
RequestDispatcher dispatcher = request.getRequestDispatcher("successful.jsp");
if (dispatcher != null){
dispatcher.forward(request, response);
}
//out.println("<font size='6' color=red>" + msg + "</font>");
}
}
2.> successful.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--<%#page language="java" import="java.util.*" %>-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Successful</title>
</head>
<body>
<form name="deleteform" action="Deleteuser" method="post">
<p><b><i>List of user details:</i></b></p>
<table border="1">
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>User Name</th>
<th>Email id</th>
<th>Mobile No</th>
<th>Address</th>
<th>Usertype</th>
<th>ID</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.fname}" /></td>
<td><c:out value="${user.mname}" /></td>
<td><c:out value="${user.lname}" /></td>
<td><c:out value="${user.uname}" /></td>
<td><c:out value="${user.emailid}" /></td>
<td><c:out value="${user.mobno}" /></td>
<td><c:out value="${user.address}" /></td>
<td><c:out value="${user.usertype}" /></td>
<td><c:out value="${user.id}" /></td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
Here, I m unable to display the list of user from the database table. I not getting any error also.
Serious apology I haven't use MVC because I first want do it using only single java program.
I have added all the necessary jar files.
Please let me know if I m missing anything or not following proper technique/standard.
To use EL syntax to get the value of object Pseudo Getter should be implemented.
So define getter for all element.
${user.fname} implicitly calls user.getFname()
You have not written any getter methods.
EL statement ${user.fname} is like calling user.getFname() and you don't have getter methods.
Define getter methods for all instance variables in Deleteuser.java.
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public String getMobno() {
return mobno;
}
public void setMobno(String mobno) {
this.mobno = mobno;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getUsertype() {
return usertype;
}
public void setUsertype(String usertype) {
this.usertype = usertype;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}

Netbeans and glassfish HTTP ERROR 404

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

Categories

Resources