This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I have tried to look for answers else where on this website but i have not been able to find anything that helps me. When ever press the create actor button to send the information to a controller i always get "HTTP 404 Status - not found: The requested resource is not available" I was just wondering if any could help me sort out this frustrating problem
This is the code for my index.jsp where i submit the information
<!DOCTYPE html>
<html>
<head>
<meta charset= "UTF-8" >
<title>Index Page</title>
</head>
<body>
<h1>Movie Example Index Page</h1>
<!--submit button goes to the controller-->
<form action="Controller" method="post">
<p>
ID <input TYPE = "text" name = "actorID"/>
Name <input TYPE ="text" name ="name"/>
Birth Year <input TYPE ="text" name ="birth_year"/>
<input TYPE="submit" value="Create Actor" />
</p>
</form>
</body>
</html>
And this is my Controller code
package MVC_Movie_Example;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// Class definition
public class Controller extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// Make an instance of a new actor
int id = Integer.parseInt(request.getParameter("actorID"));
String name = request.getParameter("name");
int birthYear = Integer.parseInt(request.getParameter("birth_year"));
Actor actor = new Actor(id, name, birthYear);
// Set the actor attribute within the request
request.setAttribute("theActor", actor);
// Send it on to a different View
request.getRequestDispatcher("outputView.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
The actor class code is
package MVC_Movie_Example; // Package declaration
// Class definition
public class Actor {
private int id;
private String name;
private int birthYear;
public Actor() {
} // Default constructor
// Value based constructor
public Actor(int externId, String externName, int externBirthYear) {
this.id = externId;
this.name = externName;
this.birthYear = externBirthYear;
}
// Actor id getter method
public int getId() {
return this.id;
}
// Actor id setter method
public void setId(int externId) {
this.id = externId;
}
// Actor name getter method
public String getName() {
return this.name;
}
// Actor name setter method
public void setName(String externName) {
this.name = externName;
}
// Other methods follow, including birthYear getter and setter
} // End of class definition
And finally this is the code for where the controller sends the output
<!DOCTYPE html>
<html>
<head>
<meta charset= "UTF-8" >
<title>Movie View Example - Output View</title>
</head>
<body>
<h1>Movie View Example – Out View Page</h1>
<jsp:useBean id="actor" type="MVC_Movie_Example.Actor" scope="request" />
<table border="1">
<tr>
<th>ID</th>
<th>Actor Name</th>
<th>Year of birth</th>
</tr>
<tr>
<td><jsp:getProperty name= "theActor" property="id" /></td>
<td><jsp:getProperty name= "theActor" property="name" /></td>
<td><jsp:getProperty name= "theActor" property="birthYear" /></td>
</tr>
</table>
</body>
</html>
WebServlet annotation above Controller class is missing
#WebServlet(name="Controller" urlPatterns={"/Controller"} )
public class Controller extends HttpServlet
{
//To-DO
}
You can also manually configure the web.xml file by adding the tags:
<servlet>
<servlet-name>Controller</servlet-name> //a name to be used for mapping requests.
<servlet-class>MVC_Movie_Example.Controller</servlet-class> //the servlet's package and class name.
</servlet>
and ....
<servlet-mapping>
<servlet-name>Controller</servlet-name> //must be the same as in tag <servlet-name> above
<url-pattern>mycontoller</url-pattern> //now..this is the name to use in the action attribute of your form.
</servlet-mapping>
The <servlet-mapping> tag will map the any url pattern matching what is specified in between the <url-pattern> tag to the servlet class specified in <servlet-name>.
This is an alternative to the annotation based solution. Hope it helps someone.
Related
Hello I have a simple form in a jsp (html) where I need to complete 4 fields (id, name, email and phone number). Whenever the ID input is empty and user clicks on "Add" button (located on form bottom), a hidden div below ID input field with the next message: "please complete ths field" is shown.
However I want this div message to be hidden again as soon as the user type a number over the input field. So I dont know how to get this keyevent and send it to servlet, and be able to hide the dive alert message again making use of a ${variable}. Im not using JavaScript, Im using Java, so I wanted to ask you, how can I achieve that
My JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<style><%#include file="/css/addEmployeeStyle2.css"%></style>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title> Add Employee Form</title>
</head>
<body>
<h1 class = "h1-title">ADD EMPLOYEE</h1>
<hr class = "hr-line">
<div class = "wrapper">
<form class = "form" action="AddEmployeeServlet" method="post">
<input type="text" name="emp_id" placeholder = "ID"class = "input"
onkeypress='return event.charCode > 47 && event.charCode < 58'>
<div id= "error" class="alert-danger" ${loginError eq 1 ? '' : 'hidden'} role="alert">
<h4>Complete this field please</h4>
</div>
<input type="text" name="emp_name" placeholder = "Name" class = "input" onkeypress="return (event.charCode > 64 &&
event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
<input type="text" name="emp_email" placeholder = "Email" class = "input">
<input type="text" name="emp_phone" placeholder ="Phone" class = "input"
onkeypress = "return event.charCode > 47 && event.charCode < 58">
<input class = "btn" type="submit" value="ADD">
</form>
</div>
</body>
<a class = "home-link" href="index.jsp"> Employee App </a>
</html>
and my servlet (AddEmployeeServlet) code:
package edu.uptc.controller;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;
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 edu.uptc.model.Employee;
/**
* Servlet implementation class EmployeeServlet
*/
#WebServlet("/AddEmployeeServlet")
public class AddEmployeeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private CopyOnWriteArrayList<Employee> employeesList;
/**
* #see HttpServlet#HttpServlet()
*/
public AddEmployeeServlet() {
super();
employeesList = new CopyOnWriteArrayList<Employee>();
burnSomeData();
}
public void burnSomeData() {
employeesList.add(new Employee(1, "Juana", "juana#mail", 11111));
employeesList.add(new Employee(2, "Pedro", "pedro#mail", 22222));
employeesList.add(new Employee(3, "Carlos", "carlos#mail", 33333));
employeesList.add(new Employee(4, "Alex", "alex#mail", 44444));
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().setAttribute("loginError", 1);
if (request.getParameter("emp_id").equals("")) {
request.getRequestDispatcher("/addEmployee.jsp").forward(request, response);
request.getSession().setAttribute("loginError", 0);
} else {
int id = Integer.valueOf(request.getParameter("emp_id"));
if (validEmployeeId(id)) {
employeesList.add(new Employee(id, request.getParameter("emp_name"), request.getParameter("emp_email"), Long.valueOf(request.getParameter("emp_phone"))));
request.getSession().setAttribute("employeesListSize", employeesList.size());
request.getRequestDispatcher("/addEmployeePositiveResponse.jsp").forward(request, response);
} else {
request.getRequestDispatcher("/addEmployeeNegativeResponse.jsp").forward(request, response);
}
request.getSession().setAttribute("employeesList", employeesList);
}
}
protected boolean validEmployeeId(int id) {
boolean valid = true;
for (Employee employee : employeesList) {
if (employee.getEmp_id() == id) {
valid = false;
break;
}
}
return valid;
}
}
You don't need to call servlet just to hide that div you can simply do that using javascript . First check if the div error doesn't have hidden class on keypress if yes then add hidden class to your div.
Demo code :
var input = document.querySelector('input[name="emp_id"]');
//on keypress call this
input.addEventListener('keypress', function(event) {
//get reference of div
var element = document.querySelector('#error')
//check it doesn't have hidden class
if (!element.classList.contains("hidden")) {
element.classList.add("hidden") //hide it
}
});
.hidden {
display: none
}
<input type="text" name="emp_id" placeholder="ID" class="input" onkeypress='return event.charCode > 47 && event.charCode < 58'>
<div id="error" class="alert-danger" ${loginError eq 1 ? '' : 'hidden'} role="alert">
<h4>Complete this field please</h4>
</div>
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 am having trouble retrieving any type of parameter from one jsp page to the other using doPost, and a form where my method is post. Note below is a minimal example.
First, I have two pages:
Here is search.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html>
<head>
<title>search</title>
<body>
<form name="search" method="post" action="search_results.jsp">
<p>
<input type="text" class="inputTitle" id="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
<button type="submit">Search</button>
<p>
</form>
</body>
</html>
And my search_results.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<title>search results</title>
<body>
<p>Title: ${movie.title}</p>
</body>
</html>
Now I have a class called SearchServlet.java:
#WebServlet("/search")
public class SearchServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
request.getRequestDispatcher("search.jsp").forward(request,response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
String title = request.getParameter("inputTitle");
String searchTitle;
try {
if(title != null && !title.isEmpty()) {
searchTitle = "hello";
} else {
searchTitle = "world";
}
session.setAttribute("movie.title", searchTitle);
request.getRequestDispatcher("search_results.jsp").forward(request, response);
} catch(ServletException e) { e.printStackTrace(); }
}
}
No matter what I enter the result (movie.title) always ends up being empty and so I get world on search_results.jsp. Why is my parameter not being passed to search_results.jsp?
It will not happen if you bypass the servlet
Look at your form action
<form name="search" method="post" action="search_results.jsp">
You are sending the post request directly to the search_results.jsp: you should send it to the servlet instead (mapped # /search)
<form name="search" method="post" action="search">
Then from the servlet you should forward the request to the search_result.jsp, which you actually did.
In addition to that when you call request.getParameter you have to keep in mind that what counts is the name of the input field, not the id. You should change the id attribute to name
<input type="text" class="inputTitle" name="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
Lastly, hopefully :) the '.' (dot) might cause issues:
session.setAttribute("movie.title", searchTitle);
When you retrieve the attribute the dot notation indicates that you are accessing a field in a object called movie
<p>Title: ${movie.title}</p> <!-- you are accessing the title property of a movie object !-->
but you do not have that...you have a movietitle, a String presumably. Change the attribute name to something like movietitle without the dot and retrieve it in the jsp the same way. the above lines will become:
session.setAttribute("movietitle", searchTitle);
<p>Title: ${movietitle}</p>
That should solve the issue.
PersonalInfoOutput.java servlet is using the doPost method. The user logs in at index.html. From index.html, the request is sent to Login.java servlet.
From there, the user is directed to the PersonalInfoOutput.java servlet.
Now, consider another page called ChangePassAdmin.html. In this html code, one of these goes to PersonalInfoOutput.java. But when I click on it from that page,
I get HTTP Status 405 - HTTP method GET is not supported by this URL.
Can someone please help me as to how I should solve this problem?
I tried changing PersonalInfoOutput.java to doGet instead of doPost but then Login.java servlet will return HTTP Status 405 - HTTP method POST is not supported by this URL. So it seems I need both doGet and doPost for this PersonalInfoOutput.java servlet.
PersonalInfoOutput.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class PersonalInfoOutput extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(false);
String employeeid = "";
if(session != null) {
employeeid = (String)session.getAttribute("employeeid");
}
boolean st = false;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", "");
PreparedStatement ps = con.prepareStatement("select employeeID, FirstName, LastName, Admin, DOB, Address, Email, HourlyRate, Gender, ALeaveBalance, SLeaveBalance, ActiveStatus, Role, BSB, BankName, AccNumber, SuperNumber, SuperCompany from payroll_system.employee_info where employeeID = ?");
ps.setString(1, employeeid);
ResultSet rs = ps.executeQuery();
st = rs.next();
if(st){
etc... (rest of the code isn't relevant to question)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel = "stylesheet" type = "text/css" href = "main.css">
<title>Login</title>
</head>
<body>
<form action="Login" method="post">
<h1>
Login
</h1>
<b>Employee ID:</b> <br>
<input type="text"name="employee_id" size="20"><br><br>
<b>Password:</b><br>
<input type="password" name="password" size="20"><br><br>
<input type="submit" value="Login"><br><br>
</form>
</body>
</html>
Login.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String employee_id = request.getParameter("employee_id");
String password = request.getParameter("password");
HttpSession session = request.getSession();
session.setAttribute("employeeid", employee_id);
if(ValidateLogin.user(employee_id, password)) {
RequestDispatcher rs = request.getRequestDispatcher("PersonalInfoOutput");
rs.forward(request, response);
}
else
{
out.print("Employee ID or Password is incorrect. Please try again.");
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
}
}
}
ChangePassAdmin.html
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<link rel = "stylesheet" type = "text/css" href = "main.css">
<link rel = "stylesheet" type = "text/css" href = "sidebar.css">
<title>Change Password</title>
<style>
table { border-collapse: collapse; width: 50%; } th, td { text-align: left; padding: 8px; } tr:nth-child(even){background-color: #f2f2f2}
tr:hover {background-color: #e2f4ff;}
</style>
</head>
<body>
<ul>
<li><a href=PersonalInfoOutput>View Personal Information</a></li>
<li><a href=PersonalInfoOutput>View Expense Claims</a></li>
<li><a href=PersonalInfoOutput>View Payslips</a></li>
<li><a class=active >Change Password</a></li>
<li><a href=PersonalInfoOutput>Maintain Employee Information</a></li>
<li><a href=PersonalInfoOutput>Maintain Tax Information</a></li>
<li><a href=PersonalInfoOutput>Maintain Payroll Items</a></li>
<li><a href=PersonalInfoOutput>Maintain Timesheet</a></li>
<li><a href=PersonalInfoOutput>Maintain Employee Expenses</a></li>
<li><a href=PersonalInfoOutput>Run Payroll</a></li>
<li><a href=PersonalInfoOutput>Generate Reports</a></li>
</ul>
<div style=margin-left:25%;padding:1px;>
</div>
<div id="container">
<h1>Change Password</h1>
<form action ="NewPassword" method = post>
<table border ="1">
<tr>
<td>Existing Password:</td>
<td><input type = "password" name = "oldpassword" size = "20"></td>
</tr>
<tr>
<td>New Password:</td>
<td><input type = "password" name = "newpassword" size = "20"></td>
</tr>
<tr>
<td>Confirm New Password</td>
<td><input type = "password" name = "confirmpassword" size = "20"></td>
</tr>
</table>
<br>
<br>
<input type = "submit" value = "Update Password">
</form>.
</div>
</body>
</html>
In ChangePassAdmin.html, double quotes around post are missing.
Both of your Servlet should have doPost method as your form is using "post" action.
<form action ="NewPassword" method = "post">
Additionally you will need two methods in this case. Add both doGet and doPost in your servlet. doPost will be used by form and doGet by links. By default all links are GET.
You can do it like:
Edit:
public class PersonalInfoOutput extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Your servlets code should be here
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
doPost() method to receive form based request. doGet() method to receive href based request. But in both cases processRequest() method will be called.
I believe the problem is that you're using the PersonalInfoOutput servlet in two ways:
Forwarding from Login servlet, which by forwarding keeps using POST method
And by href from the HTML, which by default uses method GET
Wouldn't a possible solution be for you to refactor your code, which would be good for you to do anyway, so that you implement both doGet() and doPost() in the PersonalInfoOutput servlet without repeating a lot of code?
Or you could refactor the employee database retrieval to an external class, that would be called from Login without the need to redirect from one servlet to another, and implement GET instead of POST in PersonalInfoOutput.
I've got a jsp file:
... import <%# page import="classPath.ExampleClass" %>
<%
ExampleClass cl = new ExampleClass(request);
%>
The Code of ExampleClass (Java):
private HttpServletRequest req;
public ExampleClass(HttpServletRequest req) {
this.req = req;
}
So I want to receive the complete request to evaluate it in Java. But during deploying the following error appears:
Cannot process HttpRequest to Servlet
Why?
Do not messup.Use of implicit objects of JSP
JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.
just write
<%
ExampleClass cl = new ExampleClass(request);
%>
Create bean class like.
public class ExampleClass{
HttpServletRequest request;
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
}
Now pass implicit request object with jsp tag
<jsp:useBean id="exampleClass" class="classPath.ExampleClass" scope="request"/>
<jsp:setProperty name="exampleClass" property="request" value="${pageContext.request}"/>
In your jsp add the following directive:
<jsp:useBean id="bean" class="classPath.ExampleClass" scope="request">
<jsp:setProperty name="bean" property="*" />
<jsp:setProperty name="bean" property="request" value="${pageContext.request}" />
</jsp:useBean>
The property "*" means that all attributes coming from the request will be set on the bean (class) e.g. form submission with various input fields.
The property "request" will set the HttpServletRequest as the last parameter so this method can be used as an indicator to start your logic.
Your class could look like:
public class ExampleClass {
private HttpServletRequest request;
private String fieldValue;
public void doLogic() {
// do your controller logic here
}
public HttpServletRequest getRequest() {
return request;
}
public String getFieldValue() {
return fieldValue;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
doLogic();
}
public void setFieldValue(String fieldValue) {
this.fieldValue = fieldValue;
}
}
Notice that the property fieldValue is a custom field that you can add and can be set via form submission as mentioned above:
<form method="post">
<input name="feildValue" type="text" value="${bean.fieldValue}"/>
<input name="btnSubmit" type="submit" value="Submit"/>
</form>