A user clicks on edit on the index.jsp page and it sends them to a editCustomer.jsp page. The problem is when I click update it doesnt update the customer information on the index page.
How can I do this using the code I have?
INDEX.JSP
<%#page import="edu.witc.Assignment02.controller.CustomerServlet"%>
<%# 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>Home</title>
</head>
<body>
<ul>
<% String customerString ="";
ArrayList<edu.witc.Assignment02.model.Customer> customers = (java.util.ArrayList)request.getAttribute("customers");
for (edu.witc.Assignment02.model.Customer customer : customers) {
customerString += "<li>" + customer.getName() +
"(" + customer.getCity() + ") (" +
"<a href='editCustomer?id=" + customer.getId() +
"'>edit</a>)</li>";
}%>
<%=customerString %>
</ul>
<body>
</html>
EDITCUSTOMER.JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="edu.witc.Assignment02.controller.CustomerServlet"%>
<!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>Edit Customer</title>
</head>
<body>
<h2>Edit Customer</h2>
<% int customerId =
Integer.parseInt(request.getParameter("id"));%>
<form method='post' action='customer'>
<input type='hidden' name ='id' value='<%=customerId%>'/>
<table>
<tr><td>Name:</td><td>"
<input name='name' />
</td></tr>
<tr><td>City:</td><td>
<input name='city' />
</td></tr>
<tr>
<td colspan='2' style='text-align:right'>
<input type='submit' value='Update'/></td>
</tr>
<tr><td colspan='2'>
<a href='customer'>Customer List</a>
</td></tr>
</table>
</form></body>
</html>
SERVLET
package edu.witc.Assignment02.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.witc.Assignment02.*;
import edu.witc.Assignment02.model.Customer;
/*
* Not thread-safe. For illustration purpose only
*/
#WebServlet(name = "CustomerServlet", urlPatterns = {
"/customer", "/editCustomer", "/updateCustomer"})
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = -20L;
private List<edu.witc.Assignment02.model.Customer> customers = new ArrayList<Customer>();
#Override
public void init() throws ServletException {
Customer customer1 = new Customer();
customer1.setId(1);
customer1.setName("Donald D.");
customer1.setCity("Miami");
customers.add(customer1);
Customer customer2 = new Customer();
customer2.setId(2);
customer2.setName("Mickey M.");
customer2.setCity("Orlando");
customers.add(customer2);
}
private void sendCustomerList(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/index.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
private Customer getCustomer(int customerId) {
for (Customer customer : customers) {
if (customer.getId() == customerId) {
return customer;
}
}
return null;
}
private void sendEditCustomerForm(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String url = "/editCustomer.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uri = request.getRequestURI();
if (uri.endsWith("/customer")) {
sendCustomerList(response, request);
} else if (uri.endsWith("/editCustomer")) {
sendEditCustomerForm(request, response);
}
}
#Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, ServletException {
// update customer
int customerId = 0;
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setName(request.getParameter("name"));
customer.setCity(request.getParameter("city"));
}
sendCustomerList(response, request);
}
}
CUSTOMER.JAVA
package edu.witc.Assignment02.model;
public class Customer {
private int id;
private String name;
private String city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
I'm not sure what you expect to happen. You are submitting this form
<form method='get' action='customer'>
<table>
<tr>
<td>Name:</td>
<td>
"
<input name='name' />
</td>
</tr>
<tr>
<td>City:</td>
<td>
<input name='city' />
</td>
</tr>
<tr>
<td colspan='2' style='text-align:right'>
<input type='submit' value='Update' />
</td>
</tr>
<tr>
<td colspan='2'>
<a href='customer'>Customer List</a>
</td>
</tr>
</table>
</form>
And handling it with
if (uri.endsWith("/customer")) {
sendCustomerList(response, request);
and
private void sendCustomerList(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/index.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
Nothing in the code above modifies anything in the customers List. Objects don't get changed on their own. You have to make the modifications yourself.
Maybe you meant to submit the form with a POST request. In that case, you would need an <input> field for the id.
Think about the request-response cycle.
Your Servlet container receives an HTTP request, it dispatches your Servlet to handle it. Your servlet performs some logic and forwards to a JSP. The JSP renders some HTML which is written to the body of the HTTP response. The response is sent to the client. In this case, your client is a browser which reads the HTML text and renders it graphically. You can then interact with it, fill in input fields and click buttons. When you do this, the browser takes the values you've entered and produces an HTTP request which it sends to your server. And so on, and so on...
Related
I've an InitializeServlet that creates and instantiates a HttpSession then redirects to a JSP (betFinalize.jsp). Here I can work on my session. When from that JSP I redirect (through a form) to another Servlet, FinalizeServlet I loose my session. I cannot figure out why. Following code.
InitializeServlet.java
public class InitializeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fName = request.getParameter("fName");
String lName = request.getParameter("lName");
String result = request.getParameter("result");
Bet s = new Bet();
s.setFirstLastName(fName + " " + lName);
s.setResult(result);
s.setMultiplier(calculateMultiplier());
request.getSession(true).setAttribute("bet", s);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/betFinalize.jsp");
rd.forward(request, response);
}
private double calculateMultiplier() {
return 0.8;
}
}
betFinalized.jsp
<%# page import="it.unibo.tw.model.beans.Bet"%>
<%# page import="it.unibo.tw.model.beans.Bets"%>
<%# page session="true"%>
<jsp:useBean id="bet" class="it.unibo.tw.model.beans.Bet" scope="session"></jsp:useBean>
<jsp:useBean id="finalizedBets" class="it.unibo.tw.model.beans.Bets" scope="application"></jsp:useBean>
<!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">
</head>
<body>
<h1>Hi, <%= bet.getFirstLastName() %></h1>
<h2>Current bet: <i><%= bet.toString() %></i></h2>
<form action="finalize" method="get">
<input id="import" type="number" name="import" onkeyup="calculateWin()" ><br />
<input id="win" type="text" name="win" readonly ><br />
<input type="submit">
</form>
<hr />
<ul>
<% for(Bet s : finalizedBets.getList()) { %>
<li><%= s.toString() %></li>
<% } %>
</ul>
</body>
<script>
function calculateWin() {
var multiplier = <%= bet.getMultiplier() %>
var imp = document.getElementById("import").value
document.getElementById("win").value = imp * multiplier
}
</script>
</html>
FinalizeServlet.java
public class FinalizeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
double vincita = Double.parseDouble(request.getParameter("win"));
Bet s = (Bet) request.getSession().getAttribute("bet");
if(s != null) {
// NEVER REACH HERE
s.setWin(vincita);
s.setFinalized(true);
Bets scommesseFinalized = (Bets) getServletContext().getAttribute("scommesseFinalized");
scommesseFinalized.getList().add(s);
}
request.getSession().invalidate();
RequestDispatcher rd = getServletContext().getRequestDispatcher("/start.html");
rd.forward(request, response);
}
}
You're trying to get the wrong attribute. When you set the session variable you have:
request.getSession(true).setAttribute("scommessa", s);
When you try to read it:
request.getSession().getAttribute("bet");
it should be:
request.getSession().getAttribute("scommessa");
instead.
Encode the session id in the action of the form as below:
<form action="<%=response.encodeURL("finalize")%>" method="get">
I was trying to get the values (List productList = data.getProductList();) in ShowProductCatalog.jsp from the JavaBean ProductDataBean.java. I'm getting the error nullpointerexception. Please help! Your help will be much appreciated.
*edited: I realised the connection I'm getting in ProductDataBean.java in getProductList() is null. Now the question is, how can I make the changes to insert the value? If I put the whole connection in getProductList(), there is error message. "No Suitable Driver found."
**ShowProductCatalog.jsp**
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import = "java.util.*" import="cart.*,java.net.*,java.text.*"%>
<jsp:useBean id="data" scope="session" class="cart.ProductDataBean" />
<!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">
</head>
<body>
<%
List productList = data.getProductList();
Iterator prodListIterator = productList.iterator();
%>
**ProductDataBean.java**
package cart;
import java.io.*;
import java.sql.*;
import java.util.*;
public class ProductDataBean implements Serializable{
private static Connection connection;
private PreparedStatement addRecord, getRecords;
public ProductDataBean(){
try{
// Step1: Load JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
// Step 2: Define Connection URL
String connURL ="jdbc:mysql://localhost/onlineshop?user=root&password=teck1577130713";
// Step 3: Establish connection to URL
connection = DriverManager.getConnection(connURL);
}catch(Exception e){e.printStackTrace();}
}
public static Connection getConnection(){
return connection;
}
public ArrayList getProductList() throws SQLException{
ArrayList productList = new ArrayList();
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM products");
while (results.next()){
DVD movie = new DVD();
movie.setMovie(results.getString("movieName"));
movie.setRating(results.getString("movieRate"));
movie.setYear(results.getString("movieYear"));
movie.setPrice(results.getDouble("moviePrice"));
productList.add(movie);
}
return productList;
}
}
Check your build path mySql driver is added. and please add exception to the question what you getting, then easily can answer.
mysql-connector-java-5.1.24-bin.jar
you can get it from here
have a look this SO How to avoid java code in jsp
I suggest you to use Servlets instead of writing java code in jsp.
If you write code in servlets then easily you can test/debug your code.
To answer: how can I make the changes to insert the value?
Create a PreparedStatement obj with sql insert query and call [executeUpdate()][3] to perform INSERT, UPDATE or DELETE operations.
Add this piece of code in your ProductDataBean class to add a new record to table.
public static void addRecord(DVD dvd) throws SQLException{
PreparedStatement pStatement =
getConnection().prepareStatement("insert into products(movieName, movieRate, movieYear, moviePrice) values(?,?,?,?)");
pStatement.setString(1, dvd.getMovie());
pStatement.setString(2, dvd.getRating());
pStatement.setString(3, dvd.getYear());
pStatement.setDouble(4, dvd.getPrice());
pStatement.executeUpdate();
}
Make your DVD class a POJO like
package cart;
public class DVD {
private String movie;
private String rating;
private String year;
private Double price;
public DVD(){}
public DVD(String movie, String rating, String year, Double price) {
this.movie = movie;
this.rating = rating;
this.year = year;
this.price = price;
}
public String getMovie() {
return movie;
}
public void setMovie(String movie) {
this.movie = movie;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
#Override
public String toString() {
return "DVD [movie=" + movie + ", rating=" + rating + ", year=" + year
+ ", price=" + price + "]";
}
}
And in your jsp page call servlet url pattern to perform GET and POST, and to render all products in jsp user standard tag lib jstl1.2.jar you get it from here
So replace your jsp file with:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html 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">
</head>
<body>
<c:url value="/Product" var="pdctServletUrl"/>
Product Page
<form method="post" action="${pdctServletUrl}">
<h4>Enter New Movie details:</h4>
<label>Name</label>
<input type="text" name="movie"/>
<label>Rating</label>
<input type="text" name="rating"/>
<label>Year</label>
<input type="text" name="year"/>
<label>Price</label>
<input type="text" name="price"/>
<input type="submit" value="save movie"/>
</form>
<br/>
To get a list of products click
Get Products
<c:if test="${not empty products}">
<h4>Available Products.</h4>
<table>
<tr>
<th>Movie Name</th>
<th>Rating</th>
<th>Year</th>
<th>Price</th>
</tr>
<c:forEach items="${products}" var="pd">
<tr>
<td>${pd.movie}</td>
<td>${pd.rating}</td>
<td>${pd.year}</td>
<td>${pd.price}</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
A servlet to handle GET and POST request's and transfering data to client etc.
Product.java
package cart;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
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 Product
*/
#WebServlet("/Product")
public class Product extends HttpServlet {
private static final long serialVersionUID = 1L;
private ProductDataBean pDataBean = new ProductDataBean();
public Product() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products;
try {
products = pDataBean.getProductList(); // Obtain all products.
request.setAttribute("products", products); // Store products in request scope.
request.getRequestDispatcher("/test.jsp").forward(request, response); // Forward to JSP page to display them in a HTML table.
} catch (SQLException e) {
e.printStackTrace();
}
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String movie = req.getParameter("movie");
String rating = req.getParameter("rating");
String year = req.getParameter("year");
Double price = Double.valueOf(req.getParameter("price"));
if(movie!=null && rating!=null && year!=null && price!=null)
try {
ProductDataBean.addRecord(new DVD(movie, rating, year, price));
} catch (SQLException e) {
e.printStackTrace();
}
doGet(req, resp);
}
}
I think this may help you to understand.
Your JSP page is working properly and there is no mistake. Check your database and confirm that you have rows inside the products table. Null pointer exception occurs because the method getProductList() is not returning an ArrayList.
I am till a learner in Java, please help me out. Here is my sample code, when I execute this program. It should retrieve info from the data base and store the values in the Java class and there by send the value to JSP but when i look at JSP it shows value "null"
Here are the 5 files related to my problem, any answers or solutions are happily accepted.
-------------------------this my basic input form---------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>WELCOME TO DISCOUNTLOVERS.IN</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<link href="stylesheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<div><%#include file="header.jsp" %></div>
<div><table width="920" border="0" cellpadding="0" cellspacing="0" id="main-content" >
<form method ="post" action ="Registrationform" >
<tbody>
<tr>
<td width="382" valign="top" class="formtext">
<div>First Name</div>
<div>Last name</div>
<div>E-mail</div>
<div>Password</div>
<div>Confirm Password</div>
<div>phone no</div>
<div>Address</div>
<div>City</div>
<div>State</div>
<div>country</div>
<div>post code</div>
</td>
<td width="52" class="formtext-gap">
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
</td>
<td width="486" valign="top">
<div><input type="text" name="username_first"/></div>
<div><input type="text" name="username_last"/></div>
<div><input type="text" name="username_email"/></div>
<div><input type="text" name="username_pw"/></div>
<div><input type="text" name="username_cpw"/></div>
<div><input type="text" name="username_tele"/></div>
<div><input type="text" name="username_add"/></div>
<div><input type="text" name="username_city"/></div>
<div><input type="text" name="username_state"/></div>
<div><input type="text" name="username_country"/></div>
<div><input type="text" name="username_postcode"/></div>
</td>
</tr>
<tr><td colspan="3" align="center"><input type="checkbox"/> Terms and conditions of Discountlovers.in accpeted</td></tr>
<tr><td colspan="3" align="center"><div><input type="submit" value="Submit" class=""/></div></td></tr>
</tbody></form></table></div>
<div><%#include file="footer.jsp" %></div>
</div>
</body>
</html>
------------------------ this is data insertion servlet------------------------
package registration_Servlets;
import registration_Servlets.intialization_form;
import java.io.IOException;
import java.io.PrintWriter;
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;
/**
* Servlet implementation class Registrationform
*/
#WebServlet("/Registrationform")
public class Registrationform extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Registrationform() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
intialization_form obj = new intialization_form();
String name;
String lastname;
String username_email;
String username_pw ;
String username_cpw;
String id ;
String username_add;
String username_city ;
String username_state;
String username_country;
String username_postcode;
try {
name = request.getParameter("username_first");
lastname = request.getParameter("username_last");
username_email = request.getParameter("username_email");
username_pw = request.getParameter("username_pw");
username_cpw = request.getParameter("username_cpw");
id = request.getParameter("username_tele");
username_add = request.getParameter("username_add");
username_city = request.getParameter("username_city");
username_state = request.getParameter("username_state");
username_country = request.getParameter("username_country");
username_postcode = request.getParameter("username_postcode");
DataBase db = new DataBase();
PreparedStatement pst = db.getConnection().prepareStatement("insert into registrationinfo values(?,?,?,?,?,?,?,?,?,?,?)");
pst.setString(1, name );
pst.setString(2, lastname);
pst.setString(3, username_email);
pst.setString(4, username_pw);
pst.setString(5, username_cpw);
pst.setString(6, id);
pst.setString(7, username_add);
pst.setString(8, username_city);
pst.setString(9, username_state);
pst.setString(10, username_country);
pst.setString(11, username_postcode);
int i = pst.executeUpdate();
if(i==1){
//request.setAttribute("name",name);
/*String site = new String("Retrivin_user_reg_form");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site); */
response.sendRedirect("Retrivin_user_reg_form");
}
pw.println("done");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
--------------------------------this is my data retrieve servlet-----------------
package registration_Servlets;
import java.io.IOException;
import java.io.PrintWriter;
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;
/**
* Servlet implementation class Retrivin_user_reg_form
*/
#WebServlet("/Retrivin_user_reg_form")
public class Retrivin_user_reg_form extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Retrivin_user_reg_form() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
try {
DataBase db = new DataBase();
PreparedStatement pst = db.getConnection().prepareStatement("Select * from registrationinfo");
intialization_form obj = new intialization_form();
ResultSet i = pst.executeQuery();
while(i.next()){
// pw.println("EmpName" + " " + "EmpSalary" + "<br>");
obj.name= i.getString(1);
obj.lastname=i.getString(2);
obj.username_email=i.getString(3);
obj.username_pw=i.getString(4);
obj.username_cpw=i.getString(5);
obj.id=i.getString(6);
obj.username_add=i.getString(7);
obj.username_city=i.getString(8);
obj.username_state=i.getString(9);
obj.username_country=i.getString(10);
obj.username_postcode=i.getString(11);
String site = new String("registrationcompleted.jsp");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
/*request.getRequestDispatcher("registrationcompleted.jsp").forward(request, response);*/
}
}
catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
}
}
-----------this is my Java class where i want to store my retrieved data--------------
package registration_Servlets;
public class intialization_form
{
String name;
String lastname;
String username_email;
String username_pw;
String username_cpw;
String id;
String username_add;
String username_city;
String username_state;
String username_country;
String username_postcode;
public void setname( String value )
{
name = value;
}
public String getname() { return name; }
public void setlastname( String value )
{
lastname = value;
}
public String getlastname() { return lastname; }
public void setusername_email( String value )
{
username_email = value;
}
public String getusername_email() { return username_email; }
public void setusername_pw(String value){
username_pw= value;
}
public String getusername_pw() { return username_pw; }
public void setusername_cpw(String value){
username_cpw=value;
}
public String getusername_cpw(){
return username_cpw;
}
public void setid(String value){
id= value;
}
public String getid(){
return id;
}
public void setusername_add(String value){
username_add= value;
}
public String getusername_add(){
return username_add;
}
public void setusername_city(String value){
username_city= value;
}
public String getusername_city(){
return username_city;
}
public void setusername_state(String value){
username_state= value;
}
public String getusername_state(){
return username_state;
}
public void setusername_country(String value){
username_country = value;
}
public String getusername_country(){
return username_country;
}
public void setusername_postcode(String value){
username_postcode= value;
}
public String getusername_postcode(){
return username_postcode;
}
}
-------------------------this is my out put JSP where I get null value-------------
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import = "registration_Servlets.intialization_form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>WELCOME TO DISCOUNTLOVERS.IN</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<link href="stylesheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<div><%#include file="header.jsp" %></div>
<div><table width="920" border="0" cellpadding="0" cellspacing="0" id="main-content">
<tbody>
<tr>
<td>
<% intialization_form user = new intialization_form(); %>
first Name: <%= user.getname() %>
last name: <%= user.getlastname() %><BR>
Email: <%= user.getusername_email() %><BR>
</td>
</tr>
</tbody></table></div>
<div><%#include file="footer.jsp" %></div>
</div>
</body>
</html>
I can see you have used
request.getRequestDispatcher("registrationcompleted.jsp").forward(request, response);
before doing this add line given below before forward() method
request.setAttribute("your-key", yourObjectReference);
This method of request object will set your form object as an attribute which you want to access in your output jsp, which you can retrieve using request.getAttribute("key") method.
put below code in your output jsp.
<% intialization_form user = (intialization_form)request.getAttribute("your-key"); %>
since request.getAttribute() method returns Object you will have to cast it in intialization_form
And don't forget to remove below lines from your code before doing this
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
It is because the values in you form class are NULL. You never assign any values to them.
You just create an empty form object and the "print" some of its values.
<% intialization_form user = new intialization_form(); %>
first Name: <%= user.getname() %>
last name: <%= user.getlastname() %><BR>
Email: <%= user.getusername_email() %><BR>
#See https://stackoverflow.com/tags/servlets/info for some info how to start jsp and servlet programming.
I am a starter in java.
I am trying to develop a web application to validate user name and password in mysql database.
When i run the program i am getting exception. can anyone help me to find out what is wrong in the below code.
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>
<form method="post" action="database">
<body>
<h1>Enter user details</h1>
<h2>Name</h2>
<input type="text" name="t1" /><br>
<h2>Password</h2>
<input type="password" name="p1" /><br><br>
<input type="submit" value="Submit" name="b1">
</body>
</form>
</html>
c1.java
********
package model;
public class c1 {
String name,password;
public c1(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
database.java
*************
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class database extends HttpServlet {
#Resource(name = "db1")
private DataSource db1;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String name=request.getParameter("t1").trim();
String password=request.getParameter("p1").trim();
int value=select(name,password);
if(value==1)
{
out.println("User details present in database");
}
else
{
out.println(value);
out.println("ERROR Invalid user");
}
}
catch(Exception e2)
{
out.println("error");
}
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";``
}// </editor-fold>
public int select(String UserName,String Password) throws SQLException
{
DataSource d= db1;
Connection c=d.getConnection();
PreparedStatement p=c.prepareStatement
("select * from Employee where name='"+UserName+"' and password='"+Password+"'");
ResultSet rs=p.executeQuery();
int a= rs.getRow();
return a;
}
}
You have several errors in your code:
JSP. Incorrect position of body tags:
Correct code:
<%#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 method="post" action="database">>
<h1>Enter user details</h1>
<h2>Name</h2>
<input type="text" name="t1" />
<br>
<h2>Password</h2>
<input type="password" name="p1" />
<br>
<br>
<input type="submit" value="Submit" name="b1">
</form>
</body>
</html>
JAVA. You have a couple of errors in your controller. Some ` characters producing errors.
Correct code:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
processRequest(request, response); // ERROR Removed last `
}
#Override
public String getServletInfo() {
return "Short description"; // ERROR removed lasts ``
}// </editor-fold>
WEB.XML: Check your web.xml and verify that you have the next lines:
<servlet>
<servlet-name>Database-servlet</servlet-name>
<servlet-class>controller.database</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Database-servlet</servlet-name>
<url-pattern>/database</url-pattern>
</servlet-mapping>
Hello i'm trying to create a page to update a row in my database table i'm using DAO/Servlet with JSP page
DAO code:
public static AnimalUpdateBean updateAnimal(AnimalUpdateBean bean) {
//preparing some objects for connection
PreparedStatement up = null;
Statement stmt = null;
String id = bean.getAnimalId();
String aname = bean.getAnimalName();
String dob = bean.getAnimalDob();
String gender = bean.getAnimalGender();
String breedid = bean.getAnimalBreed();
String remark = bean.getAnimalRemark();
try
{
//connect to DB
currentCon = dbConnection.getConnection();
up = currentCon.prepareStatement("update animal set aname = '"+aname+"' , gender = '"+gender+"', specie_id = '"
+breedid+"' , remark = '"+remark+"' where animal_id = '"+id+"'");
up.executeUpdate();
if (up.executeUpdate()>=1){
stmt=currentCon.createStatement();
rs = stmt.executeQuery("select aname , dob, gender, specie_id , remark from animal where animal_id = '"+id+"'");
}
System.out.println("done");
}
catch (Exception ex)
{
System.out.println("Log In failed: An Exception has occurred! " + ex);
}
//some exception handling
finally
{
if (rs != null) {try {rs.close();} catch (Exception e) {} rs = null;}
if (stmt != null) {try {stmt.close();} catch (Exception e) {}stmt = null;}
if (currentCon != null) {try {currentCon.close();} catch (Exception e) {}currentCon = null;}
}
return bean;
}
}
UpdateAnimal.jsp code:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page import="java.util.ArrayList" %>
<%#page import="content.*"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%# page session="true"%>
<%#page import="java.io.*"%>
<%#page import="java.net.*"%>
<%#page import="javax.servlet.*"%>
<%# page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256" %>
<!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=windows-1256">
<title>Update Animal</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Zoo keeper</th></tr>
</table>
<h1>Update Animal</h1>
<form action="Relay" >
<fieldset>
Animal new name: <input type= "text" name = "aname"><br>
Animal new DOB: <input type= "text" name = "dob"><br>
<br>
Animal new gender:
<select name="gender" id="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
Animal new Breed: <input type= "text" name = "breedid" ><br>
Animal new remarks: <textarea name = "remark" rows="4" cols="20">
</textarea> <br /> <br/>
<input type="submit" value="submit">
<input type="hidden" name="animal_id" value="<%= request.getParameter("animal_id") %>">
<input type="hidden" name="command" value="UpdateAnimalServlet" >
</fieldset>
</form>
</body></html>
the record being updated come from a select page to view the records when the user click on the name he will be redirected to update page CheckAnimal.jsp
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page import="java.util.ArrayList" %>
<%#page import="content.*"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%# page session="true"%>
<%#page import="java.io.*"%>
<%#page import="java.net.*"%>
<%#page import="javax.servlet.*"%>
<%# page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256" %>
<!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=windows-1256">
<title>Animal list</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Zoo keeper</th></tr>
</table>
<h1>Animal list</h1>
Click on animal name to update it!
<center>
<table width="100 % " id='table1' border="1" cellspacing="2" cellpadding="2">
<tr class="tab-highlighted-2">
<td class="tab-highlighted-2" width="15">
<div align="left">Name</div>
</td>
<td class="tab-highlighted-2" width="13">
<div align="left">Age</div>
</td>
<td class="tab-highlighted-2" width="13">
<div align="left">Gender</div>
</td>
<td class="tab-highlighted-2" width="13">
<div align="left">Status</div>
</td>
<td class="tab-highlighted-2" width="13">
<div align="left">Breed</div>
</td>
<td class="tab-highlighted-2" width="13">
<div align="left">Pen #</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">Zoo</div>
</td>
<td class="tab-highlighted-2" width="20">
<div align="left">Remarks</div>
</td>
</tr>
<c:forEach items="${beans}" var="view">
<tr>
<td>${view.animalName}</td>
<td>${view.animalDob}</td>
<td>${view.animalGender}</td>
<td>${view.animalSource}</td>
<td>${view.animalBreed}</td>
<td>${view.sectionId}</td>
<td>${view.zooId}</td>
<td>${view.animalRemark}</td>
</tr>
</c:forEach>
</table>
</center>
</body></html>
AnimalUpdateBean.java code:
package content;
public class AnimalUpdateBean {
private String animalId;
private String animalName;
private String animalDob;
private String animalGender;
private String animalBreed;
private String animalRemark;
public String getAnimalId() {return animalId;}
public String getAnimalName() {return animalName;}
public String getAnimalDob() {return animalDob;}
public String getAnimalGender() {return animalGender;}
public String getAnimalBreed() {return animalBreed;}
public String getAnimalRemark() {return animalRemark;}
public void setAnimalId(String animalId) {this.animalId = animalId;}
public void setAnimalName(String animalName) {this.animalName = animalName;}
public void setAnimalDob(String animalDob) {this.animalDob = animalDob;}
public void setAnimalGender(String animalGender) {this.animalGender = animalGender;}
public void setAnimalBreed(String animalBreed) {this.animalBreed = animalBreed;}
public void setAnimalRemark(String animalRemark) {this.animalRemark = animalRemark;}
}
the servlet responsible to start the update is UpdateAnimalServlet:
package content;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LoginServlet
*/
public class UpdateAnimalServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try
{
AnimalUpdateBean animal = new AnimalUpdateBean();
animal.setAnimalId(request.getParameter("animal_id"));
animal.setAnimalName(request.getParameter("aname"));
// animal.setAnimalDob(request.getParameter("dob"));
animal.setAnimalGender(request.getParameter("gender"));
animal.setAnimalBreed(request.getParameter("breedid"));
animal.setAnimalRemark(request.getParameter("remark"));
String test = request.getParameter("animal_id");
System.out.println(test);
System.out.println(animal);
animal = DAO.updateAnimal(animal);
response.sendRedirect("/oosd/member.jsp");
}
catch (Throwable theException)
{
System.out.println(theException);
}
}
}
I'm using a Relay servlet that calls AnimalUpdateServlet for execution:
package content;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
public class Relay extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try
{
String command = request.getParameter("command");
if (command.equals("LoginServlet")){
RequestDispatcher rd =request.getRequestDispatcher("/"+command);
rd.forward(request, response);
//for testing
System.out.println("Request forwarded to " + command + " servlet");
} else if (command.equals("UpdateAnimalServlet")){
RequestDispatcher rd =request.getRequestDispatcher("/"+command);
rd.forward(request, response);
//for testing
System.out.println("Request forwarded to " + command + " servlet");
}
else
System.out.println("=> command='" + command + "'");
String url = "/oosd/" + command;
String encodedUrl = response.encodeRedirectURL(url);
System.out.println(" url=" + url);
System.out.println(" encodedUrl=" + encodedUrl);
response.sendRedirect(encodedUrl);
}
catch (Throwable theException)
{
System.out.println(theException);
}
}
}
and last thing is the web.xml page:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>content.LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>UpdateAnimalServlet</servlet-name>
<servlet-class>content.UpdateAnimalServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>SelectAnimalServlet</servlet-name>
<servlet-class>content.SelectAnimalServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>Relay</servlet-name>
<servlet-class>content.Relay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SelectAnimalServlet</servlet-name>
<url-pattern>/SelectAnimalServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UpdateAnimalServlet</servlet-name>
<url-pattern>/UpdateAnimalServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Relay</servlet-name>
<url-pattern>/Relay</url-pattern>
</servlet-mapping>
</web-app>
I keep getting these errors:
Log In failed: An Exception has occurred! java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
I have checked the data entry and all correct name text, gender text, specie_id number, remark text i even put the dob on hold until this work i'm using access database and here is the connection code:
package content;
import java.sql.*;
public class dbConnection {
static Connection con;
static String url;
public static Connection getConnection()
{
try
{
String url = "jdbc:odbc:oosd";
// assuming "DataSource" is your DataSource name
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
try
{
con = DriverManager.getConnection(url,"","");
// assuming your SQL Server's username is "username"
// and password is "password"
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
catch(ClassNotFoundException e)
{
System.out.println(e);
}
return con;
}
}
Any idea where is my mistake here ?
as specie_id is a number and that's what the thrown exception is stating "Data type mismatch in criteria expression." and because of this exception sendRedirect error is occuring as because of the SQLException data has been already written to the response.
your query should be something like
"update animal set aname = '"+aname+"' , gender = '"+gender+"', specie_id = "
+Integer.parseInt(breedid)+" , remark = '"+remark+"' where animal_id = '"+id+"'"
same would be required if animal_id is also a number.
The sendRedirect error happens when you've already written data to the response (like with a forward, or to the JSP writer directly) then try to redirect.
The SQL error is likely due to you using a string IDs in the SQL (surrounded by single-quotes) whereas the IDs in the DB are most likely defined as an integer.
Also, after you update the animal, you perform a query, but do nothing with the results.