Servlet won't redirect to receipt page - java

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

To troubleshoot, add response.getWriter().write("..."); return; to the two possible problem places where you are doing nothing now:
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// update customer
int customerId = 0;
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
response.getWriter().write("Error: Customer ID could not be parsed to a number");
return; //to exit the function: we don't want to do anything more if we encounter this error
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setFirstName(request.getParameter("firstName"));
customer.setLastName(request.getParameter("lastName"));
customer.setEmail(request.getParameter("email"));
customer.setPhone(request.getParameter("phone"));
customer.setAddress(request.getParameter("address"));
customer.setCity(request.getParameter("city"));
customer.setZip(request.getParameter("zip"));
makeCustomerReceipt(request, response);
return; //to exit the function: you should always do this after forward or redirect
}
else
{
response.getWriter().write("Error: customer is null");
return; //to exit the function
}
}
}

Related

Inserting a data in jsp by using select and option tag

in my application i am reading a data from table class and i insert the id value in table test. i usually use table and insert link in jsp but this time i need to show my data by option tag and button for inserting. when i click on insert button i have this error ( threw exception [java.lang.NumberFormatException: For input string: ""] with root cause
java.lang.NumberFormatException: For input string: "" )
i have no problem when i use table and link for insert so the servlet and database class working fine. i think problem can be how i am using option tag
jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table>
<c:forEach var="tempstudent" items="${select}">
<c:url var="insert" value="add_course">
<c:param name="command" value="insert"/>
<c:param name="courseid" value="${tempstudent.id}"/>
</c:url>
<tr>
<td>${tempstudent.id}</td>
<td>${tempstudent.name}</td>
<td>
<a href="${insert}"
onclick="if (!(confirm('Are you sure you want to insert this student?'))) return false">
insert</a>
</td>
</tr>
</c:forEach>
</table>
<form action="add_course" method="GET">
<input type="hidden" name="command" value="insert" />
<input type="hidden" name="courseid" value="${tempstudent.id}"/>
<select>
<c:forEach var="tempstudent" items="${select}">
<option value="courseid">${tempstudent.id},<td>${tempstudent.name}</td>
</option>
</c:forEach>
</select>
<td><label></label></td>
<td><input type="submit" value="Save" class="save"/></td>
</form>
</body>
</html>
servlet file
package com.web;
import java.io.IOException;
import java.util.List;
import javax.annotation.Resource;
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.sql.DataSource;
/**
* Servlet implementation class add_course
*/
#WebServlet("/add_course")
public class add_course extends HttpServlet {
private dbutil dbutil;
#Resource(name="jdbc/web_student_tracker")
private DataSource dataSource;
#Override
public void init() throws ServletException {
//dbutil= new dbutil(dataSource);
super.init();
try {
dbutil=new dbutil(dataSource);
}
catch(Exception exc) {
throw new ServletException(exc);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// List<student> student;
// try {
// student = dbutil.getcourse();
// request.setAttribute("select",student);
// RequestDispatcher dispatcher = request.getRequestDispatcher("/course.jsp");
// dispatcher.forward(request,response);
// } catch (Exception e) { // TODO Auto-generated catch block
// e.printStackTrace();
// }
try {
String thecommand=request.getParameter("command");
if(thecommand==null) {
thecommand="LIST";
}
switch(thecommand) {
case"LIST":
listcourse(request,response);
break;
case"insert":
insertcourse(request,response);
break;
}
}
catch(Exception exc) {
throw new ServletException(exc);
}
}
private void insertcourse(HttpServletRequest request, HttpServletResponse response) throws Exception {
int courseid = Integer.parseInt(request.getParameter("courseid"));
student thestudent=new student(courseid);
dbutil.insetcourse(thestudent);
request.setAttribute("message", "Records loaded successfully");
RequestDispatcher dispatcher = request.getRequestDispatcher("/course.jsp");
dispatcher.forward(request,response);
// int courseid = Integer.parseInt(request.getParameter("courseid"));
// student thestudent=new student(courseid);
// dbutil.insetcourse(thestudent);
// insertcourse(request,response);
}
private void listcourse(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<course> student=dbutil.getcourse();
request.setAttribute("select",student);
RequestDispatcher dispatcher = request.getRequestDispatcher("/course.jsp");
dispatcher.forward(request,response);
}
}
// database class
public List <course> getcourse() throws Exception{
List<course> course=new ArrayList<>();
Connection myConn = null;
Statement myStmt = null;
ResultSet myRs = null;
try {
myConn=dataSource.getConnection();
//String sql="select id from class";
String sql ="select id,name from class";
myStmt=myConn.createStatement();
myRs=myStmt.executeQuery(sql);
while (myRs.next()) {
int myid = myRs.getInt("id");
String myname =myRs.getString("name");
course tempstudent = new course(myid,myname);
course.add(tempstudent);
}
return course;
}
finally {
// close JDBC objects
close(myConn, myStmt, myRs);
}
}
public void insetcourse(student thestudent)throws SQLException {
Connection myConn = null;
PreparedStatement myStmt=null;
/////////
try {
myConn = dataSource.getConnection();
String sql="insert into test"+"(id)"+"value(?)";
myStmt=myConn.prepareStatement(sql);
myStmt.setInt(1,thestudent.getId());
myStmt.execute();
}
finally {
close(myConn,myStmt,null);
}
}
Your <select> tag is passing a string value i.e : <option value="courseid">..</option> thats why you are getting java.lang.NumberFormatException: For input string: "" because here value="cousreid" which will get pass it is string .Instead your code should look like below for <select> :
<!--giving name attribute to access it in servlet-->
<select name="select">
<c:forEach var="tempstudent" items="${select}">
<!--passing id-->
<option value="${tempstudent.id}">${tempstudent.id},
<td>${tempstudent.name}</td>
</option>
</c:forEach>
</select>
In your servlet access <select> value using below code :
int courseid = Integer.parseInt(request.getParameter("select"));

Java Servlet Showing Blank Page

I have created a simple EJB Application to demonstrate Session Bean by making a simple calculator on a JSP Page.
For Stateless SessionBean.
index.jsp
<%#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>
<div>Calculator</div>
<form action="NewServlet" method="post">
value 1:<input type="text" name="v1"><br>
value 2:<input type="text" name="v2"><br>
<input type="radio" name="g" value="1"> ADDITION <br>
<input type="radio" name="g" value="2"> SUBTRACT <br>
<input type="radio" name="g" value="3"> DIVIDE <br>
<input type="radio" name="g" value="4"> MULTIPLY <br>
<input type="submit" value="=">
</form>
</body>
</html>
NewSessionBean.java
package com;
import javax.ejb.Stateless;
#Stateless
public class NewSessionBean implements NewSessionBeanLocal {
#Override
public int sub(int a, int b) {
return (a-b);
}
#Override
public int add(int v1, int v2) {
return v1+v2;
}
#Override
public int mul(int v1, int v2) {
return v1*v2;
}
#Override
public int div(int v1, int v2) {
return v1/v2;
}
}
NewServlet.java
package com;
import com.NewSessionBeanLocal;
import java.io.IOException;
import java.io.PrintWriter;
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;
#WebServlet(name="NewServlet", urlPatterns={"/NewServlet"})
public class NewServlet extends HttpServlet {
#EJB
private NewSessionBeanLocal newSessionBean;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
try {
int v1=Integer.parseInt(request.getParameter("v1"));
int v2=Integer.parseInt(request.getParameter("v2"));
String f=request.getParameter("g");
int result=0;
if(f.equals("1"))
{
result=newSessionBean.add(v1, v2);
out.println("<h1>result =>"+result+"<h1>");
}
else if(f.equals("2"))
{
result=newSessionBean.sub(v1, v2);
out.println("<h1>result =>"+result+"<h1>");
}
else if(f.equals("3"))
{
result=newSessionBean.div(v1, v2);
out.println("<h1>result =>"+result+"<h1>");
}
else
{
result=newSessionBean.mul(v1, v2);
out.println("<h1>result =>"+result+"<h1>");
}
}
finally{
out.close();
}
}
#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";
}
}
After writing the program, I went to the Project Folder(EnterpriseApplication3) right-click => properties => run => Relative Url: /index.jsp.
So that when I build and run the project it should start from index.jsp page.
Index.jsp page is working perfectly but when I press submit, i am getting NewServlet page which is blank.
Browser: Chrome, Mozilla, IE (All latest versions).
index.jsp Page

WebServices Calculator client don't work

is a client of a java web calculator, when I enter the values of the numbers and click on calculate the result is 0 .
this is index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Calculadora</title>
</head>
<body>
<hr/>
<div align="center">
<form action="calcular.do" style="font-family:arial">
Numero 1:<br>
<input type="text" name="num1"
style="text-align:right"/><br><br>
Numero 2:<br>
<input type="text" name="num2"
style="text-align:right"/><br><br>
<input type="radio" name="operacion" value="Suma" checked="true" />
Suma<br>
<input type="radio" name="operacion" value="Resta" />
Resta<br>
<input type="radio" name="operacion" value="Multiplicacion" />
Multiplicacion<br>
<input type="radio" name="operacion" value="division" />
Divison<br>
<input type="submit" value="calcular" name="Calcular" />
<br><br>
Resultado:<br>
<input type="text" name="resultado" value="${result}"
style="text-align:right"/><br><br>
</form>
<hr/>
</div>
</body>
</html>
this is servlet calcular.java
package controlador;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "Calcular", urlPatterns = {"/calcular.do"})
public class Calcular extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String number1 = request.getParameter("num1");
String number2 = request.getParameter("num2");
if(number1 !=null && !number1.isEmpty() && number2 !=null && !number2.isEmpty()){
jaxws.SWCalculator_Service service;
jaxws.SWCalculator port;
try{
service= new jaxws.SWCalculator_Service();
port=service.getSWCalculatorPort();
double num1 = Double.parseDouble(number1);
double num2= Double.parseDouble(number2);
double resultado=0;
String operacion = request.getParameter("operacion");
if (operacion.equals("suma")){
resultado = port.suma(num1, num2);
}
if (operacion.equals("resta")){
resultado = port.resta(num1, num2);
}
if (operacion.equals("multiplicacion")){
resultado = port.multiplicacion(num1, num2);
}
if (operacion.equals("division")){
resultado = port.division(num1, num2);
}
double respuesta = resultado;
request.setAttribute("result",respuesta);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
catch (NumberFormatException ex)
{
System.out.println("numero incorrecto\n");
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
#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>
}
the calculator works by entering 2 numbers and selecting by means of an radio button the operation (Addition, subtraction, multiplication and division) and when clicking on submit button the result of the operation must be given.
Try changing value="${result}" to value="${requestScope.result}"
<input type="text" name="resultado" value="${requestScope.result}"
style="text-align:right"/>

How can I Post parameter from JSP to HTTP using Java

I want to sent parameter from JSP to HTTP Servlet. but it doesn't work:(
I would like create a button to sent information to disable/enable user.
I'm still new to JSP and HTTP.
I hope can some one help me.
I hope it's enough to Overview
here my code:
admin.jsp
<%#page import="model.*"%>
<%#page import="java.util.*"%>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
List<Category> categories = (List<Category>) request.getAttribute("categories");
List<User> users = (List<User>) request.getAttribute("users");
User credentials = (User) request.getSession().getAttribute("credentials");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<jsp:include page="header.jsp"></jsp:include>
<jsp:include page="/WEB-INF/navbar.jsp"></jsp:include>
<h1 style="color:green;">Admin Control Page</h1>
<h2>categories</h2>
<% for (Category category : categories) { %>
<%=category.getName()%><br/>
<% } %>
<form method="post" action="<%=request.getContextPath()%>/admin" accept-charset="iso-8859-1">
<br/>
add new category: <input name="categoryName" />
<input type="hidden" name="event" value="createCategory" />
<input type="submit" />
</form>
<h2>users</h2>
<% for (User user : users){
if(user.getRole().getId()!= 1){
out.println("<a href='"+request.getContextPath()+"/user/"+user.getUsername()+"'><b>"+user.getUsername()+"</b></a>");
int id = user.getId();
%>
<%if(user.isEnabled()){ %>
//My Problem is here
<form action="/admin" method="POST">
<input value="<%user.getId();%>">
<input type="submit" value="Submit" />
</form>
<%}else if(!user.isEnabled()){
%>
// TODO Button
<%}%>
<p><hr>
<%
}
}
%>
</body>
</html>
AdminController.java
package controller;
import java.io.IOException;
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 dao.DatabaseManager;
import model.Category;
import model.User;
#WebServlet("/admin/*")
public class AdminController extends HttpServlet {
private DatabaseManager db = DatabaseManager.getInstance();
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// check admin, if not "error"
User user = (User) req.getSession().getAttribute("credentials");
if (user == null || !user.getRole().getName().equals("admin")) {
resp.sendError(403);
return;
}
// load page
req.setAttribute("categories", db.getCategoryDAO().findAll());
req.setAttribute("users", db.getUserDAO().findAll());
req.getRequestDispatcher("/WEB-INF/admin.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// event
String event = req.getParameter("event");
// create new category
if (event.equals("createCategory")) {
String categoryName = req.getParameter("categoryName").trim();
try {
Category cat = new Category();
cat.setName(categoryName);
db.getCategoryDAO().create(cat);
} catch (IllegalArgumentException e) {
// error
req.setAttribute("msg", e.getMessage());
doGet(req, resp);
return;
}
// Create successful
resp.sendRedirect(req.getContextPath() + "/admin");
return;
}
String idTemp = req.getParameter("id");
try{
int id = Integer.parseInt(idTemp);
User user = db.getUserDAO().findById(id);
user.setEnabled(false);
} catch(IllegalArgumentException e){
e.getMessage();
return;
}
resp.sendRedirect(req.getContextPath() + "/admin");
return;
}
}
Change
#WebServlet("/admin/*")
To
#WebServlet("/admin")
And you can use either:
action="<%=request.getContextPath()%>/admin" or action="admin".
And if you are still having error then mention the error name :)

Putting Inputs into JSTL session variables to later display on screen

I keep looking online for answers to put my inputs into sessions so I can output on a receipt page but all of them are different. Is there a preferred way someone could should me?
I will post my servlet and form below
Form
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.ArrayList" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Customer Management</title>
</head>
<body>
<form action="customerServlet" method="post">
<c:set var="customer" items="${sessionScope.customers}">
First Name:<br>
<input type="text" name="firstName"/><br>
<c:out value="${customer.getFirstName() }"></c:out>
Last Name:<br>
<input type="text" name="lastName" <c:out value="customer.getLastName()"></c:out>/><br>
Email:<br>
<input type="text" name="email"/><br>
Phone Number:<br>
<input type="text" name="phone"/><br>
Phone Type:<br>
<select name="thePhones" id="selectPhones">
<option selected value="choose">
Select a Phone
</option>
<c:forEach items="${sessionScope.phones}" var="current" >
<option>${current.getPhoneName()}</option>
</c:forEach>
</select><br>
Street Address:<br>
<input type="text" name="streetAddress"/><br>
Apartment Number:<br>
<input type="text" name="apartmentNumber"/><br>
City:<br>
<input type="text" name="city"/><br>
State:<br>
<select name="states" id="states">
<option selected value="Wisconsin">
Select a State
</option>
<c:forEach items="${sessionScope.states}" var="current" >
<option>${current.getStates()}</option>
</c:forEach>
</select>
<input type="submit" value="submit">
</c:set>
</form>
</body>
</html>
Servlet
package edu.witc.Assignment03.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.annotation.WebServlet;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import edu.witc.Assignment03.model.Customer;
import edu.witc.Assignment03.model.Phone;
import edu.witc.Assignment03.model.States;
#WebServlet(description = "servlet to get act as controller between form and models", urlPatterns = { "/customerServlet","/addCustomer","/addPet", "/customerManagement" })
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public CustomerServlet() {
super();
}
private void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
Phone phone = new Phone();
States state = new States();
Collection<Phone> phones = phone.getPhoneCollection();
Collection<States> states = state.getStateCollection();
session.setAttribute("phones", phones);
session.setAttribute("states", states);
//}
}
private List<edu.witc.Assignment03.model.Customer> customers = new ArrayList<Customer>();
private void addCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/customerManagement.jsp";
processRequest(request, response);
request.getRequestDispatcher(url).forward(request,response);
}
private void addPet(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/pets.jsp";
request.getRequestDispatcher(url).forward(request,response);
}
private Customer getCustomer(int customerId) {
for (Customer customer : customers) {
if (customer.getCustomerId() == customerId) {
return customer;
}
}
return null;
}
private void makeCustomerReceipt(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String url = "/receipt.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if("addCustomer".equals(action)) {
addCustomer(response, request);
}
else if("addPet".equals(action)) {
addPet(response, request);
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// update customer
int customerId = 0;
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setFirstName(request.getParameter("firstName"));
customer.setLastName(request.getParameter("lastName"));
customer.setEmail(request.getParameter("email"));
customer.setPhone(request.getParameter("phone"));
customer.setAddress(request.getParameter("address"));
customer.setCity(request.getParameter("city"));
customer.setZip(request.getParameter("zip"));
makeCustomerReceipt(request, response);
}
}
}

Categories

Resources