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 {
}
}
Related
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
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);
}
}
}
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.
index.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML5 drag'n'drop file upload with Servlet</title>
<script>
window.onload = function() {
var dropbox = document.getElementById("dropbox");
dropbox.addEventListener("dragenter", noop, false);
dropbox.addEventListener("dragexit", noop, false);
dropbox.addEventListener("dragover", noop, false);
dropbox.addEventListener("drop", dropUpload, false);
}
function noop(event) {
event.stopPropagation();
event.preventDefault();
}
function dropUpload(event) {
noop(event);
var files = event.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
upload(files[i]);
}
}
function upload(file) {
document.getElementById("status").innerHTML = "Uploading " + file.name;
var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.open("POST", "uploadServlet", false); // If async=false, then you'll miss progress bar support.
xhr.send(formData);
}
function uploadProgress(event) {
// Note: doesn't work with async=false.
var progress = Math.round(event.loaded / event.total * 100);
document.getElementById("status").innerHTML = "Progress " + progress + "%";
}
function uploadComplete(event) {
document.getElementById("status").innerHTML = event.target.responseText;
}
</script>
<style>
#dropbox {
width: 300px;
height: 200px;
border: 1px solid gray;
border-radius: 5px;
padding: 5px;
color: gray;
}
</style>
</head>
<body>
<div id="dropbox">Drag and drop a file here...</div>
<div id="status"></div>
</body>
</html>
uploadServlet.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package officer;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class uploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// Apache Commons-Fileupload library classes
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
if (! ServletFileUpload.isMultipartContent(request)) {
out.println("sorry. No file uploaded");
return;
}
else
{
// parse request
List items = sfu.parseRequest(request);
FileItem file = (FileItem) items.get(0);
String type=file.getContentType();
float size=file.getSize()/1024;
if((type.equals("image/jpeg"))&& ((size <201)&&(size>10)))
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "epolicia", "admin");
con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement("insert into image(image) values(?)");
ps.setBinaryStream(1, file.getInputStream(), (int) file.getSize());
ps.executeUpdate();
con.commit();
con.close();
out.println("Proto Added Successfully. <p> <a href='ListPhotoServlet'>List Photos </a>");
}
else
{
out.print("Invalid Image Selected !!");
}
}
}
catch(Exception ex) {
out.println( "Error --> " + ex.getMessage());
}
}
}
Above code is just simply inserting the image into database. But, i want to insert the image on the basis of userid. Then, what should i change in my code. Need help to pass the userid when image will be dropped into the box. Thanks in advance !!
I tested this in Chrome browser.
In your script;
formData.append("file", file);
// if userid is in your script
fd.append("userid", userid);
// or if userid is at server, then send it to browser first
// fd.append("userid", <%=userid%>);
In UploadServlet;
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
String userid = item.getString();
else //its the file
...
I need to import contacts to the enable my web app users to send invitation to his/her friends from my site, I am using SocioAuth Open source API to get this done, I have written 2 servlets to get this done I am pasting the code of my servlet. when I deployed the app in my Ec2 instance, I am getting an exception saying "Key in request token is null or blank in the line number 27 of the NewSocialAuthentication,
package com.auth.actions;
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 org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.AuthProviderFactory;
public class NewSocialAuthentication extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Coming to doGet of NewSocialApp..");
#SuppressWarnings("unused")
PrintWriter out = response.getWriter();
String socialAppId = request.getParameter("id");
System.out.println("SocialAppId: "+socialAppId);
AuthProvider provider;
try {
provider = AuthProviderFactory.getInstance(socialAppId);
String returnToUrl = "http://ec2-50-19-118-108.compute-1.amazonaws.com/SocialAuthNew6/return";
System.out.println("Return URL..." + returnToUrl);
String urlString = provider.getLoginRedirectURL(returnToUrl);
System.out.println("URLString: "+urlString);
request.getSession().setAttribute("SocialAuth", provider);
response.sendRedirect(response.encodeRedirectURL(urlString));
} catch (Exception e) {
System.out.println("Exception...");
e.printStackTrace();
}
}
}
package com.auth.actions;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.Contact;
import org.brickred.socialauth.Profile;
import org.brickred.socialauth.util.*;
public class ReturnServlet extends HttpServlet{
/**
*
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Coming to doGet of Return Servlet..");
try{
AuthProvider provider = (AuthProvider)request.getSession().getAttribute("SocialAuth");//this the line is rising exception
Profile p = provider.verifyResponse(request);
System.out.println(p.getFirstName());
List<Contact> contactsList = provider.getContactList();
for(int i=0;i<contactsList.size();i++){
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println(contactsList.get(i).getFirstName()+" : "+contactsList.get(i).getLastName());
out.println(contactsList.get(i).getFirstName());
out.println(contactsList.get(i).getLastName());
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
This is the servlet which redirects to the email service provider
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 org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.AuthProviderFactory;
/**
* Servlet implementation class NewSocialAuthentication
*/
public class NewSocialAuthentication extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public NewSocialAuthentication() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
#SuppressWarnings("unused")
PrintWriter out = response.getWriter();
String socialAppId = request.getParameter("id");
System.out.println("SocialAppId: "+socialAppId);
AuthProvider provider;
try {
provider = AuthProviderFactory.getInstance(socialAppId);
//String returnToUrl = "http://ec2-50-16-183-101.compute-1.amazonaws.com/SocialAuthNew/return";
String returnToUrl = "u r returning url ";
System.out.println("Return URL..." + returnToUrl);
String urlString = provider.getLoginRedirectURL(returnToUrl);
System.out.println("URLString: "+urlString);
request.getSession().setAttribute("SocialAuth", provider);
response.sendRedirect(response.encodeRedirectURL(urlString));
} catch (Exception e) {
System.out.println("Exception...");
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
the return url would look like this I have embedded in the jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="org.brickred.socialauth.AuthProvider" %>
<%#page import="org.brickred.socialauth.Contact" %>
<%#page import="org.brickred.socialauth.AuthProvider" %>
<%#page import="org.brickred.socialauth.Profile" %>
<%#page import="java.util.*" %>
Insert title here
CONTACT LIST
<%
try{
AuthProvider provider = (AuthProvider)request.getSession().getAttribute("SocialAuth");
try{
System.out.println(provider.getContactList());
}
catch(Exception e){
System.out.println("Exception Encountered..");
}
Profile p = provider.verifyResponse(request);
List contactsList = provider.getContactList();
%>
Hello, <%= p.getFirstName() %>
Contact List
First Name
Email
<%
for(int i=0;i
"/><%= contactsList.get(i).getFirstName() %><%= contactsList.get(i).getEmail() %>
<%
}
%>
</table>
<input type="submit" value="GET CONTACTS"/>
</form>
<%
}
catch(Exception e){
e.printStackTrace();
}
%>