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();
}
}
Related
--> when i am Updating it was not saving the entered details insted it was saving null. when deleting it throws error.
DataBase : restonetoone
application.properties
/*****************************/
crm.rest.url=http://localhost:8080/restonetoone/api/details
-->when i use to update it was taking null value insted of inserted data.
Details [id=25, city=null, mobileno=0, student=Student [id=25, name=null, clas=0]]
->when i was deleting it throws this error.
Mar 06, 2021 4:09:53 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping for GET /restclient/student/delete
the Details.java class Onetoone with student.java class
Details.java
/******************/
package com.rest.entity;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="details")
public class Details {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String city;
private long mobileno;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="student_id")
private Student student;
public Details(){
}
public Details(int id, String city, long mobileno, Student student) {
super();
this.id = id;
this.city = city;
this.mobileno = mobileno;
this.student = student;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public long getMobileno() {
return mobileno;
}
public void setMobileno(long mobileno) {
this.mobileno = mobileno;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
#Override
public String toString() {
return "Details [id=" + id + ", city=" + city + ", mobileno=" + mobileno + ", student=" + student + "]";
}
}
student.java class
Student.java
/******************/
package com.rest.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student")
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private int clas;
public Student() {
}
public Student(int id, String name, int clas) {
super();
this.id = id;
this.name = name;
this.clas = clas;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getClas() {
return clas;
}
public void setClas(int clas) {
this.clas = clas;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", clas=" + clas + "]";
}
}
DetailsServImpl.java class(service layers)
DetailsServImpl.java
/******************/
package com.rest.service;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.rest.entity.Details;
#Service
public class DetailsServImpl implements DetailsServ {
private RestTemplate restTemplate;
private String crmRestUrl;
private Logger logger = Logger.getLogger(getClass().getName());
#Autowired
public DetailsServImpl(RestTemplate theRestTemplate,
#Value("${crm.rest.url}") String theUrl) {
restTemplate = theRestTemplate;
crmRestUrl = theUrl;
logger.info("Loaded property: crm.rest.url=" + crmRestUrl);
}
#Override
public List<Details> getDetails() {
logger.info("in getDetails(): Calling REST API " + crmRestUrl);
// make REST call
ResponseEntity<List<Details>> responseEntity =
restTemplate.exchange(crmRestUrl, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Details>>() {});
// get the list of customers from response
List<Details> theDetails = responseEntity.getBody();
logger.info("in getDetails(): details" + theDetails);
return theDetails;
}
#Override
public Details getDetails(int theId) {
logger.info("in getDetails(): Calling REST API " + crmRestUrl);
// make REST call
Details theDetails =
restTemplate.getForObject(crmRestUrl + "/" + theId,
Details.class);
logger.info("in saveDetails(): theDetails=" + theDetails);
return theDetails;
}
#Override
public void saveDetails(Details theDetails) {
logger.info("in saveSt(): Cudentalling REST API " + crmRestUrl);
int detailsId = theDetails.getId();
// make REST call
if (detailsId == 0) {
// add employee
restTemplate.postForEntity(crmRestUrl, theDetails, String.class);
} else {
// update employee
restTemplate.put(crmRestUrl, theDetails);
}
logger.info("in saveDetails(): success");
}
#Override
public void deleteDetails(int theId) {
logger.info("in deleteDetails(): Calling REST API " + crmRestUrl);
// make REST call
restTemplate.delete(crmRestUrl + "/" + theId);
logger.info("in deleteDetails(): deleted Details theId=" + theId);
}
}
StudentServImpl.java class
StudentServImpl.java
/******************/
package com.rest.service;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.rest.entity.Details;
import com.rest.entity.Student;
#Service
public class StudentServImpl implements StudentServ {
private RestTemplate restTemplate;
private String crmRestUrl;
private Logger logger = Logger.getLogger(getClass().getName());
#Autowired
public StudentServImpl(RestTemplate theRestTemplate,#Value("${crm.rest.url}") String theUrl){
restTemplate = theRestTemplate;
crmRestUrl = theUrl;
logger.info("Loaded property: crm.rest.url=" + crmRestUrl);
}
#Override
public List<Student> getStudent() {
logger.info("in getCustomers(): Calling REST API " + crmRestUrl);
// make REST call
ResponseEntity<List<Student>> responseEntity =
restTemplate.exchange(crmRestUrl, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Student>>() {});
// get the list of customers from response
List<Student> theStudent = responseEntity.getBody();
logger.info("in getCustomers(): customers" + theStudent);
return theStudent;
}
#Override
public void saveStudent(Student theStudent) {
logger.info("in saveSt(): Cudentalling REST API " + crmRestUrl);
int studentId = theStudent.getId();
// make REST call
if (studentId == 0) {
// add employee
restTemplate.postForEntity(crmRestUrl, theStudent, String.class);
} else {
// update employee
restTemplate.put(crmRestUrl, theStudent);
}
logger.info("in saveStudent(): success");
}
#Override
public Student getStudent(int theId) {
logger.info("in getCustomer(): Calling REST API " + crmRestUrl);
// make REST call
Student theStudent =
restTemplate.getForObject(crmRestUrl + "/" + theId,
Student.class);
logger.info("in saveCustomer(): theCustomer=" + theStudent);
return theStudent;
}
#Override
public void deleteStudent(int theId) {
logger.info("in deleteStudent(): Calling REST API " + crmRestUrl);
// make REST call
restTemplate.delete(crmRestUrl + "/" + theId);
logger.info("in deleteStudent(): deleted Student theId=" + theId);
}
}
Now the controller class(here i am using single controller for multiple entites).
ClientController.java
/******************/
package com.rest.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.rest.entity.Details;
import com.rest.entity.Student;
import com.rest.service.DetailsServ;
import com.rest.service.StudentServ;
#Controller
#RequestMapping("/cont")
public class ClientController {
#Autowired
private DetailsServ detailsServ;
#Autowired
private StudentServ studentServ;
#GetMapping("/showForm")
public String showForm(Model theModel){
Details theDetails = new Details();
Student theStudent = new Student();
theDetails.setStudent(theStudent);
theModel.addAttribute("for",theDetails);
return "the-for";
}
#PostMapping("/saveForm")
private String saveForm(#ModelAttribute("for") Details theDetails) {
detailsServ.saveDetails(theDetails);
return "redirect:/cont/list";
}
#GetMapping("/list")
public String showList(Model theModel) {
List<Details> theDetails = detailsServ.getDetails();
theModel.addAttribute("details", theDetails);
return "list-table";
}
#GetMapping("/update")
public String updateDetails(#RequestParam("detailsId") int theId, Model theModel) {
Details theDetails =detailsServ.getDetails(theId);
theModel.addAttribute("for",theDetails);
return "the-for";
}
#GetMapping("/delete")
public String deleteDetails(#RequestParam("detailsId") int theId) {
detailsServ.deleteDetails(theId);
return "redirect:/cont/list";
}
}
I use this form for both saving and updating.
the-for.jsp
/******************/
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<title>Save Customer</title>
<link type="text/css"
rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/style.css">
<link type="text/css"
rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/add-customer-style.css">
</head>
<body>
<div id="wrapper">
<div id="header">
<h2>Form</h2>
</div>
</div>
<div id="container">
<h3>Save StudentDetails</h3>
<form:form action="saveForm" modelAttribute="for" method="POST">
<!-- need to associate this data with customer id -->
<form:hidden path="id" />
<table>
<tbody>
<tr>
<td><label>City name:</label></td>
<td><form:input path="city" /></td>
</tr>
<tr>
<td><label>mobileno:</label></td>
<td><form:input path="mobileno" /></td>
</tr>
<tr>
<td><label>name:</label></td>
<td><form:input path="student.name" /></td>
</tr>
<tr>
<td><label>class:</label></td>
<td><form:input path="student.clas" /></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit" value="Save" class="save" /></td>
</tr>
</tbody>
</table>
</form:form>
<div style="clear; both;"></div>
<p>
Back to List
</p>
</div>
</body>
</html>
Now the table which shows the CRUD dynamically.
list-table.jsp
/******************/
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page import = "java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>List</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2 class="pt-2">Student Manager</h2>
<!-- put new button: Add Student -->
<input type="button" value="Add Student"
onclick="window.location.href='showForm'; return false;"
class="btn btn-primary btn-sm mb-3" />
<!-- add our html table here -->
<table class="table table-bordered table-striped">
<thead class="table-dark">
<tr>
<th>city</th>
<th>mobileno</th>
<th>name</th>
<th>class</th>
<th>Action</th>
</tr>
</thead>
<!-- loop over and print our students -->
<tbody>
<c:forEach var="tempDetails" items="${details}">
<!-- construct an "update" link with student id -->
<c:url var="updateLink" value="/cont/update">
<c:param name="detailsId" value="${tempDetails.id}" />
</c:url>
<!-- construct an "delete" link with student id -->
<c:url var="deleteLink" value="/student/delete">
<c:param name="studentId" value="${tempStudent.id}" />
</c:url>
<tr>
<td>${tempDetails.city}</td>
<td>${tempDetails.mobileno}</td>
<td>${tempDetails.student.name}</td>
<td>${tempDetails.student.clas}</td>
<td>
<!-- display the update link -->
Update
|
<a href="${deleteLink}"
onclick="if (!(confirm('Are you sure you want to delete this student?'))) return false">Delete</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>
For more clearity sake i am shering the link of my project which include Both client side and backend code files with database.
LINK( https://drive.google.com/file/d/128pvCd6bYdCNhOiG6ERRXbPRUlnhZlTp/view?usp=sharing )
I am working on a hibernate project using apache.tomcat in netbeans in which I am creating an application with a user login (employee ID and password) that allows baseball field employees (from mysql database) to request passes to use the field. Users should be able to 1) choose an event for reservation (date & time) from a drop down menu, 2) input their group size, group name, and employee department(drop-down) and 3) manage the reservations on file specific to their employee ID.
I can access the login screen, but nothing happens when I enter employee credentials. I am not sent to the memberscreen.jsp upon entering a correct login, and I do not get the errors I set up for invalid logins. I have been at this for hours and I can not seem to find where I went wrong.
Note: The project requires that I use hibernate
I have tried googling ways to fix this but I have come up short, I think my problem may be too specific. I am getting no errors and the build is successful, but not functional.
logonservlet.java
package servlets;
import business.Employee;
import business.EmployeeDB;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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 LogonServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String msg = "", empid = "";
long pattempt;
String URL = "/Logon.jsp";
Employee e;
try {
empid = request.getParameter("empid").trim();
e = EmployeeDB.getEmployee(empid);
if (e == null) {
msg = "No member record found<br>";
} else {
pattempt = Long.parseLong(request.getParameter("password"));
e.setPassattempt((int) pattempt);
if (!e.isAuthenticated()) {
msg = "Member found but not authenticated<br>";
} else {
msg = "member authenticated<br>";
URL = "/MemberScreen.jsp";
}
request.getSession().setAttribute("e", e);
}
} catch (Exception x) {
msg = "Servlet exception: " + x.getMessage();
}
request.setAttribute("msg", msg);
RequestDispatcher disp =
getServletContext().getRequestDispatcher(URL);
disp.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>
}
Logon.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Field Pass</title>
</head>
<body>
<h1>Welcome</h1>
<p>Please Enter your id and password:</p>
<form action="Logon" method="post">
<table>
<tr>
<td>User ID:</td>
<td><input type="text" name="userid" id="userid"
value="${empty user.userID ? cookie.memid.value : user.userID }" />
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="password">
</td>
</tr>
</table>
<br>
<input type="submit" value="Log in">
</form>
<br>
</body>
</html>
employee.java
package business;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.Transient;
import org.hibernate.annotations.NamedQuery;
#Entity
#Table(name="Employee")
#NamedQuery(name="dbget_Employee", query="from EMPLOYEE where EMP_ID = :EMP_ID")
public class Employee {
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
#Id
#Column(name="EMP_ID")
private int emp_id;
#Column(name="LAST_NAME")
private String last_name;
#Column(name="FIRST_NAME")
private String first_name;
#Column(name="MIDDLE_INITIAL")
private String middle_initial;
#Column(name="HIRE_DATE")
#Temporal(javax.persistence.TemporalType.DATE)
private Date hire_date;
#Column(name="DEPT_ID")
private int dept_id;
#Column(name="PASSWORD")
private int password;
#Column(name="ADMIN")
private String admin;
#Transient
private int passattempt;
#Transient
private String msg;
public Employee() {
emp_id = 0;
last_name= "";
first_name = "";
middle_initial = "";
hire_date = null;
dept_id = 0;
password = 0;
admin = "";
}
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getMiddle_initial() {
return middle_initial;
}
public void setMiddle_initial(String middle_initial) {
this.middle_initial = middle_initial;
}
public Date getHire_date() {
return hire_date;
}
public void setHire_date(Date hire_date) {
this.hire_date = hire_date;
}
public int getDept_id() {
return dept_id;
}
public void setDept_id(int dept_id) {
this.dept_id = dept_id;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public String getAdmin() {
return admin;
}
public void setAdmin(String admin) {
this.admin = admin;
}
public int getPassattempt() {
return passattempt;
}
public void setPassattempt(int passattempt) {
this.passattempt = passattempt;
}
public boolean isAuthenticated() {
if (this.password > 0) {
if (this.password == this.getPassattempt()) {
return true;
} else {
setMsg("Member not authenticated");
}
}
return false;
}
}
employeeDB.java
package business;
import javax.persistence.NoResultException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
/**
*
* #author noah
*/
public class EmployeeDB {
public static Employee getEmployee(int emp_id) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = null;
Employee e = null;
try {
String qS ="from Employee e where e.emp_id = :emp_id";
session = sessionFactory.openSession();
Query q = session.createQuery(qS);
q.setParameter("emp_id", emp_id);
e = (Employee)q.uniqueResult();
} catch (NoResultException ex) {
return null;
} finally {
session.close();
}
return e;
}
public static Employee getEmployee(String empid) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of
generated methods, choose Tools | Templates.
}
}
memberScreen.jsp
<%#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>Member Welcome</title>
<style>
table.member-details{
border-collapse: collapse;
}
table.member-details td, table.member-details th{
padding: 6px;
border: 1px solid #999;
}
</style>
</head>
<c:if test="${!e.authenticated}">
<script type="text/javascript">
window.location = "/ClubDB";
</script>
</c:if>
<c:if test="${e.authenticated}">
<body>
<h1>Club member Data</h1>
<form id="memupdate" action="MemberUpdate" method="post">
<table class="member-details">
<tr>uu
<td>Member ID:</td>
<td><input type="text" id="memid" name="memid"
value="${e.empid}" readonly="true"></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" id="lastname" name="lastname"
value="${e.lastname}" ></td>
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" id="firstname" name="firstname"
value="${e.firstname}" ></td>
</tr>
<tr>
<td>Middle Nm:</td>
<td><input type="text" id="middlename" name="middlename"
value="${e.middlename}" ></td>
</tr>
<tr>
<td>Status:</td>
<td><input type="text" id="status" name="status"
value="${m.status}" readonly="true" ></td>
<tr>
<tr>
<td>Member Date:</td>
<td><input type="text" id="memdt" name="memdt"
value="${m.memdtS}" readonly="true" ></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="psswd" name="psswd"
value="${m.password}" size="22"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Update Member data"></td>
</tr>
</table>
</form>
<br>
${msg}
<hr>
<br>View Transaction History From:<br>
<form action="ShowPurchases" method="post" >
<table>
<tr>
<td>Month:</td><td><input type="text" name="month"
id="month" value=""></td>
<td>Day:</td><td><input type="text" name="day"
id="day" value=""></td>
<td>Year:</td><td><input type="text" name="year"
id="year" value=""></td>
</tr>
</table><br>
<input type="submit" value="View Transactions">
</form> <br>
<br><br>
Back to the Login Screen
</body>
</c:if>
</html>
hibernate xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-
iiapp_3_1.xsd">
<servlet>
<servlet-name>LogonServlet</servlet-name>
<servlet-class>servlets.LogonServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogonServlet</servlet-name>
<url-pattern>/Logon</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>Logon.jsp</welcome-file>
</welcome-file-list>
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.
so I am working in a Spring MVC project where I have this class with a few Date fields and I am creating a CRUD for it. Problem is, I read an instance of the class from the database and then send it to the view for editing, and although I am not manipulating any of the Date fields, only the strings, when I collect the object using a post form, the Date fields come as null even though they came from the database with a value and I sent them to the view with that value.
The class:
package com.sophos.mat.beans;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.hibernate.validator.constraints.Length;
#Entity
#Table(name="T_PROYECTOS")
public class Proyecto implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name="IN_PROYECTO")
#GeneratedValue(strategy=GenerationType.AUTO, generator="SECUENCIA_IN_PROYECTO")
#SequenceGenerator(name="SECUENCIA_IN_PROYECTO", sequenceName="SECUENCIA_IN_PROYECTO", allocationSize=1, initialValue= 1)
private long id;
#Column(name="VC_NOMBRE")
#Length(max = 50, message = "El campo no puede exceder los 50 caracteres")
private String nombre;
#Column(name="VC_DESCRIPCION")
#Length(max = 200, message = "El campo no puede exceder los 200 caracteres")
private String descripcion;
#Column(name="VC_CODIGO_SOPHOS")
#Length(max = 20, message = "El campo no puede exceder los 20 caracteres")
private String codigoSophos;
#Column(name="DT_FECHACREACION")
private Date fechaCreacion;
#Column(name="VC_USUARIOACTUALIZACION")
private String usuarioActualizacion;
#Column(name="DT_FECHAACTUALIZACION")
private Date fechaActualizacion;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getCodigoSophos() {
return codigoSophos;
}
public void setCodigoSophos(String codigoSophos) {
this.codigoSophos = codigoSophos;
}
public Date getFechaCreacion() {
return fechaCreacion;
}
public void setFechaCreacion(Date fechaCreacion) {
this.fechaCreacion = fechaCreacion;
}
public String getUsuarioActualizacion() {
return usuarioActualizacion;
}
public void setUsuarioActualizacion(String usuarioActualizacion) {
this.usuarioActualizacion = usuarioActualizacion;
}
public Date getFechaActualizacion() {
return fechaActualizacion;
}
public void setFechaActualizacion(Date fechaActualizacion) {
this.fechaActualizacion = fechaActualizacion;
}
}
The controller:
package com.sophos.mat.controller;
import java.util.Date;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.sophos.mat.beans.Proyecto;
import com.sophos.mat.services.IProyectoService;
#Controller
public class ProyectoController {
#Autowired
private IProyectoService proyectoService;
#RequestMapping(value = "/editarproyecto/{id}", method = RequestMethod.GET)
public String editarProyectoGet(ModelMap model, #PathVariable long id){
try {
Proyecto proyectoData = proyectoService.buscarProyectoPorId(id);
model.put("proyectoData", proyectoData);
return "editarproyecto";
} catch (Exception e) {
e.printStackTrace();
return "redirect:/proyectos";
}
}
#RequestMapping(value="/editarproyecto/{id}", method = RequestMethod.POST)
public String editarProyectoPost(ModelMap model, #PathVariable long id, #ModelAttribute("proyectoData")#Valid Proyecto proyectoData, BindingResult result){
if(result.hasErrors()){
return "editarproyecto";
}
try{
proyectoData.setFechaActualizacion(new Date());
proyectoService.actualizarProyecto(proyectoData);
return "redirect:/proyectos";
}catch(Exception e){
e.printStackTrace();
return "redirect:/proyectos";
}
}
public IProyectoService getProyectoService() {
return proyectoService;
}
public void setProyectoService(IProyectoService proyectoService) {
this.proyectoService = proyectoService;
}
}
And the view: editarproyecto.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib uri= "http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
<title>>Nuevo Proyecto</title>
<style>
.error { color: red; }
</style>
</head>
<body>
<h1>Nuevo Proyecto</h1>
<form:form method="post" modelAttribute="proyectoData">
<table >
<tr>
<td align="right">
Nombre proyecto:
</td>
<td>
<form:input path="nombre"/>
</td>
<td>
<form:errors path="nombre" cssClass="error"/>
</td>
</tr>
<tr>
<td align="right">
Descripción
</td>
<td>
<form:input path="descripcion"/>
</td>
<td>
<form:errors path="descripcion" cssClass="error"/>
</td>
</tr>
<tr>
<td align="right">
Cód. Sophos
</td>
<td>
<form:input path="codigoSophos"/>
</td>
<td>
<form:errors path="codigoSophos" cssClass="error"/>
</td>
</tr>
<tr>
<td align="right">
Usuario que actualiza
</td>
<td>
<form:input path="usuarioActualizacion"/>
</td>
<td>
<form:errors path="usuarioActualizacion" cssClass="error"/>
</td>
</tr>
</table>
<br>
<input type="submit" value="Guardar">
</form:form>
Proyectos
</body>
</html>
When processing POST, I get an exception from hibernate telling me that I'm trying to update to NULL the column 'DT_FECHACREACION' corresponding to the class field 'fechaCreacion'. As a temporary fix, I had to add in the POST method a query to the database to reset 'fechaCreacion' back to its previous value which I don't want to change and then update the entity with the rest of the captured values. That works but is ugly af and adds extra and unwanted overhead. My database is Oracle 11g. Thanks in advance folks!
PD: Very newbie spring developer, am in my internship and trying my best to get a full contract when the internship is over :D so any help will be much appreciated.
When you call the service you have to control which fields you return to the view.
Proyecto proyectoData = proyectoService.buscarProyectoPorId(id);
You can omit fields your DAO is returning with #JsonIgnore annotation.
....
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="T_PROYECTOS")
public class Proyecto implements Serializable{
...
#JsonIgnore
public Date getFechaCreacion() {
return fechaCreacion;
}
....
}
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