I'm trying to create simple unique username check following this tutorial.
http://javaandj2eetutor.blogspot.com/2013/12/check-username-availability-using-java.html
But My ajax call for username is fails. I'm new to ajax and somewhat new for jsp.
Here is my index.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Username Availability</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
$(".username").change(function () {
var username = $(this).val();
if (username.length >= 3) {
$(".status").html("<font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "CheckAvalability",
data: "uname="+ username,
success: function (msg) {
$(".status").ajaxComplete(function (event, request, settings) {
$(".status").html(msg);
});
}
});
}
else {
$(".status").html("<font color=red>Username should be <b>3</b> character long.</font>");
}
});
});
</script>
<div>
<label class="flable">User Name :</label> <input class="username" type="text" name="username"> <span class="status"></span>
</div>
</body>
</html>
Here is my Servlet
package hsenid;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class CheckAvailability extends HttpServlet {
private static final Logger logger = LogManager.getLogger(CheckAvailability.class);
private static final long serialVersionUID = -734503860925086969L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
logger.info("Check availability called");
DBConnector dbPool = (DBConnector)getServletContext().getAttribute("DBConnection");
Connection myConn = dbPool.getConn();
String uname = request.getParameter("username");
PreparedStatement ps = myConn.prepareStatement("select username from userdetails where username=?");
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
out.println("<font color=green><b>"+uname+"</b> is avaliable</font>");
logger.info("Username detected!!!");
}
else{
out.println("<font color=red><b>"+uname+"</b> is already in use</font>");
}
out.println();
} catch (Exception ex) {
out.println("Error ->" + ex.getMessage());
} finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Here is my servlet mapping in web.xml.
<servlet>
<servlet-name>CheckAvailability</servlet-name>
<servlet-class>hsenid.CheckAvailability</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckAvailability</servlet-name>
<url-pattern>/CheckAvailability</url-pattern>
</servlet-mapping>
This detects if minimum characters aren't added and also gives the massage check availability when type in there so I think jquery is added. Also I've run the servlet in Eclipse Mars. It do check the if a username is in the table or not. So I believe that the problem calling to the servlet because I can't see the log4j console output then. I'm unable find what wrong with my code.
Thanks in advance
Related
I have Form in JSP which have two input boxes along with submit and clear button like this
<form name="loginForm" method="GET" action="Ajaxexample" id="loginForm">
<table>
<tr>
<td>From Date</td><td><input type="text" name="n1" value=""/></td>
</tr>
<tr>
<td>End Date</td><td><input type="text" name="n2" value=""/></td>
</tr>
<tr></tr>
<tr>
<td><input type="submit" name="validpro_insert" value="Insert"></td>
<td><input type="reset" name="validpro_clear" value="Clear"></td>
</tr>
</table>
</form>
As I have called the servlet using get method in form tag which is used to get data from database via JDBC API and to handle the response I have use ajax like this
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
System.out.println("In get");
PrintWriter out = response.getWriter();
String responseStr = "";
responseStr = addUser(request); // Return either error/success
System.out.println("Reponse:" + responseStr);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(responseStr);
out.print(responseStr);
As I have to write some code to get data from DB in servlet and return that response to ajax which handle success and error on the same jsp like this
<script type="text/javascript" src="js/jq.js"></script>
<script type="text/javascript">
var form = $('#loginForm');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
error: function (theRequest,textStatus, errorThrown) {
// Success = false;
alert (theRequest.responseText);
alert(errorThrown);
alert('No graph found');//doesnt goes here
},
success: function (data) {
var result=data;
alert(result);
}
});
return false;
});
</script>
But the problem is that I am not getting any value from servlet in ajax to handle success or error
I think I am facing this problem due to servlet doget() method code.. if there is any other problem plz let me know. Any help should be appreciated
with these changes in my code, it runs successfully
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter())
String responseSend = "";
String from = request.getParameter("n1");
String to = request.getParameter("n2");
if ((from == null) || (from.equals(""))) {
System.out.println("From null");
responseSend = "error";
}
else if ((to == null) || (to.equals(""))) {
System.out.println("End null");
responseSend = "error";
}
else{
//jdbc code
System.out.println("got it");
int n1 = Integer.parseInt(request.getParameter("n1"));
int n2 = Integer.parseInt(request.getParameter("n2"));
responseSend = "code";
}
out.print(responseSend);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("In get");
processRequest(request, response);
}
As I have added a new method processrequest() with request and response parameters which will return the text/HTML to our Ajax code on the same jsp.Firstly I am confused with success/error in ajax code but now I have found that
error: function (theRequest,textStatus, errorThrown) {
alert (theRequest.responseText);
alert(errorThrown);
},
success: function (data) {
var result=data;
alert(result);
}
The error will be called when it doesn't found servlet at given URL and success will be called when it successfully call the servlet with given type and servlet URL.
I have pasted my code here that work well
Try changing your parameter
Your JSP Page
<script src="http://code.jquery.com/jquery-1.10.2.js"
type="text/javascript"></script>
<form id="form">
Enter Your Name: <input type="text" id="userName" />
</form>
<br>
<br>
<strong>Ajax Response</strong>:
<div id="ajaxGetUserServletResponse"></div>
here is your ajax
$(document).ready(function() {
$('#form').submit(function() {
$.ajax({
url : 'GetUserServlet',
data : {
userName : $('#userName').val()
},
success : function(responseText) {
$('#ajaxGetUserServletResponse').text(responseText);
}
});
});
});
your servlet file
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;
public class GetUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName").trim();
if(userName == null || "".equals(userName)){
userName = "Guest";
}
String greetings = "Hello " + userName;
response.setContentType("text/plain");
response.getWriter().write(greetings);
}
}
I am new with servlet, I am able to get data from the servlet but not able to send data to it and I want to do this without using a submitting form, can i get some help please
on the click of the button it will go to the servlet and return the text but not the value send to it
This is my index.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('#somebutton').click(function() {
$.get('GetUserServlet', function(responseText) {
$('#somediv').text(responseText);
});
});
});
$("#somebutton").click(function(){
$.ajax
(
{
url:'GetUserServlet',
data:{name:'abc'},
type:'get',
cache:false,
success:function(data){alert(data);},
error:function(){alert('error');}
}
);
}
);
</script>
</head>
<body>
<button id="somebutton" onclick="showHint('GetUserServlet.java', 'travis');">press here</button>
<div id="somediv"></div>
</body>
this my servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = "Update Sucessful";
String name = request.getParameter("name");
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write( name + text); // Write response body.
you could either use $.ajax() or $.post here. since you have used $.ajax(). please refer below correction:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('#somebutton').click(function() {
$.get('GetUserServlet', function(responseText) {
$('#somediv').text(responseText);
});
});
});
$("#somebutton").click(function(){
$.ajax({
url:'GetUserServlet',
data:{name:'abc'},
type:'get',
cache:false,
success:function(data){
alert(data);
$('#somediv').text(responseText);
},
error:function(){
alert('error');
}
}
);
}
);
</script>
</head>
<body>
<button id="somebutton">press here</button>
<div id="somediv"> </div>
</body>
and your servlet should be:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetUserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String text = "Update successfull"; //message you will recieve
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
out.println(name + " " + text);
}
You may use $.post method for this purpose.
Here is my solution
index.jsp
<!DOCTYPE html><html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$("#somebutton").click(function() {
servletCall();
});
});
function servletCall() {
$.post(
"GetUserServlet",
{name : "Message from jsp"}, //meaasge you want to send
function(result) {
$('#somediv').html('Here is your result : <strong>' + result + '</strong>'); //message you want to show
});
};
</script>
</head>
<body>
<button id="somebutton">press here</button>
<div id="somediv"></div>
</body>
</html>
GetUserServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetUserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String text = "<br>Message from servlet<br>"; //message you will recieve
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
out.println(text + name);
}
}
I am trying to check database for username availability. I don't know where it went wrong but it just keep saying "Checking availability" and never returns the answer. Below is my code.
index.jsp;
<html>
<head>
<title>Username Availability</title>
<style type="text/css">
.flable {
color: gray;
}
.status {
font-family: verdana;
font-size: 12px;
}
.uname {
color: blue;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js "></script>
<script type="text/javascript">
$(document).ready(function(){
$(".uname").change(function(){
var uname = $(this).val();
if(uname.length >= 3){
$(".status").html("<img src='images/loading.gif'><font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "check",
data: "uname="+ uname,
success: function(msg){
$(".status").ajaxComplete(function(event, request, settings){
$(".status").html(msg);
});
}
});
}
else{
$(".status").html("<font color=red>Username should be <b>3</b> character long.</font>");
}
});
});
</script>
</head>
<body>
<div>
<label class="flable">User Name :</label> <input type="text" class="uname" /> <span class="status"></span>
</div>
</body>
</html>
CheckAvailibilty.java:
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class CheckAvailability extends HttpServlet {
private static final long serialVersionUID = -734503860925086969L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String connectionURL = "jdbc:mysql://localhost:3306/quora"; // students is my database name
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "root");
String uname = request.getParameter("uname");
PreparedStatement ps = connection.prepareStatement("select username from users where username=?");
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
out.println("<font color=green><b>"+uname+"</b> is avaliable");
}
else{
out.println("<font color=red><b>"+uname+"</b> is already in use</font>");
}
out.println();
} catch (Exception ex) {
out.println("Error ->" + ex.getMessage());
} finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
web.xml:
<servlet>
<servlet-name>check</servlet-name>
<servlet-class>com.amzi.servlets.CheckAvailability</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>check</servlet-name>
<url-pattern>/check</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
You don't need ajaxComplete, when you get a msg just feed it to html()
success: function(msg){
$(".status").html(msg);
}
I am pretty new in developing web applications using Java. I have developed a small application which is a login & registration page both of which are working fine. Now, I have decided on making a admin page(using jsp). In my java code I control the redirection of jsp pages (if user!="admin"then home.jsp else user=="admin" then admin.jsp). in my admin page what I want to do is I want the admin to be able to view all the users registered and can edit their details or delete them. Someone can please suggest me on how to achieve this.
Login Servlet.java(code where I decide between admin & regular user)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email");
String password = request.getParameter("password");
String errorMsg = null;
String name;
if(email == null || email.equals("")){
errorMsg ="User Email can't be null or empty";
}
if(password == null || password.equals("")){
errorMsg = "Password can't be null or empty";
}
if(errorMsg != null){
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>"+errorMsg+"</font>");
rd.include(request, response);
}else{
Connection con = (Connection) getServletContext().getAttribute("DBConnection");
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement("select id, name, email,country from Users where email=? and password=?");
ps.setString(1, email);
ps.setString(2, password);
rs = ps.executeQuery();
if(rs != null && rs.next()){
User user = new User(rs.getString("name"), rs.getString("email"), rs.getString("country"), rs.getInt("id"));
name=rs.getString("name");
System.out.println("Name:"+ name);
//if(rs.getString("name")!="admin")
if(!name.equalsIgnoreCase("admin"))
{
logger.info("User found with details="+user);
HttpSession session = request.getSession();
session.setAttribute("User", user);
response.sendRedirect("home.jsp");
}
// String rs1=rs.getString();
else if(name.equalsIgnoreCase("admin"))
{
logger.info("Admin found with details="+user);
HttpSession session = request.getSession();
session.setAttribute("User", user);
response.sendRedirect("admin.jsp");
}
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
logger.error("User not found with email="+email);
out.println("<font color=red>No user found with given email id, please register first.</font>");
rd.include(request, response);
}
} catch (SQLException e) {
e.printStackTrace();
logger.error("Database connection problem");
throw new ServletException("DB Connection problem.");
}finally{
try {
rs.close();
ps.close();
} catch (SQLException e) {
logger.error("SQLException in closing PreparedStatement or ResultSet");;
}
}
}
home.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page import="com.javadbproject.util.User"%>
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!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=US-ASCII">
<title>Home Page</title>
<link rel="stylesheet" type="text/css" href="<c:url value='/loginstyle.css'/>">
</head>
<body>
<%User user = (User) session.getAttribute("User"); %>
<h3>Hi <%=user.getName() %></h3>
<strong>Your Email</strong>: <%=user.getEmail() %><br>
<strong>Your Country</strong>: <%=user.getCountry() %><br>
<br>
<form action="Logout" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>
AuthenticationServlet
package com.javadbproject.servlet.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
#WebFilter("/AuthenticationFilter")
public class AuthenticationFilter implements Filter {
private Logger logger = Logger.getLogger(AuthenticationFilter.class);
public void init(FilterConfig fConfig) throws ServletException {
logger.info("AuthenticationFilter initialized");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String uri = req.getRequestURI();
logger.info("Requested Resource::"+uri);
HttpSession session = req.getSession(false);
if(session == null && !(uri.endsWith("html") || uri.endsWith("Login") || uri.endsWith("Register"))){
logger.error("Unauthorized access request");
res.sendRedirect("login.html");
}else{
// pass the request along the filter chain
chain.doFilter(request, response);
}
}
public void destroy() {
//close any resources here
}
}
I am looking to develop my admin.jsp on the similar lines as my home.jsp
Thanks!!
You need a database mysql would be nice to start with.
You need to have a mysql connector jar file.
Create a class User for example.
public class User{
String iduser;
String name;
String username;
String password;
//setters and getters
}
Create a table for user in mysql or any database that you have.
CREATE TABLE sampleapplication.user (
iduser INT NOT NULL AUTO_INCREMENT ,
name VARCHAR(45) NULL ,
username VARCHAR(45) NULL ,
usercol VARCHAR(45) NULL ,
PRIMARY KEY (iduser) );
Let's start the database with java. :) add the mysql connector jar file in your build path (right click project > Build path > Configure build path > Click Add external jar > Locate mysql connector), and paste it in your web-inf>lib folder.
Create a class for database transaction. for reference
public class DatabaseTransaction{
public List<User> readDataBase() throws Exception {
try {
// this will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// setup the connection with the DB.
connect = DriverManager
.getConnection("jdbc:mysql://localhost/database?"
+ "user=sqluser&password=sqluserpw");
// statements allow to issue SQL queries to the database
statement = connect.createStatement();
// resultSet gets the result of the SQL query
resultSet = statement
.executeQuery("select * from user");
List<User> listOfUsers=new ArrayList<User>();
User userToAdd;
while (resultSet.next()) {
userToAdd = new User();
userToAdd.setUsername(resultSet.getString("username"));
userToAdd.setPassword(resultSet.getString("pword"));
userToAdd.setUserid(resultSet.getString("userid"));
userToAdd.setName(resultSet.getString("name"));
listOfUsers.add(userToAdd);
}
}
}
call the DatabaseTransaction to your filter/controller/servlet
DatabaseTransaction databaseTransaction = DatabaseTransaction();
//use your `HttpServletRequest`
//parameters are key and value
//store as attribute to access in jsp page
request.setAttribute("userList",databaseTransaction.readDataBase());
//then forward the page using `HttpServletRequest`
//dont use response.redirect(); you wont be able to use the attribute because you are using a response
//filename of the jsp
request.getRequestDispatcher("adminpage").forward(request, response);
In your jsp page. use JSTL
//import the core tag library
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
//lastly loop through the list attribute
<table>
<thead>
<tr>
<td>id</td>
<td>Name</td>
<td>Username</td>
</tr>
</thead>
<tbody>
<c:foreach items="${userList}" var="user">
<tr>
<td><c:out value="${user.iduser}"/></td>
<td><c:out value="${user.name}"/></td>
<td><c:out value="${user.username}"/></td>
</tr>
</c:foreach>
</tbody>
</table>
thats all :)
Servlet Filter is what you need, you need a logical roles for each user and allowable URL patterns per role configured and a Filter filtering each request and blocking/allowing based on it
SO first off let me begin by saying that my servlet loads the option lists in a form i have just fine. The problem is when i start from the index.jsp like i want, the lists dont load. So basically, i want to click a link on the index.jsp to take me to the servlet to then redirect me to the correct page based on the link clicked. Maybe I have been looking at this too long and just need fresh eyes but I cant get why it wont work.
I have included my Index.jsp and servlet
Index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.ArrayList" %>
<!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>Insert title here</title>
</head>
<body>
<form method="get" action="customerServlet">
Add Customer
<br/>
Add Pet
</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" })
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);
request.getRequestDispatcher("/customerManagement.jsp").forward(request, response);
//}
}
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 sendEditCustomerForm(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String url = "/customerManagement.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uri = request.getRequestURI();
if (uri.endsWith("/addCustomer")) {
addCustomer(response, request);
} else if (uri.endsWith("/addPet")) {
addPet(response, request);
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
// 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"));
}
}
}
It would be easier to use one parameter and check the value than to manually parse the URL:
Add Customer
<br/>Add Pet
In your servlet:
String action = request.getParameter("action");
if("addCustomer".equals(action)) { ... }
else if("addPet".equals(action)) { ... }
if you are using "forms", this could be the solution to send params to servlet.
<form action="ServletName" method="POST">
<input type="text" name="paramName">
<input type="submit" value="Add">
</form>
In Servlet:
String costumerName = request.getParameter("paramName");
If you just use a link like href, you should send the param like:
<a href="ServletName?ID=12345">
In servlet, same.
String costumerName = request.getParameter("ID");