I need help in forwarding the result set values from servlet to jsp without using JSTL implementation
Work flow :
The user enters a value in text box and clicks search button
On clicking search the servlet is called.
The servlet focuses on the database implementation and forward the result set values to the same jsp page from where the request comes.
Issue:
My result set size is 3, but the value which is in the top of my table alone is getting printed in my jsp page. The remaining 2 values are missing.I want all the values to be printed in my jsp page.
This is my code:
Productlist.jsp
<%#page import="java.util.List"%>
<%#page import="web.Products"%>
<%#page import="java.util.ArrayList"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Products</title>
</head>
<body>
<form method="post" align="center" action="ProductList">
Company Name:<input type="text" size="20" id="company" name="company" />
<input type="submit" value="search"/>
<%
List<Products> pdts = (List<Products>) request.getAttribute("list");
if(pdts!=null){
for(Products prod: pdts){
out.println("<br/>" + prod.getProductname());
}
}
%>
</form>
</body>
</html>
Products.java
public class Products {
private String productname;
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname=productname ;
}
}
ProductList.java(servlet-code)
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 java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
public class ProductList extends HttpServlet {
static final String dbURL = "jdbc:mysql://localhost:3306/pdt";
static final String dbUser = "root";
static final String dbPass = "root";
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ResultSet rs = null;
Connection connection = null;
List<Products> pdt = new ArrayList<Products>();
try{
String company =request.getParameter("company");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection (dbURL,dbUser,dbPass);
String sql="select product_pck from comp_pdt_list where company_name='"+company+"'";
PreparedStatement prep = connection.prepareStatement(sql);
rs=prep.executeQuery();
while(rs.next()) {
Products prod=new Products();
prod.setProductname(rs.getString("product_pck"));
pdt.add(prod);
request.setAttribute("list",pdt);
RequestDispatcher rd=request.getRequestDispatcher("Productlist.jsp");
rd.forward(request,response);
return;
}
prep.close();
} catch(Exception E) {
//Any Exceptions will be caught here
System.out.println("The error is"+E.getMessage());
} finally {
try {
connection.close();
} catch (Exception ex) {
System.out.println("The error is" + ex.getMessage());
}
}
}
}
You set the attribute to request in your while loop. So the "list" contains only one product. (method returns on first iteration)
Add products to the list in while loop and set your list (request attribute) only after while loop.
Following should fix it:
while(rs.next()){
Products prod=new Products();
prod.setProductname(rs.getString("product_pck"));
pdt.add(prod);
}
request.setAttribute("list",pdt);
RequestDispatcher rd=request.getRequestDispatcher("Productlist.jsp");
rd.forward(request,response);
Related
This question already has an answer here:
Submitting form to Servlet which interacts with database results in blank page
(1 answer)
Closed 2 years ago.
I am new to servlets. I have a class MenuServlet from where I call getMenu function of StoreController class. In this StoreController class I connected database and executed query.
Hereby i attached two classes functions where it may be wrong. I checked the connection also. when i consoled there is no problem i can get the list of items. But i am getting null pointer exception.
Servlet.service() for servlet [jsp] threw exception
java.lang.NullPointerException
at org.apache.jsp.menu_jsp._jspService(menu_jsp.java:102)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:742)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:484)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:409)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:337)
at milkshake.servlets.MenuServlet.doGet(MenuServlet.java:63)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
//this is doget function of menuservlet
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("menuservlet");
StoreController sc = new StoreController();
try {
request.setAttribute("menu1", sc.getMenu());
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
RequestDispatcher dispatcher = request.getRequestDispatcher("menu.jsp");
dispatcher.forward(request, response);
}
public class StoreController {
static List<Milkshake> menuboard = new ArrayList<Milkshake>();
public List<Milkshake> getMenu() throws SQLException,
ClassNotFoundException {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String username = "sa";
String password = "123456abcd";
String url = "jdbc:sqlserver://localhost;databaseName=Milkshake";
Connection con;
con = DriverManager.getConnection(url, username, password);
String sql = "select * from dbo.Milkshake";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
menuboard.add(new Milkshake(rs.getInt(1),rs.getString(2), rs.getDouble(3)));
}
rs.close();
stmt.close();
con.close();
return menuboard;
}
}
<!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>
<h2>Menu</h2>
<h2>items:</h2>
<%List<Milkshake> list=(List<Milkshake>)request.getAttribute("menu1"); %>
<%for (Milkshake m:list){ %>
<%=m.getMilkshakeid()%>
<%=m.getName() %>
<%=m.getPrice() %>
<%} %>
<form action="AddServlet">
<button>addorder</button>
</form>
</body>
</html>
Thank you for your responses. The reasons for null pointer exception while retrieving from the database are
Mysql jar is not added to class path.
Connection object is not properly initialised so the con object itself is null
register and load driver class only once
Null check the objects if you are not sure
Probably your server is failing to load the JDBC driver class. In order to confirm it, I would debug the servlet code or at least put System.out.println(sc.getMenu()) before request.setAttribute("menu1", sc.getMenu()).
Apart from this, I can see multiple issues with your code:
In the JSP, the import statement is missing.
It seems you have defined the servlet-mapping in web.xml. However, I recommend you use #WebServlet annotation which is much simpler to use and removes the need for an additional file (web.xml).
You should not declare menuboard as static in StoreController. This way, you are making it a class variable which means the value of menuboard will be same for all instances of StoreController. If this variable is to be used by just getMenu() I recommend you make it local to getMenu().
If you are closing Connection, you do not need to close Resultset and Statement explicitly. They will be automatically closed when the Connection is closed.
Given below is an mvce using MySQL database:
Milkshake.java:
package beans;
public class Milkshake {
private int milkshakeid;
private String name;
private double price;
public Milkshake(int milkshakeid, String name, double price) {
this.milkshakeid = milkshakeid;
this.name = name;
this.price = price;
}
public int getMilkshakeid() {
return milkshakeid;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
StoreController.java:
package milkshake.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import beans.Milkshake;
public class StoreController {
public List<Milkshake> getMenu() throws SQLException, ClassNotFoundException {
List<Milkshake> menuboard = new ArrayList<>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbase", "root", "Hello#123");
String sql = "select * from Milkshake";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
menuboard.add(new Milkshake(rs.getInt(1), rs.getString(2), rs.getDouble(3)));
}
con.close();
return menuboard;
}
}
AddServlet.java:
package servlets;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import milkshake.db.StoreController;
#WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StoreController sc = new StoreController();
try {
request.setAttribute("menu1", sc.getMenu());
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
RequestDispatcher dispatcher = request.getRequestDispatcher("menu.jsp");
dispatcher.forward(request, response);
}
}
menu.jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#page import="java.util.List,beans.Milkshake"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Menu</h2>
<h2>items:</h2>
<%
List<Milkshake> list = (List<Milkshake>) request.getAttribute("menu1");
%>
<%
for (Milkshake m : list) {
%>
<%=m.getMilkshakeid()%>
<%=m.getName()%>
<%=m.getPrice()%>
<br>
<%
}
%>
</body>
</html>
Output:
I'm trying to implement a search feature to my web application that allows a user to search a database of products. I've attempted to do this using the following:
The .jsp file for the web page which starts by listing all products (productSearch.jsp):
<%#page import="java.sql.Connection"%>
<%#page import="databaseManagement.DBConnection"%>
<%#page import="java.sql.ResultSet" %>
<%#page import="java.sql.SQLException"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.PreparedStatement"%>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1" />
<title>Search Our Products</title>
</head>
<body>
<form method="post">
Search:<input type="text" name="Search">
<input type="submit" value="Go">
<table border="2">
<tr>
<td>ID</td>
<td>NAME</td>
<td>DESCRIPTION</td>
<td>PRICE</td>
</tr>
<%
try
{
DBConnection db = new DBConnection();
Connection con = db.getConnection();
PreparedStatement ps = con.prepareStatement("select * from products");
ResultSet rs = ps.executeQuery();
while(rs.next())
{
%>
<tr>
<td><%=rs.getInt("ID") %></td>
<td><%=rs.getString("NAME") %></td>
<td><%=rs.getString("DESCRIPTION") %></td>
<td><%=rs.getString("PRICE") %></td>
</tr>
<%
}
%>
</table>
<%
rs.close();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</form>
</body>
</html>
The class to take the user's input and run the query (ProductSearch.java):
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.PrintWriter;
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 databaseManagement.DBConnection;
#WebServlet("/ProductSearch")
public class ProductSearch extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProductSearch() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String searchTerm = request.getParameter("Search");
try {
DBConnection db = new DBConnection();
Connection con = db.getConnection();
PreparedStatement ps = con.prepareStatement("select * from products where name like %?%");
ps.setString(1, searchTerm);
ResultSet rs = ps.executeQuery();
return;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And lastly a class to handle the connection to the database (DBConnection):
package databaseManagement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
// TODO: finish
//CHANGE USERNAME AND PASSWORD WHEN IMPLIMENTING ON VM
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/applicationdata", "root", "safepassword");
return con;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
}
The issue I'm now having is that I'm not sure how to take the results I got from the ProductSearch class and display them back in the productSearch.jsp page.
I'm quite new to this, so I apologise if I've made any glaring mistakes. Any help is greatly appreciated :)
Firstly , create a class where all values which you want return back is declared and also getter/setter of that variable .
i.e Suppose variable user.
import java.util.*;
public class Abc{
private String user;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public Abc(String user) {
this.user = user;
}
}
Next , In your ProductSearch.java file put this code :
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String searchTerm = request.getParameter("Search");
ArrayList<Abc> ab= new ArrayList();
try
{
String sql1 ="select * from products where name like %?%";
PreparedStatement ps = conn.prepareStatement(sql1);
ps.setString(1,searchTerm);
resultSet = ps.executeQuery();
while(resultSet.next())
{
Abc b=new Abc();
b.setUser(resultSet.getString("user"));
ab.add(b);
}
request.setAttribute("r1", ab);
request.getRequestDispatcher("productSearch.jsp").forward(request, response);
}
catch(Exception s2)
{
s2.printStackTrace();
}
}
}
Lastly print result back in your productSearch.jsp page using jstl
<!-- this is use because we use jstl tag-->
<%#taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<table align="center" border="1">
<tr bgcolor="#d9ac26">
<td><b>search</b></td>
</tr>
<!--Here we are printing result-->
<c:forEach var="book" items="${r1}">
<tr bgcolor="">
<td>${book.user}</td>
</tr>
</c:forEach>
</table>
Hope this helps you. Make necessary changes as per your requirement . This is not complete code .
Please help me about MVC java servlet. I found problem when show database query result on multiple rows and multiple columns (load all data, let say I get 10 rows after query), I want load all list student in JSP table.
How to setAttribute in the servlet and getAttribute in the JSP?
I'm set query result into a array list, this my code:
Bean Class
package com.mvc.bean;
public class StudentBean {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
DAO Class
package com.mvc.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import com.mvc.bean.StudentBean;
import com.mvc.util.DBConnection;
public class StudentDao {
public ArrayList<StudentBean> getStudent() {
ArrayList<StudentBean> list_student = new ArrayList<StudentBean>();
Connection con = null;
Statement statement = null;
ResultSet resultSet = null;
try {
con = DBConnection.createConnection();
statement = con.createStatement();
resultSet = statement.executeQuery("SELECT * FROM tbl_student");
while(resultSet.next()){
StudentBean studentBean = new StudentBean();
studentBean.setId(resultSet.getString("id"));
studentBean.setName(resultSet.getString("name"));
list_student.add(studentBean);
}
} catch (Exception e) {
e.printStackTrace();
}
return list_student;
}
}
Servlet Class
package com.mvc.controller;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mvc.bean.StudentBean;
import com.mvc.dao.StudentDao;
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public StudentServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StudentDao studentDao = new StudentDao();
ArrayList<StudentBean> studentList = studentDao.getStudent();
//I have get value studentBean as array list
//Here, how to request.setAttribute ? i want passing to jsp table
request.getRequestDispatcher("/Student.jsp").forward(request, response);
}
}
JSP
<!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>Student</title>
</head>
<body>
<table>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<tr>
//Here i want get array value from servlet, how to ?
<td><%=request.getAttribute("?") %></td>
<td<%=request.getAttribute("?") %>></td>
</tr>
</table>
</body>
</html>
Or otherwise ?
From java code you can use : request.setAttribute("mylist", studentBean);
in you JSP you need to use request.getAttribute("mylist")
you will get your list.
For table you need to make loop for extracting information from your list.
Solved, in the Servlet Class added request.setAttribute.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StudentDao studentDao = new StudentDao();
ArrayList<StudentBean> studentList = studentDao.getStudent();
//added here
request.setAttribute("studentList", studentList);
request.getRequestDispatcher("/Student.jsp").forward(request, response);
}
And get the studentList in the JSP.
Add #taglib prefix="c" in the top line:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
In the table use forEach to extract <tr> tag.
.getID() and .getName() refer to Bean Class method:
<table>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<c:forEach var="studentBean" items="${studentList}">
<tr>
<td>${studentBean.getID()}</td>
<td>${studentBean.getName()}</td>
</tr>
</c:forEach>
</table>
I am trying to make an Ajax call from my JSP to Servlet and then get the data from the servlet and embed it to the html view. For now the data is not even being added to my tags after the ajax call. What could I be doing wrong ? Is there a better way to do it? Any suggestions or advise is really appreciated.
HomeServlet.java
package com.example;
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.Statement;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
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 org.json.JSONArray;
import com.google.gson.Gson;
/**
* Servlet implementation class Home
*/
#WebServlet("/HomeServlet")
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HomeServlet() {
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
Map<String, String> options = new LinkedHashMap<>();
String text = "some text";
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<html><body>");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/apiprovider","root","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from apiinfo");
// out.println("<table border=1 width=50% height=50%>");
// out.println("<tr><th>EmpId</th><th>EmpName</th><th>Salary</th><tr>");
while (rs.next()) {
String n = rs.getString("apiname");
String nm = rs.getString("apiendpoint");
options.put("value1", n);
options.put("value2", nm);
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
// out.println("<tr><td>" + n + "</td><td>" + nm + "</td><td>" + s + "</td></tr>");
}
// out.println("</table>");
// out.println("</html></body>");
con.close();
}
catch (Exception e) {
out.println("error");
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
response.setContentType("text/html");
PrintWriter out= response.getWriter();
String n = request.getParameter("apiname");
String p = request.getParameter("apiendpoint");
String e = request.getParameter("apiversion");
String c = request.getParameter("source");
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/apiprovider","root","");
System.out.println("Connection created");
PreparedStatement ps= ((java.sql.Connection) con).prepareStatement("insert into apiinfo(apiname,apiendpoint,apiversion,accessibility) values (?,?,?,?)");
ps.setString(1,n);
ps.setString(2,p);
ps.setString(3, e);
ps.setString(4,c);
ps.execute();
out.close();
System.out.println("Inserted");
}
catch(Exception e1)
{
System.out.println(e1);
}
}
}
Home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>
<div id="ajaxresponse">
</div>
<form>
API Name:<br>
<input type="text" id = "apiname" name="apiname">
API ENDPOINT:<br>
<input type="text" id ="apiendpoint" name="apiendpoint">
<br>
API VERSION:<br>
<input type="text" id="apiversion" name="apiversion">
ACCESSIBLE:<br>
<input type="checkbox" name="source" value="internet"> Internet<br>
<input type="checkbox" name="source" value="vpn"> VPN<br>
<!--
<br><br>
<input type="submit" formaction="Home" method="post" value="Submit"> -->
<br>
<input type="submit" id="check" name="check" value="Check">
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
console.log("I was clicked");
$.get("HomeServlet", function(responseText) {
// Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
var $select = $("#ajaxresponse"); // Locate HTML DOM element with ID "someselect".
$select.find("option").remove(); // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
$.each(responseJson, function(key, value) {
// Iterate over the JSON object.
$("<option>").val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
}); // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
</script>
</body>
</html>
When I click on the check button. This is what shows up in the url.
http://localhost:8080/TestApplication/Home.jsp?apiname=&apiendpoint=&apiversion=&check=Check
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.