capturing data from the drop down menu and radio buttons - java

I'm trying to capture the data I enter from my form. Once I hit the submit button but I'm having difficulties. Below is my simple code. I'm trying to work on a registration page that captures all the info about a person. Some of the data have a drop down menu and radio button. I want to capture and store everything in the database(mysql).
My servlet code:
package com.Registration.Controllers;
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;
/**
* Servlet implementation class AddUserSevelet
*/
#WebServlet("/AddUserSevelet")
public class AddUserSevelet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public AddUserSevelet() {
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
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter write = response.getWriter();
String username = request.getParameter("uname");
String password = request.getParameter("pass");
String country = request.getParameter("country");
AddUser register =new AddUser();
if (register.adduser(username, password, country)){
write.println("You Have Been Registered Successfully");
} else {
write.print("ERROR WHILE LOADING");
}
}
}
my adduser class
package com.Registration.Controllers;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class AddUser {
public boolean adduser(String userName,String password,String country){
boolean isRegistered = false;
try{
Connection con = DB_Connection.getConnection();
PreparedStatement psmt = con.prepareStatement("insert into user VALUES(default,?,?,?,?)");
psmt.setString(1, userName);
psmt.setString(2, password);
psmt.setString(3, country);
int success = psmt.executeUpdate();
if(success > 0){
isRegistered = true;
}
}
catch(Exception e){
e.printStackTrace();
}
return isRegistered;
}
}
My HTML code:
<body>
<form action="AddUserSevelet" method="post">
UserName: <input type="text" name="uname"/><br/><hr/>
password: <input type="password" name="pass"/><br/><hr/>
Country: <input type="text" name="country"/><br/><hr/>
<input type="radio" name="color" value="red" checked>red
<br>
<input type="radio" name="color" value="blue" checked>blue
<br>
<input type="radio" name="color" value="white">white
<br/><hr/>
<br/><hr/>
<select name ="cars">
<option value="BMW"> BMW 320i</option>
<option value="BENZ"> Compressor</option>
<option value="Toyota"> Allion</option>
<option value="Audi"> A5</option>
<option value="Jeep"> Cheroki</option>
<option value="Volvo"> Volvo g5</option>
</select>
<input type="submit" value="Register"/><br/><hr/>
</body>
My question is how do I capture the data from the drop down menu and the radio button, if I put change my servlet code to:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter write = response.getWriter();
String username = request.getParameter("uname");
String password = request.getParameter("pass");
String country = request.getParameter("country");
String cars = request.getParameter("cars");
String color = request.getParameter("color");
AddUser register =new AddUser();
if (register.adduser(username, password, country, cars , color)){
write.println("You Have Been Registered Successfully");
} else {
write.print("ERROR WHILE LOADING");
}
My class code:
Connection con = DB_Connection.getConnection();
PreparedStatement psmt = con.prepareStatement("insert into 'user'(?,?,?,?,?) VALUES(default,?,?,?,?,?,?)");
psmt.setString(1, userName);
psmt.setString(2, password);
psmt.setString(3, country);
psmt.setString(4, cars);
psmt.setString(5, color);
Im getting the error:
error while loading and in the console its java.sql.SQLEXCEPTION:No VALUE specified for parameter 6
Kindly help me with sugestions or solutions on how I can capture data and insert it or edit it using servlets. I'm a newbie just trying to learn. Thank you!

Related

Retrieving record from database in Java by using select option tag

I want to retrieve record from database by clicking on the option selected from drop down list and it as a table on the web page. But after implementing following code the web page is blank now what should I do? Any type of help will be appreciable. Here is my index.jsp page:
<%#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>
<form name="f1" action="portal" method="POST">
<h3>Name of the Book : </h3>
<select name="book" id="book">
<option value="">Select</option>
<option value="1">The Pilgrims Progress</option>
<option value="2">Robinson Crusoe</option>
<option value="3">Gullivers Travels</option>
<option value="4">Clarissa</option>
<option value="5">Tom Jones</option>
<option value="6">The Life and Opinions of Tristram Shandy, Gentleman</option>
<option value="7">Emma</option>
<option value="8">Frankenstein</option>
<option value="9">Nightmare Abbey</option>
<option value="10">The Narrative of Arthur Gordon Pym of Nantucket</option>
<option value="11">Sybil</option>
<option value="12">Jane Eyre</option>
<option value="13">Wuthering Heights</option>
<option value="14">Vanity Fair</option>
<option value="15">David Copperfield</option>
<option value="16">The Scarlet Letter</option>
<option value="17">Moby-Dick</option>
<option value="18">Alices Adventures in Wonderland</option>
<option value="19">The Moonstone</option>
<option value="20">Little Women</option>
<option value="21">Middlemarch</option>
</select>
<input type="submit" value="submit" />
</form>
</body>
</html>
And here is my servlet page for retrieving data from database
package com;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
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 portal extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request
* servlet request
* #param response
* servlet response
* #throws ServletException
* if a servlet-specific error occurs
* #throws IOException
* if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String book = request.getParameter("book");
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "password");
PreparedStatement pt = conn.prepareStatement("Select * from book where Book_Name = ?");
pt.setString(1, book);
out.print("<table width = 75%>");
out.print("<center><h1>Welcome To The Portal</h1></center>");
ResultSet rs = pt.executeQuery();
ResultSetMetaData rsd = rs.getMetaData();
while (rs.next()) {
out.print("<tr>");
out.print("<td>" + rsmd.getColumnName(1) + "</td>");
out.print("<td>" + rs.getString(1) + "</td></tr>");
out.print("<tr><td>" + rsmd.getColumnName(2) + "</td>");
out.print("<td>" + rs.getString(2) + "</td></tr>");
out.print("<tr><td>" + rsmd.getColumnName(3) + "</td>");
out.print("<td>" + rs.getString(3) + "</td></tr>");
out.print("<tr><td>" + rsmd.getColumnName(4) + "</td>");
out.print("<td>" + rs.getString(4) + "</td></tr>");
RequestDispatcher rd = request.getRequestDispatcher("logout.jsp");
rd.include(request, response);
}
out.println("</table>");
}
catch (Exception e) {
out.println(e);
}
}
// <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>
}
now I don't know where I miss something.
I suggest that you use your servlet as a controller that control the data in your application and not as a vue where you write html tags
this example may help you :
Firstly, create a serialisable java class where you put communicate with database :
public class BookData implements Serializable {
private String ISBN;
private String titre;
private String auteur;
private int ID;
private String editeur;
// ADD GETTER AN SETTER METHODS
public BookData(String titre, String auteur, int ID, String editeur, String ISBN) {
this.titre = titre;
this.auteur = auteur;
this.ID = ID;
this.editeur = editeur;
this.ISBN = ISBN;
}
public List<BookData> loadData(String book) {
List<BookData> actorList = new ArrayList<BookData>();
com.mysql.jdbc.PreparedStatement ps = null;
ResultSet rs = null;
String url = "jdbc:mysql://127.0.0.1:3306/DATABASENAME";// CHANGE
String name = "NAME";// CHANGE
String pw = "PWD";// CHANGE
String driver = "com.mysql.jdbc.Driver";
Connection connexion = null;
try {
Class.forName(driver).newInstance();
connexion = DriverManager.getConnection(url, name, pw);
String q = "Select * from book where Book_Name ='" + book + "'";
Statement commande = connexion.createStatement();
rs = commande.executeQuery(q);
while (rs.next()) {
BookData bk = new BookData(rs.getString("Book_Title"), rs.getString("Book_Author"), rs.getInt("ID"),
rs.getString("Publisher"), rs.getString("ISBN"));/* CHANGE COLUMN NAMES */
actorList.add(bk);
}
return actorList;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
rs.close();
connexion.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Secondly the servlet :
public class EXAMPLE_SERVLET extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String option = request.getParameter("book");
BookData dao = new BookData();
List<BookData> list = dao.loadData(option);
request.setAttribute("booklist", list);
RequestDispatcher view = request.getRequestDispatcher("test.jsp");
view.forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
then the JSP ((test.jsp))
<table>
<thead>
<tr>
<th>titre</th> //...COLUMNS
</tr>
</thead>
<tbody>
<c:forEach var="employee" items="${booklist}">
<tr>
<td style="width: 110px; color: #3278b3;">${employee.titre}</td>
//...ROWS
</tr>
</c:forEach>
</tbody>
</table>
i solved my question thanks to everyone who helped me but not i get it where i was doind a mistake it was in option tag value attribute i took the value as 1 , 2 and 3 .. so on but it should be same as the text and in servlet page i've changed the while loop to if & else so it is working fine.. thanku soo much for all your help

Unable to retrive data from database and display in JSP using Servlet

I am beginner in JSP and Servlets. I have searched about the issue and couldn't found exactly what the solution is.
I am passing data from jsp to servlet and inserting in database and from there retrieving the same and passing to JSP for display
I was able to pass data from JSP and insert in database successfully but unable to retrieve and display in jsp again. Below is code.
jsp:
<!DOCTYPE HTML><%#page language="java"
contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>loginform</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form name=loginform action=TestServlet method=post>
Input ID <input type=text name="id" size=10></input> <br><br>
<Input type="button" value=Retrive> <br>
<label for = "getdata" ></label> <br>
value is <%= request.getSession().getAttribute("data") %>
<input type=submit value=submit></input>
</form>
</body>
</html>
Servlet:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.*;
/**
* Servlet implementation class TestServlet
*/
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TestServlet() {
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
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
// Actual logic goes here.
try {
String getvalue=request.getParameter("id");
PrintWriter out = response.getWriter();
out.println(getvalue);
out.println("attempting to read from table");
Class.forName("oracle.jdbc.driver.OracleDriver");
// Open a connection
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#IP:Port:ServiceName, UN, Pass);
// Execute SQL query
Statement stmt = conn.createStatement();
String sqlinsert, sqlselect;
sqlinsert = "Insert into abc(abc) values("+getvalue+")";
sqlselect="Select abc from abc";
ResultSet rs = stmt.executeQuery(sqlinsert);
ResultSet rs1 = stmt.executeQuery(sqlselect);
int id=0 ;
// Extract data from result set
while(rs1.next()){
//Retrieve by column name
id = rs1.getInt("ABC");
//Display values
out.println("ID: " + id + "<br>");
}
HttpSession session = request.getSession(false);
request.setAttribute("data", "0");
request.getRequestDispatcher("/loginform.jsp").forward(request, response);
// out.println("</body></html>");
// Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}
}
I am unable to understand where is the problem. Every time I run the code I am able to see only null in JSP.
Simply change request.getSession().getAttribute("data") to request.getAttribute("data") and it will work fine.
In your Java code you use request.setAttribute("data", "0"); ,but in you JSP page you use request.getSession().getAttribute("data") ,so you will not get the data.
you are actually storing your data in session and try to fetch it from request scope so i think you are getting null value.
in jsp remove <%= request.getSession().getAttribute("data") %> line and use this line <%= request.getAttribute("data") %>

Servlet getServletContext().getRequestDispatcher shows attributes in url line

I have built a small servlet with two jsp files and a controller.
This is the login.jsp :
<body>
<section class="loginform cf">
<form name="login" action="controller/login" method="get" onsubmit="return validateForm()"
accept-charset="utf-8">
<ul>
<li><label for="username">Username</label> <input type="text"
name="username" ></li>
<li><label for="password">Password</label> <input
type="password" name="password" ></li>
<li><input type="submit" value="Login"></li>
</ul>
</form>
<form action="http://localhost:8080/ToDoListProj" method="get">
<input title="Register" type="submit" value="Not Yet A Member?" formaction="register.jsp"/>
<br/>
</form>
</section>
</body>
and this is the controller:
package il.ac.hit.controller;
import il.ac.hit.model.HibernateToDoListDAO;
import il.ac.hit.model.Item;
import il.ac.hit.model.ToDoListPlatformException;
import il.ac.hit.model.User;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import antlr.StringUtils;
/**
* Servlet implementation class ToDoListPlatformContrller
*/
#WebServlet("/controller/*")
public class ToDoListPlatformController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ToDoListPlatformController() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
private boolean isAlphaNumeric(String word)
{
return word.matches("[a-zA-Z0-9]+");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = request.getPathInfo();
System.out.println(path);
RequestDispatcher dispatcher = null;
switch(path)
{
case "/login":
{
try {
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username != null && password != null && isAlphaNumeric(username) && isAlphaNumeric(password))
{
List<User> usersList = il.ac.hit.model.HibernateToDoListDAO.getInstance().getUsersList();
for(User user : usersList)
{
if(user.getName().equals(username) && user.getPassword().equals(password))
{
Cookie cookie = new Cookie("UserId", username);
cookie.setPath("/");
response.addCookie(cookie);
request.getSession().setAttribute("UserID", username);
request.getSession().setAttribute("table", HibernateToDoListDAO.getInstance().getItemsList(username));
dispatcher = getServletContext().getRequestDispatcher("/view.jsp");
break;
}
}
}
else
{
dispatcher = getServletContext().getRequestDispatcher("/wronglogin.jsp");
}
} catch (ToDoListPlatformException e) {
dispatcher = getServletContext().getRequestDispatcher("/wronglogin.jsp");
}
break;
}
dispatcher.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
when I enter a username and password on the login jsp page and hit submit, both attributes are being shown in the URL line.
this is what I get:
http://localhost:8080/ToDoListProj/controller/login?username=usernamesample&password=passwordasmple
How can I fix that ?
You should change method="get" to method="post".
GET method adds the data to the URL as in your case. Never use get method when deals with auth. forms.
Use Http POST instead of GET:
In the JSP
<form name="login" action="controller/login" method="post"
and in the controller:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
// read login data from request like you do now in doGet...
<form name="login" action="controller/login" method="get" , the form uses get ,so the parameters show up in the url ,use method="post". Now remember after making this doPost() will be called , so ou'll have to either copy your code in to doPost() or call doGet() from doPost()
You have to change get to post method
<form name="login" action="controller/login" method="post" onsubmit="return validateForm()"
In get the request parameters are passed to the server by appending
at the end of the url, whereas in a post request form elements or
parameters are passed as a part of HTTP body and does not append at
the end of URL. So whenever we need to send some sensitive information
to server, a post request is sent.
HttpGet is "OK", if you use https instead of http. Https will encrypt your get parameters (but the whole request url may be saved unencrypted in server logs for example, therefore HttpPost would be the method of choice).
In addition to all the answers saying you should use method=post, you could put the code from doGet in a own function, lets say login, so you can use HttpPost and HttpGet at the same time:
private RequestDispatcher login(HttpServletRequest request, HttpServletResponse response) {
String path = request.getPathInfo();
System.out.println(path);
RequestDispatcher dispatcher = null;
switch(path)
{
case "/login":
{
try {
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username != null && password != null && isAlphaNumeric(username) && isAlphaNumeric(password))
{
List<User> usersList = il.ac.hit.model.HibernateToDoListDAO.getInstance().getUsersList();
for(User user : usersList)
{
if(user.getName().equals(username) && user.getPassword().equals(password))
{
Cookie cookie = new Cookie("UserId", username);
cookie.setPath("/");
response.addCookie(cookie);
request.getSession().setAttribute("UserID", username);
request.getSession().setAttribute("table", HibernateToDoListDAO.getInstance().getItemsList(username));
dispatcher = getServletContext().getRequestDispatcher("/view.jsp");
break;
}
}
}
else
{
dispatcher = getServletContext().getRequestDispatcher("/wronglogin.jsp");
}
} catch (ToDoListPlatformException e) {
dispatcher = getServletContext().getRequestDispatcher("/wronglogin.jsp");
}
break;
}
return dispatcher;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
login(request, response).forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
login(request, response).forward(request, response);
}

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

How to pass multiple values to servlet using Jquery

I have an Html form from that i need to pass values to servlet using jquery and there it will validates the information and returns the result.But when i try to pass the data using jQuery.
The servlet showing that null value received.
<div class="ulogin">
<h2>Login</h2>
<div id="error"></div>
<form action="Login" method="post" id="spsignin">
<input type="text" name="uname" class="text validate[required]" id="name" placeholder="Username"/>
<input type="password" name="pass" class="text validate[required]" id="password" placeholder="Password"/>
<input type="submit" value="" id="memberlogin"/>
</form>
</div>
My javascript file is
$(document).ready(function() {
//Stops the submit request
$("#spsignin").submit(function(e){
e.preventDefault();
});
//checks for the button click event
$("#memberlogin").click(function(e){
//get the form data and then serialize that
dataString = $("#spsignin").serialize();
dataString1 = $("#spsignin").serialize();
var uname = $("input#name").val();
var pass = $("input#password").val();
$.ajax({
type: "POST",
url: "Login",
data:'uname=' +encodeURIComponent(uname) &'pass=' + encodeURIComponent(pass),
dataType: "json",
//if received a response from the server
success: function( data, textStatus, jqXHR) {
if(data.success)
{
$("#error").html("<div><b>success!</b></div>"+data);
}
//display error message
else {
$("#error").html("<div><b>Information is Invalid!</b></div>"+data);
}
},
//If there was no resonse from the server
error: function(jqXHR, textStatus, errorThrown){
console.log("Something really bad happened " + textStatus);
$("#error").html(jqXHR.responseText);
},
//capture the request before it was sent to server
beforeSend: function(jqXHR, settings){
//disable the button until we get the response
$('#memberlogin').attr("disabled", true);
},
complete: function(jqXHR, textStatus){
//enable the button
$('#memberlogin').attr("disabled", false);
}
});
});
});
And the servlet is
package skypark;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Login
*/
#WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
Boolean success=true;
/**
* #see HttpServlet#HttpServlet()
*/
public Login() {
super();
// TODO Auto-generated constructor stub
}
public static Connection prepareConnection()throws ClassNotFoundException,SQLException
{
String dcn="oracle.jdbc.OracleDriver";
String url="jdbc:oracle:thin:#//localhost:1521/skypark";
String usname="system";
String pass="tiger";
Class.forName(dcn);
return DriverManager.getConnection(url,usname,pass);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String uname,pass;
response.setContentType("text/html");
PrintWriter out=response.getWriter();
response.setContentType("text/html");
response.setHeader("Cache-control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Max-Age", "86400");
uname=request.getParameter("uname");
pass=request.getParameter("pass");
Boolean suc;
try {
suc = check(uname,pass);
out.println(suc);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.flush();
out.close();
}
public Boolean check(String uname,String pass) throws SQLException, ClassNotFoundException
{
ResultSet rs = null;
int i=0;
Connection con=prepareConnection();
String Query="select uname,email from passmanager where pass=?";
PreparedStatement ps=con.prepareStatement(Query);
try
{
ps.setString(1,pass);
rs=ps.executeQuery();
while(rs.next())
{
if (uname.equalsIgnoreCase(rs.getString("uname")) || uname.equalsIgnoreCase(rs.getString("email")))
{
rs.close();
ps.close();
ps = null; con.close();
con = null;
success=true;
i=1;
break;
}
}
}
catch(Exception e)
{
System.out.println(e);
}
if(i==0)
{
success=false;
}
return success;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request,response);
}
}
I think error is with jquery. please any one help me to overcome from this...
The problem is with this line:
data:'uname=' +encodeURIComponent(uname) &'pass=' + encodeURIComponent(pass)
which should be
data: 'uname='+encodeURIComponent(uname)+'&'+'pass='+encodeURIComponent(pass)
note the missing + after encodeURIComponent(uname)
I spot one little error on your Ajax script, your ampersand sign is not part of the string:
data:'uname=' + encodeURIComponent(uname) &'pass=' + encodeURIComponent(pass),
should be
data:'uname=' + encodeURIComponent(uname) + '&pass=' + encodeURIComponent(pass),
If that doesn't fix it then here's few more things you can check:
Check you only have one input element with id 'name' on your html
Check your request went to right servlet on your servlet mapping
Check you don't have any filters that intercepts and modify / redirect requests
Other than that your code seem fine
well the issue has been cleared already but other than passing the values one by one you can submit the whole form at once ,have a look at this .
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing spinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
and you form would be like this
<form id="tempForm" enctype="multipart/form-data">
<input type="text" name="" id="" />
<input type="text" name="" id="" />
<input type="file" name="" id="" />
</form>
and you can find the plug in enter link description here

Categories

Resources