Transferring data from servlet to jsp page - java

I would like to get rid of the printWriter code in the servlet.
Basically I want to output the current customers and their respective cities with the id which is a hidden field on the index page. From there I would like to be able to edit the customer name or city and then have it sent back to the index page where the information would be updated.
How do I do this?
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.ServletConfig;
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_model.*;
/**
* Servlet implementation class CustomerServlet
*/
#WebServlet(name = "CustomerServlet", urlPatterns = {
"/customer", "/editCustomer", "/updateCustomer"
})
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = -20L;
private List<Customer> customers = new ArrayList<Customer>();
/**
* #see HttpServlet#HttpServlet()
*/
public CustomerServlet() {
super();
// TODO Auto-generated constructor stub
}
#Override
public void init() throws ServletException {
Customer customer1 = new Customer();
customer1.setId(1);
customer1.setName("Donald D.");
customer1.setCity("Miami");
customer1.add(customer1);
Customer customer2 = new Customer();
customer1.setId(2);
customer1.setName("Mickey M.");
customer1.setCity("Orlando");
customer1.add(customer2);
}
private void sendCustomerList(HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html><head><title>Customers</title></head>"
+ "<body><h2>Custoemrs</h2>");
writer.println("<ul>");
for (Customer customer : customers){
writer.println("<li>" + customer.getName()
+ "(" + customer.getCity() + ") ("
+ "<a href='editCustomer?id=" + customer.getId()
+ ";>edit</a>)");
}
writer.println("</ul>");
writer.println("</body></html>");
}
private Customer getCustomer(Integer customerId){
for (Customer customer : customers) {
if(customer.getId() == customerId){
return customer;
}
}
return null;
}
private void sendEditCustomerForm(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
Integer customerId = 0;
try{
customerId = Integer.parseInt(request.getParameter("id"));
}catch(NumberFormatException e){
}
Customer customer = getCustomer(customerId);
if(customer != null){
writer.println("<html><head>"
+ "<title>Edit Customer</title></head>"
+ "<body><h2>Edit Customer</h2>"
+ "<form method = 'post' action = 'updateCustomer'>");
writer.println("<input type = 'hidden' name = 'id' value = 'customerId'/>");
writer.println("<table>");
writer.println("<tr><td>Name:</td><td>"
+ "<input name = 'name' value = '"
+ customer.getName().replaceAll("'", "&#39")
+ "'/></td></tr>");
writer.println("<tr><td>City:</td><td>"
+ "<input name = 'city' value = '"
+ customer.getCity().replaceAll("'", "&#39")
+ "'/></td></tr>");
writer.println("<tr>"
+ "<td colspan='2' style = 'text-align: right'>"
+ "<input type ='submit' value = 'Update'/></td>"
+ "</tr>");
writer.println("<tr><td colspan='2'>"
+ "<a href = 'customer'>CustomerList</a>"
+ "</td></tr>");
writer.println("</table>");
writer.println("</form></body>");
}else{
writer.println("No Customer Found");
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uri = request.getRequestURI();
if(uri.endsWith("/customer")){
sendCustomerList(response);
}else if(uri.endsWith("/editCustomer")){
sendEditCustomerForm(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//update customer
Integer 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);
}
}
Customer Class
package edu.witc.Assignment02_model;
public class Customer {
private Integer id;
private String name;
private String city;
public Integer getId(){
return id;
}
public void setId(Integer 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;
}
public void add(Customer customer1) {
// TODO Auto-generated method stub
}
}
index page
<%# 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>Home</title>
</head>
<body>
<h1>Current Customer(s) w/City</h1><br>
<%! String name, city; %>
<% %>
</body>
</html>

Better late than never.
Ok, to get this working you should add jstl library to your project.
Servlet
#WebServlet(name = "CustomerServlet", urlPatterns = {
"/customer", "/editCustomer", "/updateCustomer"
})
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = -20L;
private List<Customer> customers = new ArrayList<Customer>();
#Override
public void init() throws ServletException {
Customer customer1 = new Customer();
...
customers.add(customer1);
Customer customer2 = new Customer();
...
customers.add(customer2);
}
private Customer getCustomer(Integer customerId){
for (Customer customer : customers) {
if(customer.getId() == customerId){
return customer;
}
}
return null;
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uri = request.getRequestURI();
if(uri.endsWith("/customer")){
request.setAttribute("customers", customers);
request.getRequestDispatcher("/customers.jsp").forward(request, response);
}else if(uri.endsWith("/editCustomer")){
try{
customerId = Integer.parseInt(request.getParameter("id"));
}catch(NumberFormatException e){
e.printStackTrace();
}
Customer customer = getCustomer(customerId);
request.setAttribute("customer", customer);
request.getRequestDispatcher("/edit_customer.jsp").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer 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"));
}
response.sendRedirect("/customer");
}
}
customers.jsp
<%#page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<h1>Customer list</h1>
<ul>
<c:forEach var="c" items="${customers}">
<li>${c.name} (Edit)</li>
</c:forEach>
</ul>
edit_customer.jsp
<%#page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<h1>Edit customer</h1>
<form method="POST" action="/updateCustomer">
<input type="hidden" name="id" value="${customer.id}"/>
Name: <input type="text" name="name" value="${customer.name}"/><br/>
City: <input type="text" name="city" value="${customer.city}"/><br/>
<input type="submit" value="Save"/>
</form>

Related

How to sent data from form to backend? [Java]

how to send data from the form view to the backend? I want to use the collected data to create a JSON request.
#Controller
public class ControllerClass {
Connect connect = new Connect();
#RequestMapping(value = "/Search", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("Forms", "FlightDTO", new FlightDTO());
}
#RequestMapping(value = "/connect", method = RequestMethod.POST)
public String submit(#Valid #ModelAttribute("FlightDTO") FlightDTO flightDTO,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error.jsp";
}
return connect.connect();
}
}
View class collecting data.
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="#{/connect}" th:object="${FlightDTO}" method="post">
<p>Orgin: <input type="text" th:field="*{Origin}" /></p>
<p>Departure: <input type="text" th:field="*{Departure}" /></p>
<p>DateFrom: <input type="text" th:field="*{DateFrom}" /></p>
<p>DateTo: <input type="text" th:field="*{DateTo}" /></p>
<p>Currency: <input type="text" th:field="*{Currency}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
Class responsible for consume data JSON.
public class Connect {
public String connect() {
String output = null;
try {
UrlBuilder urlBuilder = new UrlBuilder();
urlBuilder.ulr();
System.out.println("URL String : " + urlBuilder.ulr());
URL url = new URL(urlBuilder.ulr());
HttpURLConnection conn = (HttpURLConnection) url.openConnection() ;
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : " + conn.getResponseCode());
}
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
output = response.toString();
} catch (Exception e) {
System.out.println("Exception Flight:- " + e);
}
return output;
}
}
Class that is responsible for collecting data from the view
public class FlightDTO {
private String dateFrom;
private String dateTo;
#Size(min = 2, max = 10)
private String origin;
#Size(min = 2, max = 10)
private String departure;
#Size(min = 2, max = 4)
private String currency;
My URL builder Class responsible for build request.
public class UrlBuilder extends FlightDTO {
private String key = "47c5ebee552ce27c902e7521b6ef3858";
public String ulr( ) {
String connectUrlString =
"http://api.travelpayouts.com/v1/prices/cheap?origin="
+ getOrigin() + "&destination=" + getDeparture() +
"&depart_date=" + getDateFrom() +
"&currency=" + getCurrency() +
"&return_date=" + getDateTo() +
"&token=" + key;
return connectUrlString ;
}
}
I tried to solve my problem in many ways. Unfortunately to no avail, that's why I decided to create a thread. I could not find a similar problem. I was probably looking for a bad one. However, I do not know how to google
I get null response :
http://api.travelpayouts.com/v1/prices/cheap?origin=null&destination=null&depart_date=null&currency=null&return_date=null&token=47c5ebee552ce27c902e7521b6ef3858
Above code will not work as you are creating new UrlBuilder object which will not have any values instead of passing flightDTO object from the controller.
Controller
#RequestMapping(value = "/connect", method = RequestMethod.POST)
public String submit(#Valid #ModelAttribute("FlightDTO") FlightDTO flightDTO,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error.jsp";
}
return connect.connect(flightDTO); //passing flightDTO object received from form
}
Connect
public String connect(FlightDTO flightDTO) { //Added new parameter to recevice flightDTO
String output = null;
try {
UrlBuilder urlBuilder = new UrlBuilder();
urlBuilder.setOrigin(flightDTO.getOrigin());
urlBuilder.setDestination(flightDTO.getDestination());
urlBuilder.setDateFrom(flightDTO.getDateFrom());
urlBuilder.setDateTo(flightDTO.getDateTo());
......//Set other required values
urlBuilder.ulr();
System.out.println("URL String : " + urlBuilder.ulr());
......//other code
}
}

Display datatable on clicking a button

I'm writing a webapp where in there is a table that is to be generated using Ajax. This data is actually pulled from the database. And here I want to use jquery datatable plugin.
Index.jsp
<html>
<head>
</head>
<body>
<marquee>
<h1>This is an example of ajax</h1>
</marquee>
<form name="vinform">
Enter id:<input type="button" id="somebutton" value="Click Me">
</form>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Case Number</th>
<th>Case Owner</th>
<th>Status</th>
<th>Issue</th>
<th>Reason</th>
<th>Date/Time Opened</th>
<th>Age</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Case Number</th>
<th>Case Owner</th>
<th>Status</th>
<th>Issue</th>
<th>Reason</th>
<th>Date/Time Opened</th>
<th>Age</th>
</tr>
</tfoot>
</table>
<span id="somediv"> </span>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="tableGenerator.js"></script>
</body>
</html>
tableGenerator.js
$('#somebutton').click(function() {
$(document).ready(function() {
$('#example').DataTable({
"ajax" : "Controller",
"columns" : [ {
"data" : "userBean.caseNumber"
}, {
"data" : "userBean.caseOwner"
}, {
"data" : "userBean.status"
}, {
"data" : "userBean.issue"
}, {
"data" : "userBean.reason"
}, {
"data" : "userBean.age"
} ]
});
});
});
UserBean.java
package org.bean;
public class UserBean {
private int age;
private String caseOwner, status, issue, reason, dateOpened, caseNumber, resolution, finalStatus, startDate,
endDate;
private Double totalTimeTaken;
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getCaseNumber() {
return caseNumber;
}
public void setCaseNumber(String caseNumber) {
this.caseNumber = caseNumber;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCaseOwner() {
return caseOwner;
}
public void setCaseOwner(String caseOwner) {
this.caseOwner = caseOwner;
}
public String getStatus() {
return status;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public void setStatus(String status) {
this.status = status;
}
public String getIssue() {
return issue;
}
public void setIssue(String issue) {
this.issue = issue;
}
public String getDateOpened() {
return dateOpened;
}
public void setDateOpened(String dateOpened) {
this.dateOpened = dateOpened;
}
public String getResolution() {
return resolution;
}
public void setResolution(String resolution) {
this.resolution = resolution;
}
public String getFinalStatus() {
return finalStatus;
}
public void setFinalStatus(String finalStatus) {
this.finalStatus = finalStatus;
}
public double getTotalTimeTaken() {
return totalTimeTaken;
}
public void setTotalTimeTaken(Double totalTimeTaken) {
this.totalTimeTaken = totalTimeTaken;
}
public UserBean() {
}
public UserBean(String caseNumber, String caseOwner, String issue, int age, String reason, String dateOpened,
String status, String finalStatus, String resolution, String startDate, String endDate,
Double totalTimeTaken) {
this.caseNumber = caseNumber;
this.caseOwner = caseOwner;
this.issue = issue;
this.reason = reason;
this.age = age;
this.dateOpened = dateOpened;
this.status = status;
this.resolution = resolution;
this.finalStatus = finalStatus;
this.startDate = startDate;
this.endDate = endDate;
this.totalTimeTaken = totalTimeTaken;
}
}
Controller.java(Servlet)
import java.io.IOException;
import java.util.ArrayList;
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.bean.UserBean;
import com.dao.DataDao;
import com.google.gson.Gson;
#WebServlet("/Controller")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// String id = request.getParameter("val");
DataDao dataDao = new DataDao();
ArrayList<UserBean> list = dataDao.getFrameWork();
String searchList = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(searchList);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
DBUtility.java
package com.dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBUtility {
private static Connection connection = null;
public static Connection getConnection() throws Exception {
if (connection != null)
return connection;
else {
// Store the database URL in a string
String userName = "sa";
String password = "T!ger123";
String url = "jdbc:sqlserver:XXXXXX;DatabaseName=TEST";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// set the url, username and password for the databse
connection = DriverManager.getConnection(url, userName, password);
return connection;
}
}
}
DataDao.java
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.bean.UserBean;
public class DataDao {
private Connection connection;
public DataDao() throws Exception {
connection = DBUtility.getConnection();
}
public ArrayList<UserBean> getFrameWork() throws SQLException {
ArrayList<UserBean> list = new ArrayList<UserBean>();
PreparedStatement ps = null;
try {
ps = connection.prepareStatement("select * from statusTable");
// ps.setString(1, frameWork);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
UserBean userBean = new UserBean();
userBean.setCaseNumber(rs.getString(1));
userBean.setCaseOwner(rs.getString(2));
userBean.setStatus(rs.getString(3));
userBean.setIssue(rs.getString(4));
userBean.setReason(rs.getString(5));
userBean.setDateOpened(rs.getString(6));
userBean.setAge(rs.getInt(7));
list.add(userBean);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return list;
}
}
When I click on the button, instead of displaying the table data, it is showing nothing apart from the Basic html skeleton created in my index file.
Instead of using
$('#somebutton').click(function() {
$(document).ready(function() {
$('#example').DataTable({
"ajax" : "Controller",
"columns" : [ {
"data" : "userBean.caseNumber"
}, {
"data" : "userBean.caseOwner"
}, {
"data" : "userBean.status"
}, {
"data" : "userBean.issue"
}, {
"data" : "userBean.reason"
}, {
"data" : "userBean.age"
} ]
});
});
});
when i used
$('#somebutton').click(
function() {
$.getJSON('Controller', function(searchList) {
var $table = $('<table>').appendTo($('#somediv'));
$.each(searchList, function(index, userBean) {
$('<tr>').appendTo($table).append(
$('<td>').text(userBean.caseNumber)).append(
$('<td>').text(userBean.caseOwner)).append(
$('<td>').text(userBean.status)).append(
$('<td>').text(userBean.issue)).append(
$('<td>').text(userBean.reason)).append(
$('<td>').text(userBean.age));
});
});
});
A normal html table is getting displayed.
Please let me know how can i display this data.
Thanks

How to receive info to put in HTML/JSP from post servlet

Basically my goal for this page I'm working on is for users to type in a stock symbol and this information goes to a post method and send back the data to put on the same html/jsp page. I have been able to get this to work where the form leads to another JSP page, but that has to be a separate page, I'd like to be able to stay on the same page and have the info come up. If you have a resource that could teach me how to deal with this problem, I would appreciate that just as much as a solution. I have been using the Gradle Build Tool.
Here is the form(in index.jsp):
<h1>Search Stock</h1>
<form method="POST" action="DataPage.jsp">
<input type = "text" name = "Symbol">
<input type = "submit" name = "getData">
</form>
Here is the functioning JSP code(DataPage.jsp):
<%
String Ticker = request.getParameter("Symbol");
PrintWriter write = response.getWriter();
if((Ticker == null)){
String message = "Please enter a stock symbol";
write.println(message);
}else{
try{
Company object = Serializing.getCompany(Ticker);
object.updateData();
write.println("data last added" + object.getLastUpdate());
write.println(object.getSentiment());
}catch(NullPointerException x){
Company object = Serializing.getCompany(Ticker);
}
}%>
Here is the servlet I tried writing(DataServlet.java), I have very little experience with servlets, I scavenged this from different sources and questions on stackoverflow:
package Default;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by Ceyer on 9/3/2015.
*/
#javax.servlet.annotation.WebServlet(name = "DataServlet", urlPatterns = ("/"))
public class DataServlet extends javax.servlet.http.HttpServlet {
private static final long serialVersionUID = 1L;
public DataServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
String Ticker = request.getParameter("Symbol");
if ((Ticker == null)||Ticker.trim().isEmpty()) {
String message = "Please enter a stock symbol";
request.setAttribute("data", message);
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} else {
PrintWriter write = response.getWriter();
try {
Company object = Serializing.getCompany(Ticker);
object.updateData();
request.setAttribute("data", object.getSentiment() + "updated last" + object.getLastUpdate());
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} catch (NullPointerException x) {
Company object = Serializing.getCompany(Ticker);
request.setAttribute("data", "We do not have info on this stock");
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
If you want to use only one page and with a servlet, I think you can use session and response.sendRedirect() to do it.
This is index.jsp page
<h1>Search Stock</h1>
<form method="POST" action="DataServlet" onsubmit="dataCheck()">
<input type="text" name="Symbol">
<input type="submit" value="getData">
</form>
<%
if(session.getAttribute("data") != null) {
out.print("<p>" + session.getAttribute("data"));
session.removeAttribute("data");
}
%>
<script>
function dataCheck() {
if(document.getElementsByName[0].value == ""){
alert("Symbol is null!");
return false;
}
return true;
}
</script>
This is DataServlet class
public class DataServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String Ticker = request.getParameter("Symbol");
Company object = Serializing.getCompany(Ticker);
if (object != null) {
object.updateData();
request.getSession().setAttribute("data", object.getSentiment() +
"updated last" + object.getLastUpdate());
} else {
request.getSession().setAttribute("data", "We do not have info on this stock");
}
response.sendRedirect("index.jsp");
}
}

SQL syntax error in pagination query

I'm trying to make pagination in my jsp page. But I didn't get data from Database. I got an error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-10, 5' at line 1".
I didn't understand what's wrong. would you please check my code and help me to solve the problem?
BooksInfo.java
package com.sreejonee.books;
import java.sql.Date;
import java.sql.Timestamp;
public class BooksInfo {
private int book_id;
private String bookName;
private String filename;
private String writerName;
private String book_details;
private Timestamp date_time;
private int rating;
private int parentscat_id;
private String parentscat_name;
private String thumCoverImag;
private String filePath;
public int getBook_id() {
return book_id;
}
public void setBook_id(int book_id) {
this.book_id = book_id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getWriterName() {
return writerName;
}
public void setWriterName(String writerName) {
this.writerName = writerName;
}
public String getBook_details() {
return book_details;
}
public void setBook_details(String book_details) {
this.book_details = book_details;
}
public Timestamp getDate_time() {
return date_time;
}
public void setDate_time(Timestamp date_time) {
this.date_time = date_time;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public int getParentscat_id() {
return parentscat_id;
}
public void setParentscat_id(int parentscat_id) {
this.parentscat_id = parentscat_id;
}
public String getParentscat_name() {
return parentscat_name;
}
public void setParentscat_name(String parentscat_name) {
this.parentscat_name = parentscat_name;
}
public String getThumCoverImag() {
return thumCoverImag;
}
public void setThumCoverImag(String thumCoverImag) {
this.thumCoverImag = thumCoverImag;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
BooksInfoDAO.java
package com.sreejonee.books;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import com.sreejonee.db.ConnectionFactory;
import com.sreejonee.db.DBConnector;
public class BooksInfoDAO {
Connection connection;
Statement stmt;
private int noOfRecords;
private static Connection getConnection()
throws SQLException,
ClassNotFoundException
{
Connection con = ConnectionFactory.
getInstance().getConnection();
System.out.println("connected!");
return con;
}
public List<BooksInfo> viewAllBooksInfo(int offset, int noOfRecords) {
String query = "select SQL_CALC_FOUND_ROWS * from library ORDER by date_time DESC limit"+ offset + ", " + noOfRecords;
List<BooksInfo> bookslist = new ArrayList<BooksInfo>();
BooksInfo books = null;
try {
connection = getConnection();
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
books = new BooksInfo();
books.setBook_id(rs.getInt("book_id"));
books.setBook_details(rs.getString("book_details"));
books.setBookName(rs.getString("bookName"));
books.setWriterName(rs.getString("writerName"));
books.setDate_time(rs.getTimestamp("date_time"));
books.setParentscat_id(rs.getInt("parentscat_id"));
books.setParentscat_name(rs.getString("parentscat_name"));
books.setFilename(rs.getString("filename"));
books.setFilePath(rs.getString("filePath"));
books.setRating(rs.getInt("rating"));
books.setThumCoverImag(rs.getString("thumCoverImag"));
bookslist.add(books);
}
rs.close();
rs = stmt.executeQuery("SELECT FOUND_ROWS()");
if (rs.next())
this.noOfRecords = rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e2) {
e2.printStackTrace();
}
}
return bookslist;
}
public int getNoOfRecords() {
return noOfRecords;
}
}
Servlet:
BooksInfoServlet.java
package com.sreejonee.servlet;
import java.io.IOException;
import java.util.List;
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 com.sreejonee.books.BooksInfo;
import com.sreejonee.books.BooksInfoDAO;
#WebServlet("/BooksInfoServlet")
public class BooksInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public BooksInfoServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int page = 1;
int recordsPerPage = 5;
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
BooksInfoDAO booksInfoDAO = new BooksInfoDAO();
List<BooksInfo> bookslist = booksInfoDAO.viewAllBooksInfo((page-1)*recordsPerPage, recordsPerPage);
int noOfRecords = booksInfoDAO.getNoOfRecords();
int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
request.setAttribute("booksList", bookslist);
request.setAttribute("noOfPages", noOfPages);
request.setAttribute("currentPage", page);
RequestDispatcher view = request.getRequestDispatcher("user.jsp");
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
JSP page:
<c:forEach var="books" items="${bookslist}">
<div id="${books.filename}" class="single_midlecontent_component">
<div class="socialicon_on_post">
<h4>
<i class="fa fa-facebook-square"></i>
</h4>
</div>
<div class="title_of_post ">
<a href="#" class="media-left">
<img class="media-object" src="${books.getFilePath()+File.separator+books.getThumCoverImag()}" alt="...">
</a>
<h5 class="media-body ">
<span>${books.getBookName()}</span>
</h5>
<h5 class="media-body ">
<span>by ${books.getWriterName()}</span>
</h5>
<p class="date_time media-body">${books.getDate_time()}</p>
</div>
<div class="body_of_post">
<p>${books.getBook_details()}</p>
<img src="" class="img-responsive" alt="Responsive image">
</div>
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-layout="standard" data-action="like" data-show-faces="true" data-share="true"></div>
<div class="download_book">
<form action="DownloadFileServlet" method="post">
<input type="hidden" name="filename" value="${books.getFilename()}">
<div>
<input type="hidden" name="parentscat_name" value="${books.getParentscat_name()}">
</div>
<div class="download_button">
<input class="btn btn-default " type="submit" value="Download">
</div>
</form>
</div>
<div class="bottom_of_post"></div>
</div>
I can see two errors here.
First one:
String query = "select SQL_CALC_FOUND_ROWS * from library ORDER by date_time DESC limit"+ offset + ", " + noOfRecords;
There is a space missing after limit -- the way you wrote it, it will generate ... limit10, 5.
Second one:
I think the caller of viewAllBooksInfo() gives a wrong offset argument. Based on the error, I assume that offset is -10 which is illegal because the arguments to the limit clause in MySQL need to be non-negative.
In your updated question, you show this code:
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
BooksInfoDAO booksInfoDAO = new BooksInfoDAO();
List<BooksInfo> bookslist = booksInfoDAO.viewAllBooksInfo((page-1)*recordsPerPage, recordsPerPage);
Obviously, because recordsPerPage is 5, and offset is -10, page seems to be -1. You have not shown the Code for the page which calls the BooksInfoServlet, but I guess you have entered -1 as the requested page number there.
You should have looked yourself before asking this question. It is expected from you that you should first try to remove these error yourself.
If you would look into the error stack, it says:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-10, 5' at line 1"
If you can look carefully, the limit options are "-10, 5". Limit arguments in MySQL should be non-negative.
And in BooksInfoDAO.java code:
public List<BooksInfo> viewAllBooksInfo(int offset, int noOfRecords) {
String query = "select SQL_CALC_FOUND_ROWS * from library ORDER by date_time DESC limit"+ offset + ", " + noOfRecords;
...
you are missing a space between the limit clause and the offset parameter.

output JSON array in a html table(a jsp page)

As the title suggested, how do I output a JSON array correctly in a table from a JSP page?
Right now whenever I display the JSON array object using <c:out value="${jsonArray}"/> but it just displays the whole contents of it in JSON string i.e {name: hello, address: baker street } but what I want to do is somehow parse this and display the info appropriately like this:
**name** **address**
hello baker street
spring java
tim sun
Is it possible in JSTL? I am new to JSTL stuff.
package com.kc.models;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;
import org.hibernate.Hibernate;
public class FileObject {
private String filename;
private String type;
private double size;
private Blob file;
private int id;
private String os;
private String description;
public FileObject() {
}
/**
* Constructor for use in returning just the list of files without the
* actual content
*
* #param name
* #param size
* #param id
* #param type
*/
public FileObject(String name, double size, int id, String type) {
this.filename = name;
this.type = type;
this.size = size;
this.id = id;
}
/**
* Constructor used to create a fileObject with all its properties assigned
*
* #param name
* #param size
* #param id
* #param type
* #param file
*/
public FileObject(String name, double size, int id, String type, Blob file,
String os, String description) {
this.filename = name;
this.type = type;
this.size = size;
this.id = id;
this.file = file;
this.os = os;
this.description = description;
}
public FileObject(String description){
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFilename() {
return filename;
}
public void setFilename(String fileName) {
this.filename = fileName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getSize() {
return size;
}
public void setSize(double size) {
this.size = size;
}
public Blob getFile() {
return file;
}
public void setFile(Blob file) {
this.file = file;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
#Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO call a method that returns a list of Mobile Apps.
String fileType = ServletRequestUtils.getRequiredStringParameter(request, "fileType");
//testAddingSomeFilesToDb();
return new ModelAndView("" + "testJsonResponse", "jsonArray",
getFileList(fileType) );
}
/**
* Get file list from sql server based on type
* #return file list in json
*/
private JSONArray getFileList(String type) {
// TODO: Get request parameter that states what type of file extensions
// the client wants to recieve
ctx = new ClassPathXmlApplicationContext("zang-file-service.xml");
FileHelper file = (FileHelper) ctx.getBean("fileHelper");
return file.getFileList(type);
}
public JSONArray getFileList(String type) {
return constructJsonArray(dbFileHelper.getFileList(type));
}
private JSONArray constructJsonArray(List<FileObject> fileList) {
JSONArray mJsonArray = new JSONArray();
JSONObject mJsonFileObject = new JSONObject();
for (int i = 0; i < fileList.size(); i++) {
mJsonFileObject.put("FileObject", fileList.get(i));
System.out.println("File ID = " + fileList.get(i).getId());
System.out.println("fileName = " + fileList.get(i).getFilename());
System.out.println("type = " + fileList.get(i).getType());
System.out.println("size = " + fileList.get(i).getSize());
mJsonArray.add(mJsonFileObject);
}
return mJsonArray;
}
here is my jsp page:
<%# include file="/WEB-INF/jsp/include.jsp" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var files = "${jsonArray}";
$(document).ready(function() {
var table = $('<table/>').appendTo($('#somediv'));
$(files).each(function(i, file) {
$('<tr/>').appendTo(table)
.append($('<td/>').text(file.filename))
.append($('<td/>').text(file.id))
.append($('<td/>').text(file.type))
.append($('<td/>').text(file.size))
.append($('<td/>').text(file.os));
});
});
</script>
</head>
<body>
<div id="somediv"></div>
</body>
</html>
edit: here is my json output:
var files = [{"FileObject":{"description":"","file":null,"filename":"ACG Simulator(firefox).jpg","id":6,"os":"","size":172,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"car.jpg","id":11,"os":"","size":152,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"contacts highlighted.jpg","id":13,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"contacts highlighted2.jpg","id":14,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"contacts options.jpg","id":15,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"edit contact view.jpg","id":17,"os":"","size":52,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"fileObject.jpg","id":20,"os":"","size":30,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"groups.jpg","id":27,"os":"","size":31,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"inside contacts.jpg","id":31,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"Music highlighted.jpg","id":37,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"music options view.jpg","id":38,"os":"","size":46,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"music phone view.jpg","id":39,"os":"","size":51,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"music vault view.jpg","id":40,"os":"","size":48,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"nice.jpg","id":41,"os":"","size":225,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photo highlighted.jpg","id":42,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photo options view.jpg","id":43,"os":"","size":48,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photo preview view.jpg","id":44,"os":"","size":46,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photos phone view.jpg","id":45,"os":"","size":51,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photos vault view.jpg","id":46,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"svn error.jpg","id":54,"os":"","size":35,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"Video Highlighted.jpg","id":55,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"Videos options view.jpg","id":56,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"videos phone view.jpg","id":57,"os":"","size":50,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"videos Vault view.jpg","id":58,"os":"","size":49,"type":"jpg"}}]
Your question is too ambigious to give a suitable answer, so I'll cover all possible scenarios:
You have it as a JavaScript variable like so:
var persons = [
{ "name": "John Doe", "address": "Main Street 1" },
{ "name": "Jane Doe", "address": "Baker Street 1" },
{ "name": "Jack Doe", "address": "Church Street 1" }
];
I'd suggest to use jQuery to create a HTML table out of it. Here's an SSCCE, you can copy'n'paste'n'run it:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var persons = [
{ "name": "John Doe", "address": "Main Street 1" },
{ "name": "Jane Doe", "address": "Baker Street 1" },
{ "name": "Jack Doe", "address": "Church Street 1" }
];
$(document).ready(function() {
var table = $('<table/>').appendTo($('#somediv'));
$(persons).each(function(i, person) {
$('<tr/>').appendTo(table)
.append($('<td/>').text(person.name))
.append($('<td/>').text(person.address));
});
});
</script>
</head>
<body>
<div id="somediv"></div>
</body>
</html>
You have it as a Java String variable like so:
String jsonPersons = "["
+ "{ \"name\": \"John Doe\", \"address\": \"Main Street 1\" },"
+ "{ \"name\": \"Jane Doe\", \"address\": \"Baker Street 1\" },"
+ "{ \"name\": \"Jack Doe\", \"address\": \"Church Street 1\" }"
+ "]";
Then I suggest to use a JSON parser to get a List<Person> out of it, like Google Gson:
List<Person> persons = new Gson().fromJson(jsonPersons, new TypeToken<List<Person>>() {}.getType());
Where the Person class look like this:
public class Person {
private String name;
private String address;
// Add or generate getters/setters.
}
Let the servlet put it in the request scope and forward to JSP for display like so:
request.setAttribute("persons", persons);
request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response);
In JSP, use JSTL <c:forEach> to iterate over it:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${persons}" var="person">
<tr>
<td>${person.name}</td>
<td>${person.address}</td>
</tr>
</c:forEach>
</table>
Same as 2), you have it as a Java variable, but you'd like to obtain it by Ajax in JSP. Then create a Servlet class which does the following in doGet() method:
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().write(jsonPersons);
And call it by jQuery Ajax with a callback which does the same as 1).
$(document).ready(function() {
var table = $('<table/>').appendTo($('#somediv'));
$.getJSON('url/to/servlet', function(persons) {
persons.each(function(i, person) {
$('<tr/>').appendTo(table)
.append($('<td/>').text(person.name))
.append($('<td/>').text(person.address));
});
});
});
Assuming:
jsonArray = [ {name: 'hello', address: 'baker street'}, ... ];
One way to do it is to construct the html in Javascript code like this:
var myHTMLStr = '<table>';
for(var i in jsonArray) {
myHTMLStr+='<tr><td>' + jsonArray[i]['name'] + '</td><td>' + jsonArray[i]['address'] + '</td></tr>';
}
myHTMLStr+='</table>';
Now display the HTML string:
document.getElementById('tableOutput').innerHTML = myHTMLStr;

Categories

Resources