Putting Inputs into JSTL session variables to later display on screen - java

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

Related

How should I send a parameter from jsp page to a servlet then to a jsp page then to a servlet?

I am trying to make a login form. and want the username parameter to accessed by the changepass.java file.
The flow of the application is:
login.jsp -> LoginServlet -> AfterLogin.jsp -> ChangePass.jsp -> ChangePassword Servlet
I tried using the session and request dispatcher for this it is not working.
I am able to get the parameter from login.jsp to ChangePass.jsp but after that the changePassword servlet is not able to access it.
My code for the flow is:
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<body>
<div align="center">
<form name="login" onsubmit="return onSubmit()" action="LoginServlet">
<h2 style="color:blue">Account Login</h2>
<table style="background-color:powderblue;border: 2px solid green;border-color:green;">
<tr><td>Enter User Name:</td><td><input type="text" name="username" minlength="6" required></td></tr>
<tr><td>Enter Pass Word:</td><td><input type="password" name="password" id="password" required></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="login"></td></tr>
</table>
<br>
<u>Home</u>
</form>
</div>
<%
String msg=(String) request.getAttribute("msg");
if(msg!=null){
%>
<p style="color:red"><%=msg%></p>
<%
}
%>
<script type="text/javascript">
function onSubmit(){
var y=document.login.password.value;
var passR=/^(?=.*\d)(?=.*[A-Z]).{6,20}$/;
if(!y.match(passR)){
alert("Password must contain at least one number and one UpperCase letter");
document.getElementById("password").focus();
}
}
</script>
</body>
</html>
LoginServlet.java
package com.wipro.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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;
import com.wipro.util.DButil;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try{
Connection con=DButil.getConnection();
PrintWriter out=response.getWriter();
String username=request.getParameter("username");
String password=request.getParameter("password");
String sql="select * from user_table where username=? and password=?";
PreparedStatement st=con.prepareStatement(sql);
st.setString(1, username);
st.setString(2, password);
ResultSet rs=st.executeQuery();
if(rs.next()) {
HttpSession se=request.getSession();
se.setAttribute("username", username );
request.getRequestDispatcher("AfterLogin.jsp").include(request, response);
}
else {
request.setAttribute("msg", "Invalid Credentials");
request.getRequestDispatcher("login.jsp").include(request, response);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
AfterLogin.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1><font color=green> Welcome <%=session.getAttribute("username")%></font></h1>
Change Password
</body>
</html>
ChangePass.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div align="center">
<form name="changePS" onsubmit="return onSubmit()" action="ChangePassword">
<%
String username=(String)session.getAttribute("username");
request.setAttribute("username", username);
%>
<h1><font color=green> Welcome <%=username%></font></h1>
<h2 style="color:blue">Change Password</h2>
<table style="background-color:powderblue;border: 2px solid green;border-color:green;">
<tr><td>Old Password:</td><td><input type="password" name="oldpwd" id="oldpwd" required></td></tr>
<tr><td>New Password:</td><td><input type="password" name="newpwd" id="newpwd" required></td></tr>
<tr><td>Confirm Password:</td><td><input type="password" name="confpwd" id="confpwd" required></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="login"></td></tr>
</table>
<br>
<u>Home</u>
</form>
</div>
<script type="text/javascript">
function onSubmit(){
y=document.changePS.oldpwd.value;
z=document.changePS.newpwd.value;
a=document.changePS.confpwd.value;
passR=/^(?=.*\d)(?=.*[A-Z]).{6,20}$/;
if(z != a){
alert("New Password and Confirm Password do not match");
document.getElementById("confpwd").focus();
return false;
}
if(!y.match(passR)){
alert("Old Password must contain at least one number,one UpperCase letters");
document.getElementById("oldpwd").focus();
return false;
}
if(!z.match(passR)){
alert("New Password must contain at least one number,one UpperCase letters");
document.getElementById("newpwd").focus();
return false;
}
return true;
}
</body>
</html>
ChangePassword.java
package com.wipro.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
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;
import com.wipro.util.DButil;
/**
* Servlet implementation class ChangePassword
*/
#WebServlet("/ChangePassword")
public class ChangePassword extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ChangePassword() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try{
Connection con=DButil.getConnection();
PrintWriter out=response.getWriter();
String username = (String)request.getAttribute("username");
String password=request.getParameter("newPwd");
String sql="update user_table set password=? where username=?";
PreparedStatement st=con.prepareStatement(sql);
st.setString(1, username);
st.setString(2, password);
int rs=st.executeUpdate();
if(rs!=0) {
out.println("<h1><font color=green> Updated the password </font></h1>");
}
else {
out.println("<h1><font color=red> Sorry no username with this name </font></h1>"+username);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}

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 :)

Servlet won't redirect to receipt page

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

Categories

Resources