Not able to fetch data from database by using ajax in java - java

hi i am implementing program which fetch data from database in java with ajax. but unfortunately it is not retireving output here is my code. program is running succesfully but not able to display database data from it.
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AJAX JsonArray Example</title>
<link href='http://fonts.googleapis.com/css?family=Oxygen' rel='stylesheet' type='text/css'>
<style type="text/css">
table, td, th
{
border:1px solid green;
font-family: 'Oxygen', sans-serif;
}
th
{
background-color:green;
color:white;
}
body
{
text-align: center;
}
.container
{
margin-left: auto;
margin-right: auto;
width: 40em;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#tablediv").hide();
$("#showTable").click(function(event){
$.get('PopulateTable',function(responseJson) {
if(responseJson!=null){
$("#countrytable").find("tr:gt(0)").remove();
var table1 = $("#countrytable");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['code']);
rowNew.children().eq(1).text(value['name']);
rowNew.children().eq(2).text(value['continent']);
rowNew.children().eq(3).text(value['region']);
rowNew.children().eq(4).text(value['population']);
rowNew.children().eq(5).text(value['capital']);
rowNew.appendTo(table1);
});
}
});
$("#tablediv").show();
});
});
</script>
</head>
<body class="container">
<h1>AJAX Retrieve Data from Database in Servlet and JSP using JSONArray</h1>
<input type="button" value="Show Table" id="showTable"/>
<div id="tablediv">
<table cellspacing="0" id="countrytable">
<tr>
<th scope="col">Code</th>
<th scope="col">Name</th>
<th scope="col">Continent</th>
<th scope="col">Region</th>
<th scope="col">Population</th>
<th scope="col">Capital</th>
</tr>
</table>
</div>
</body>
</html>
FetchData.jsp
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import Countries.Countries;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
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.Properties;
public class FetchData {
private static Connection connection = null;
public static Connection getConnection() {
if (connection != null)
return connection;
else {
try {
Properties prop = new Properties();
InputStream inputStream = FetchData.class.getClassLoader().getResourceAsStream("/db.properties");
prop.load(inputStream);
String driver = prop.getProperty("jdbc:mysql:");
String url = prop.getProperty("localhost:3306/country_db");
String user = prop.getProperty("root");
String password = prop.getProperty("");
Class.forName(driver);
connection = DriverManager.getConnection("localhost:3306/country_db", "root", "");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
}
public static ArrayList<Countries> getAllCountries() {
connection = FetchData.getConnection();
ArrayList<Countries> countryList = new ArrayList<Countries>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from country");
while(rs.next()) {
Countries country=new Countries();
country.setCode(rs.getString("Code"));
country.setName(rs.getString("Name"));
country.setContinent(rs.getString("Continent"));
country.setRegion(rs.getString("Region"));
country.setPopulation(rs.getInt("Population"));
country.setCapital(rs.getString("Capital"));
countryList.add(country);
}
} catch (SQLException e) {
e.printStackTrace();
}
return countryList;
}
}
PopulateTable.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import Countries.Countries;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
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;
#WebServlet("/PopulateTable")
public class PopulateTable extends HttpServlet {
private static final long serialVersionUID = 1L;
public PopulateTable() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<Countries> country=new ArrayList<Countries>();
country=FetchData.getAllCountries();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(country, new TypeToken<List<Countries>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
response.setContentType("application/json");
response.getWriter().print(jsonArray);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Coutries.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Countries;
public class Countries {
public Countries(String code,String name, String continent,String region,int population, String capital )
{
this.setCode(code);
this.setName(name);
this.setContinent(continent);
this.setRegion(region);
this.setPopulation(population);
this.setCapital(capital);
}
public Countries() {
}
private String code;
private String name;
private String continent;
private String region;
private int population;
private String capital;
public void setCode(String code) {
this.code = code;
}
public String getCode() {
return code;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setContinent(String continent) {
this.continent = continent;
}
public String getContinent() {
return continent;
}
public void setRegion(String region) {
this.region = region;
}
public String getRegion() {
return region;
}
public void setPopulation(int population) {
this.population = population;
}
public int getPopulation() {
return population;
}
public void setCapital(String capital) {
this.capital = capital;
}
public String getCapital() {
return capital;
}
}
here is a image for mysql database and its table.

You can first try to figure out where the actual problem is occurring.
- First you can check if the data is actually being retrieved from database. In servlet doGet method you iterate over country list and print its data using system.out.println
- If you are able to retrieve data then on the client side see that proper Json data is coming. You can check response on client side using firebug.
- In the jQuery code use console.log to check whether the data is coming or not. You can put log statement before and after the if(responseJson!=null) to check if data is actually null or not.
- If data is not null then there must be some issue with the format in which data is coming or how you are iterating over the data.

Related

Problems with cli.get() and getting attributes in JSP and Servlet

Good morning, I have this problem.
I have a java class "Cliente" with the corresponding data (I leave you the code)
package Clases;
public class Cliente {
public Cliente(String dni, String nombre, String apellido, String telefono){
}
}
Then, I have this Servlet with DoGet where I generate a list of Cliente and get my session, and a dopost that asks for the parameters:
package Servlets;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.util.*;
import Clases.Cliente;
#WebServlet(name = "SvPrueba", urlPatterns = {"/SvPrueba"})
public class SvPrueba extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Cliente> listaClientes = new ArrayList<> ();
listaClientes.add(new Cliente("12345678", "Luisina", "de Paula", "444222357"));
listaClientes.add(new Cliente("46325965", "Avril", "Lavigne", "774568931"));
listaClientes.add(new Cliente("69584123", "Gianluigi", "Guidicci", "4567531654"));
HttpSession misession = request.getSession();
misession.setAttribute("listaClientes", listaClientes);
response.sendRedirect("MostrarJSP.jsp");
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String dni = request.getParameter("dni");
String nombre = request.getParameter("nombre");
String apellido = request.getParameter("apellido");
String telefono = request.getParameter("telefono");
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
Finally, I have a JSP where it presents the error: In it I bring the session and ask for the attributes to write them. However, on every "cli.get" I get cannot find symbol error
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Clientes</title>
</head>
<body>
<h1>Lista de Clientes</h1>
<%# page import="java.util.List" %>
<%# page import="Clases.Cliente" %>
<%
List<Cliente> listaClientes = (List) request.getSession().getAttribute("listaClientes");
int cont=1;
for (Cliente cli : listaClientes) { %>
<p><b>Cliente Nº <%=cont%></b></p>
<p>Dni: <%=cli.getDni()%></p>
<p>Nombre: <%=cli.getNombre()%></p>
<p>Apellido: <%=cli.getApellido()%></p>
<p>Teléfono: <%=cli.getTelefono()%></p>
<% cont= cont+1;%>
<%}%>
</body>
</html>
I'm starting in Java and I can't fix this :(
I hope that getDni, getNombre, etc. will bring me the data and write it in the HTML code, but I have some error and I don't know what it is.
Thank you ^^
The Cliente class is empty (apart from an empty constructor that does nothing by itself if you don't tell it what to do). You have to define both the data it contains and the methods to get the data. Something like this:
public class Cliente {
// the data in the class
String dni;
String nombre;
String apellido;
String telefono;
// manually set all members here
public Cliente(String dni, String nombre, String apellido, String telefono) {
this.dni = dni;
this.nombre = nombre;
this.apellido = apellido;
this.telefono = telefono;
}
// getter methods are not created automatically, you have to define them
public String getDni() { return dni; }
public String getNombre() { return nombre; }
public String getApellido() { return apellido; }
public String getTelefono() { return telefono; }
}

React form data to Java Servlet

I want a solution for my problem. I am facing a problem where the data received from Search.js form is not sending data to my Java Servlet in DYNAMIC WEB PROJECT in Eclipse. I have attached the screenshots and the codes also. Please help.
Search.js Code:
import React from 'react'
import axios from 'axios';
const Search = () => {
const handleSubmit = async (e) => {
const re = /^[0-9\b]+$/
if (e.key === "Enter") {
if(e.target.value==='' || re.test(e.target.value))
{
e.preventDefault()
let res= fetch("http://localhost:8080/Hrc/search",{
mode:"no-cors",
method:"POST",
headers: {
'Content-Type': 'application/json'
},
body:JSON.stringify({
cust_number:e.target.value
})})
console.log(e.target.value)
if(res.ok)
{
console.log("Successful search")
}
else{
console.log("Error")
}
}
// ... submit to API or something
}
}
return (
<div>
<div>
<form onSubmit='http://localhost:8080/Hrc/search' method="post">
<input type="text" name='cust_number' placeholder='Search Customer Id' className="sarch-button" onKeyPress={handleSubmit}/>
</form>
</div>
</div>
)
}
export default Search
App.js
import React,{ useState } from 'react'
import {useMemo} from 'react'
import Logo from './components/Logo.js'
import './App.css'
import PredictBtn from './components/PredictBtn.js'
import Analytics from './components/AnalyticsView.js'
import Advsrchmodal from './components/Advsrchmodal.js'
import Search from './components/Search.js'
import Add from './components/Addmodal.js'
import Edit from './components/Edit.js'
import Delete from './components/Delete.js'
import Table from './components/Table.js'
import table from './assets/json/mock.json'
import {Columns} from './components/column'
export default function App(){
const [advmodal,setadvmodal]=useState(false)
const [addmodal,setaddmodal]=useState(false)
const [editmodal,seteditmodal]=useState(false)
const [delmodal,setdelmodal]=useState(false)
const [search,setSearch]=useState('')
const searchItems=(searchValue)=>{
setSearch(searchValue)
}
const columns = useMemo(()=> Columns ,[])
const data = useMemo(()=> table, [])
return(
<div>
<body>
<Logo />
<div className='header-btns'>
<PredictBtn/><Analytics/>
<button onClick={()=> setadvmodal(true)} className="leftbtns adv-srch-btn"id="adv-srch-modal">ADVANCED SEARCH</button>
<Advsrchmodal onClose={()=> setadvmodal(false)} show={advmodal}/>
<Search handleSearch={searchItems}/>
<button onClick={()=> setaddmodal(true)} className="rightbtns add-btn" id ="add-modal">ADD</button>
<Add onClose={()=> setaddmodal(false)} show={addmodal}/>
<button onClick={()=> seteditmodal(true)} className="rightbtns edit-btn">EDIT</button>
<Edit onClose={()=> seteditmodal(false)} show={editmodal}/>
<button onClick={()=> setdelmodal(true)} className="rightbtns del-btn">DELETE</button>
<Delete onClose={()=>setdelmodal(false)} show={delmodal}/>
</div>
<div className="Table">
<Table columns={Columns} data={data}/>
</div>
</body>
</div>
)
}
Ignore the other imports , focus on the search import
Search.java('The Servlet') code:
package com.highradius;
import java.io.IOException;
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 java.io.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.FileWriter;
#WebServlet("/servlet")
public class Search extends HttpServlet {
private static final long serialVersionUID = 1L;
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost:3306/grey_goose?zeroDateTimeBehavior=convertToNull";
static final String USER="root";
static final String PASSWORD="ROHITghosh1234";
public Search() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
resp.addHeader("Access-Control-Allow-Origin","http://localhost:3000");
Connection conn = null;
Statement stmt = null;
List<Response> demoList = new ArrayList<>();
String cust_number=req.getParameter("cust_number");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
stmt = conn.createStatement();
String sql;
if(cust_number=="")
sql="select sl_no,business_code,cust_number,clear_date,buisness_year,doc_id,posting_date,document_create_date,due_in_date,invoice_currency,document_type,posting_id,total_open_amount,baseline_create_date,cust_payment_terms,invoice_id from winter_internship";
else
sql="select sl_no,business_code,cust_number,clear_date,buisness_year,doc_id,posting_date,document_create_date,due_in_date,invoice_currency,document_type,posting_id,total_open_amount,baseline_create_date,cust_payment_terms,invoice_id from winter_internship where cust_number like '"+cust_number+"%'";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {
Response res=new Response();
res.setsl_no(rs.getInt("sl_no"));
res.setbusiness_code(rs.getString("business_code"));
res.setcust_number(rs.getString("cust_number"));
res.setclear_date(rs.getDate("clear_date"));
res.setbuisness_year(rs.getInt("buisness_year"));
res.setdoc_id(rs.getString("doc_id"));
res.setposting_date(rs.getDate("posting_date"));
res.setdocument_create_date(rs.getDate("document_create_date"));
res.setdue_in_date(rs.getDate("due_in_date"));
res.setinvoice_currency(rs.getString("invoice_currency"));
res.setdocument_type(rs.getString("document_type"));
res.setposting_id(rs.getInt("posting_id"));
res.settotal_open_amount(rs.getDouble("total_open_amount"));
res.setbaseline_create_date(rs.getDate("baseline_create_date"));
res.setcust_payment_terms(rs.getString("cust_payment_terms"));
res.setinvoice_id(rs.getInt("invoice_id"));
demoList.add(res);
}
String jsonString = getJSONStringFromObject(demoList);
resp.setContentType("application/json");
try {
resp.getWriter().write(jsonString);
File files=new File("D:\\\\hrcsummerinternship\\\\src\\\\assets\\\\json\\\\searchoutput.json");
files.delete();
FileWriter file=new FileWriter("D:\\hrcsummerinternship\\src\\assets\\json\\searchoutput.json");
file.write(jsonString);
file.close();
} catch (IOException e) {
e.printStackTrace();
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
private String getJSONStringFromObject(List<Response> filmlist) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(filmlist);
//System.out.print(json);
return json;
}
}
Folder Structure
Console output
I have also used axios, but to no avail. Please Help

getting a servlet to print from a csv file to an xhtml page/PluginExecutionException

I need to pull data from a csv file that is on my computer and print it to a web page via a servlet. The data needs to read one line at a time and refresh every second, then when it hits the end of the csv file, start again at the top. I feel like I'm close, but when I try to build the program nothing outputs to the web page. It's highly possible that something is misplaced in the code. Any help you can give would be greatly appreciated, I completely suck at programming and am just trying to get through this class. I have added code from all 3 parts. I am using netbeans IDE 8.2 and glassfish server.
main.xthml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Ivan's HTTP ETF</title>
<link rel="stylesheet" type="text/css" href="resources/css/default.css" />
<script type="text/javascript">
var ajaxRequest;
function updatePage() {
if (ajaxRequest.readyState === 4) {
var arraypv = ajaxRequest.responseText.split("/");
document.getElementById("date").innerHTML = arraypv[0];
document.getElementById("time").innerHTML = arraypv[1];
document.getElementById("price").innerHTML = arraypv[2];
document.getElementById("volume").innerHTML = arraypv[3];
document.getElementById("52-weekHigh").innerHTML = arraypv[4];
document.getElementById("52-weekLow").innerHTML = arraypv[5];
makeAjaxRequest();
}
}
function makeAjaxRequest() {
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = updatePage;
ajaxRequest.open("GET", "http://localhost:8080/dukeetf/dukeetf", true);
ajaxRequest.send(null);
}
</script>
</head>
<body onload="makeAjaxRequest();">
<h1>Ivan's HTTP ETF</h1>
<table>
<tr>
<td align="left">Ticker</td>
<td align="right">IGH</td>
</tr>
<tr>
<td align="left">Date</td>
<td id="date" align="right">--</td>
</tr>
<tr>
<td align="left">Time</td>
<td id="time" align="right">--</td>
</tr>
<tr>
<td align="left">Price</td>
<td id="price" align="right">--</td>
</tr>
<tr>
<td align="left">Volume</td>
<td id="volume" align="right">--</td>
</tr>
<tr>
<td align="left">52-weekHigh</td>
<td id="weekHigh" align="right">--</td>
</tr>
<tr>
<td align="left">52-weekLow</td>
<td id="weekLow" align="right">--</td>
</tr>
</table>
</body>
</html>
DukeETFServlet.java:
package javaeetutorial.web.dukeetf;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(urlPatterns={"/dukeetf"}, asyncSupported=true)
public class DukeETFServlet extends HttpServlet {
private static final Logger logger = Logger.getLogger("DukeETFServlet");
private static final long serialVersionUID = 2114153638027156979L;
private Queue<AsyncContext> requestQueue;
#EJB private PriceVolumeBean pvbean;
#Override
public void init(ServletConfig config) {
/* Queue for requests */
requestQueue = new ConcurrentLinkedQueue<>();
/* Register with the bean that provides price/volume updates */
pvbean.registerServlet(this);
}
/* PriceVolumeBean calls this method every second to send updates */
public void send(String date, String time, String price, String volume, String weekHigh, String weekLow) {
/* Send update to all connected clients */
requestQueue.forEach((acontext) -> {
try {
String msg = String.format(date, time, price, volume, weekHigh, weekLow);
PrintWriter writer = acontext.getResponse().getWriter();
writer.write(msg);
logger.log(Level.INFO, "Sent: {0}", msg);
/* Close the connection
* The client (JavaScript) makes a new one instantly */
acontext.complete();
} catch (IOException ex) {
logger.log(Level.INFO, ex.toString());
}
});
}
/* Service method */
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html");
/* Put request in async mode. */
final AsyncContext acontext = request.startAsync();
/* Remove from the queue when done */
acontext.addListener(new AsyncListener() {
#Override
public void onComplete(AsyncEvent ae) throws IOException {
requestQueue.remove(acontext);
logger.log(Level.INFO, "Connection closed.");
}
#Override
public void onTimeout(AsyncEvent ae) throws IOException {
requestQueue.remove(acontext);
logger.log(Level.INFO, "Connection timeout.");
}
#Override
public void onError(AsyncEvent ae) throws IOException {
requestQueue.remove(acontext);
logger.log(Level.INFO, "Connection error.");
}
#Override
public void onStartAsync(AsyncEvent ae) throws IOException { }
});
/* Add to the queue */
requestQueue.add(acontext);
logger.log(Level.INFO, "Connection open.");
}
}
PriceVolumeBean.java:
package javaeetutorial.web.dukeetf;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/* Updates price and volume information every second */
#Startup
#Singleton
public class PriceVolumeBean {
private static final Logger logger = Logger.getLogger("PriceVolumeBean");
private final String csvFile = "/Users/ivanhurdimac/glassfish5/docs/javaee-tutorial/examples/web/servlet/dukeetf/project4input.csv";
/* Use the container's timer service */
#Resource TimerService tservice;
private BufferedReader reader = null;
private DukeETFServlet servlet;
#PostConstruct
public void init() {
try {
reader = new BufferedReader(new FileReader(csvFile));
} catch (IOException e) {
throw new RuntimeException("Failed to read the CSV file [" + csvFile + "].", e);
}
/* Intialize the EJB and create a timer */
logger.log(Level.INFO, "Initializing EJB.");
tservice.createIntervalTimer(1000, 1000, new TimerConfig());
}
public void registerServlet(DukeETFServlet servlet) {
/* Associate a servlet to send updates to */
this.servlet = servlet;
}
#Timeout
public void timeout() {
String line;
try {
line = reader.readLine();
// Once we are done, just return
if (line == null) {
return;
}
} catch (IOException e) {
throw new RuntimeException("Failed to read a line from the CSV file [" + csvFile + "].", e);
} finally {
if (reader != null){
try{
reader.close();
}catch (IOException e){
throw new RuntimeException("CSV file didn't close [" + csvFile + "].", e);
}
}
}
String[] parts = line.split(",");
/* Adjust price and volume and send updates */
String date = parts[0];
String time = parts[1];
String price = parts[2];
String volume = parts[3];
String weekHigh = parts[4];
String weekLow = parts[5];
if (servlet != null) {
servlet.send(date, time, price, volume, weekHigh, weekLow);
}
}
}

Image not refreshing in JSP java dynamic web project

Building a web application where the user can search a word and a relevant image will be returned. But whenever the query is changed, the image does not. What is going on here?
User searches "cat" and image comes back. But then stays like this after the first query.
DefineWord.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="googleAPI.*" %>
<!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>Define</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-lightbox.min.css">
<link rel="stylesheet" href="css/bootstrap-lightbox.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/includeNAV.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<style>
.fit_image img {
max-width: 100%;
max-height: 100%;
}
.fit_image {
width: 400px;
height: 200px;
}
</style>
</head>
<body>
<div id="includedNav"></div>
<div class="container">
<form id="searchForm" method="get" action="LinkServlet">
<fieldset>
<input id="s" type="text" name="query" /> <input type="submit"
value="Submit" id="submitButton" />
</fieldset>
</form>
</div>
<br />
<!-- Requests attributes from servlet -->
<div class="container">
<%-- <%=request.getAttribute("links") %> --%>
<br /> ONE LINK:
<div class="fit_image">
<img src="<%=request.getAttribute("onelink")%>"/>
</div>
</div>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script
src="//blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js"></script>
<script src="js/bootstrap-image-gallery.min.js"></script>
</body>
</html>
LinkServlet.java
package googleAPI;
import java.io.IOException;
import java.util.ArrayList;
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;
#WebServlet("/LinkServlet")
public class LinkServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LinkServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.removeAttribute("onelink");
// Get query from user through http parameter
String query = request.getParameter("query");
String results = google.psuedomain(query);
// Put results string into a ArrayList so that the jsp can dynamically
// call each image
String[] urlAry = results.split("\n");
ArrayList<String> ar = new ArrayList<String>();
ar.clear();
ar.removeAll(ar);
for (int i = 0; i < urlAry.length; i++) {
ar.add(urlAry[i]);
}
// Get first element from ArrayList and set attribute
String onelink = ar.get(0);
request.setAttribute("onelink", onelink);
// Set query results to attribute so JSP can call it
request.setAttribute("links", ar);
// Forward request back to the same JSP.
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/DefineWord.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
google.java
package googleAPI;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Pattern;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
public class google {
static StringBuilder results = new StringBuilder();
static String finalResults;
public static String getFinalResults() {
return finalResults;
}
public static void setFinalResults(String finalResults) {
google.finalResults = finalResults;
}
public static String psuedomain(String qry) throws IOException {
String key = "*********private key************";
URL url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key
+ "&cx=*********private key************&q=" + qry + "&alt=json");
// CONNECTION LOGIC
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
Pattern pattern = Pattern.compile("(?:(?:https?)+\\:\\/\\/+[a-zA-Z0-9\\/\\._-]{1,})+(?:(?:jpe?g|png|gif))");
Matcher matcher = pattern.matcher(output);
if (matcher.find()) {
results.append(matcher.group() + "\n");
}
}
conn.disconnect();
finalResults = removeDup();
return finalResults;
}
public static String removeDup() {
String[] tokens = results.toString().split("\n");
StringBuilder resultBuilder = new StringBuilder();
Set<String> alreadyPresent = new HashSet<String>();
boolean first = true;
for (String token : tokens) {
if (!alreadyPresent.contains(token)) {
if (first)
first = false;
else
resultBuilder.append("\n");
if (!alreadyPresent.contains(token))
resultBuilder.append(token + "\n");
}
alreadyPresent.add(token);
}
String result = resultBuilder.toString();
return result;
}
}
Any ideas as to why this might be happening? Thanks for your time.
I think the problem had to do with using static methods. I removed the static declarations, changed some code around and it seems to work now.
google2.java
package googleAPI;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Pattern;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
public class google2 {
StringBuilder results = new StringBuilder();
String finalResults;
public String psuedomain(String qry) throws IOException {
String key = "*********private key************";
URL url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key
+ "&cx=*********private key************&q=" + qry + "&alt=json");
// CONNECTION LOGIC
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
Pattern pattern = Pattern.compile("(?:(?:https?)+\\:\\/\\/+[a-zA-Z0-9\\/\\._-]{1,})+(?:(?:jpe?g|png|gif))");
Matcher matcher = pattern.matcher(output);
if (matcher.find()) {
results.append(matcher.group() + "\n");
}
}
conn.disconnect();
finalResults = removeDup();
return finalResults;
}
public String removeDup() {
String[] tokens = results.toString().split("\n");
StringBuilder resultBuilder = new StringBuilder();
Set<String> alreadyPresent = new HashSet<String>();
boolean first = true;
for (String token : tokens) {
if (!alreadyPresent.contains(token)) {
if (first)
first = false;
else
resultBuilder.append("\n");
if (!alreadyPresent.contains(token))
resultBuilder.append(token + "\n");
}
alreadyPresent.add(token);
}
String result = resultBuilder.toString();
return result;
}
public String finalResults(String query){
try {
psuedomain(query);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return finalResults;
}
}
Link2Servlet.java
package googleAPI;
import java.io.IOException;
import java.util.ArrayList;
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;
#SuppressWarnings("serial")
#WebServlet("/Link2Servlet")
public class Link2Servlet extends HttpServlet {
public Link2Servlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String query = request.getParameter("query");
google2 google = new google2();
String test = google.finalResults(query);
String[] urlAry = test.split("\n");
ArrayList<String> ar = new ArrayList<String>();
for (int i = 0; i < urlAry.length; i++) {
ar.add(urlAry[i]);
}
request.setAttribute("onelink", ar.get(0));
request.setAttribute("links", ar);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/DefineWord.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}

JSP- unable to insert record using JSP Beans [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I am trying to insert college name into database using beans following MVC pattern but whenever I click on insert button I got 404 error. Here is the code
JSP File
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Practical 5</title>
</head>
<body>
<h1>Insert College</h1>
<form action="NewServlet">
Enter Name<input type="text" name="collegeName"><br>
Enter City<input type="text" name="collegeCity"><br>
Enter Year<input type="number" name="collegeYear"><br>
Enter Fees<input type="number" name="collegeFees"><br>
<input type="submit" name="Insert" value="Insert">
</form>
<%
String msg=(String)request.getAttribute("msg");
%>
<h2><%=msg%></h2>
</body>
</html>
CollegeBean.java
package college;
public class CollegeBean {
public String cname;
public String ccity;
public int year;
public float fees;
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCcity() {
return ccity;
}
public void setCcity(String ccity) {
this.ccity = ccity;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public float getFees() {
return fees;
}
public void setFees(float fees) {
this.fees = fees;
}
}
CollegeDB.java
package college;
import java.sql.*;
public class CollegeDB {
public String insertOperation(CollegeBean collegeBeanObj) throws ClassNotFoundException,SQLException
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn= DriverManager.getConnection("jdbc:mysql://localhost/jspractical5", "root", "");
Statement st= cn.createStatement();
int flag= st.executeUpdate("INSERT INTO college (c_name, c_city, c_year, c_fees) VALUES('"+collegeBeanObj.getCname()+"','"+collegeBeanObj.getCcity()+"','"+collegeBeanObj.getYear()+"','"+collegeBeanObj.getFees()+"')");
if (flag!=0)
return "Record Inserted";
else
return "Record not inserted";
}
}
Finally the controller file the servlet to handle all the stuff
NewServlet.java
package college;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
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;
#WebServlet(name = "NewServlet", urlPatterns = {"/college/NewServlet"})
public class NewServlet extends HttpServlet {
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("name");
String city=request.getParameter("city");
int year=Integer.parseInt(request.getParameter("year"));
float fees=Integer.parseInt(request.getParameter("fees"));
CollegeBean collegeBeanObj= new CollegeBean();
collegeBeanObj.setCname(name);
collegeBeanObj.setCcity(city);
collegeBeanObj.setYear(year);
collegeBeanObj.setFees(fees);
CollegeDB cd= new CollegeDB();
String msg= cd.insertOperation(collegeBeanObj);
request.setAttribute("msg", msg);
RequestDispatcher rd= getServletContext().getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
catch(Exception e)
{
out.println(e);
}
}
#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";
}
}
The problem is with the line in the controller where you assign the RequestDipatcher.
May be the file path of index.html is wrong. Check the folder structure and insert the path accordingly. If the index.html is in same directory of the page where request is sent then in the file path of index.html, remove the leading '/'.
Also change the form action attribute URL to same URL pattern defined in urlPattrns in the controller annotation "/college/NewServlet"

Categories

Resources