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
Related
This question already has answers here:
Java URL encoding of query string parameters
(11 answers)
Closed 5 years ago.
I wrote the netbeans ta web service project. But when I write "50% discount" to the value of a parameter I use with http post, it looks like "P discount" to me. How can I fix this problem?
192.168.0.222:7001/Project/KonuEkle?uye=test&&baslik=%50 discount&&mesaj=test&&kategori=123&&link=null
import com.mrkcn.servlet.Classlar.ConnectInfo;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
public class KonuEkleServlet extends HttpServlet {
public String kullaniciadi;
public String baslik;
public String mesaj;
public String kategori;
public String altKategori;
public String link;
public Connection con;
boolean action = false;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
ConnectInfo conServlet= new ConnectInfo();
con=null;
con=conServlet.baglanti();
PreparedStatement pstmt=null;
ResultSet rs=null;
Boolean konuEkleKontrol = false;
PrintWriter out = resp.getWriter();
JSONObject j = new JSONObject();
ArrayList<String> konuEkleList = new ArrayList<String>(100);
kullaniciadi = req.getParameter("uye");
baslik = req.getParameter("baslik");
mesaj = req.getParameter("mesaj");
kategori = req.getParameter("kategori");
link = req.getParameter("link");
j.put("mesaj1",baslik);
//altKategori = req.getParameter("altkategori");
//kategoriBilgiGetir(kategori , altKategori);
String konuEkle="insert into konular(uye,baslik,mesaj,kategori,tarih,edittarih,aktif,indirimpuani,altkategori,link) values (?,?,?,?,GETDATE(),NULL,1,0,0,?)";
pstmt=con.prepareStatement(konuEkle);
pstmt.setString(1, kullaniciadi);
pstmt.setString(2, baslik);
pstmt.setString(3, mesaj);
pstmt.setString(4, kategori);
pstmt.setString(5, link);
int count = pstmt.executeUpdate();
action = (count > 0);
if (action)
{
j.put("mesaj","basarili");
konuEkleList.add(j.toString());
out.write(konuEkleList.toString());
out.close();
}
else
{
j.put("mesaj","basarisiz");
konuEkleList.add(j.toString());
out.write(konuEkleList.toString());
out.close();
}
} catch (SQLException ex) {
Logger.getLogger(KonuEkleServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (JSONException ex) {
Logger.getLogger(KonuEkleServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
URLs are treated as encoded when received by the servlet. The % symbol followed by a 2 hex digits is the ASCII code of the character so %50 represents the letter P. To represent the % symbol you have to send %25 to represent the % symbol.
Your URL should be:
192.168.0.222:7001/Project/KonuEkle?uye=test&&baslik=%2550 discount&&mesaj=test&&kategori=123&&link=null
Here you can find a list of the character codes:
https://www.w3schools.com/tags/ref_urlencode.asp
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 {
}
}
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.
i managed to store an image in my mysql database as Blob. (i am also using hibernate)
now i am trying to load that image and send it on a jsp page so the user can view the image.
This is my struts 2 action class
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Blob;
import org.hibernate.Hibernate;
import domain.post.image.Image;
public class FileUploadAction {
private File file;
#SuppressWarnings("deprecation")
public String execute() {
try {
System.out.println(file.getPath());
Image image = new Image();
FileInputStream fi = new FileInputStream(file);
Blob blob = Hibernate.createBlob(fi);
image.setImage(blob);
image.save();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
and this is my Image class
public class Image extends AbsDBObject<Object> {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(Image.class);
private Blob image;
private String description;
//Getters and Setters
}
would you please tell me what should i put in an action class, jsp page and struts.xml in order to showing the stored image?
Finally I solved it, for future googlers :
Add this line to jsp,
<img src="<s:url value="YourImageShowAction" />" border="0"
width="100" height="100">
and this is ShowImageAction class : note that the execute method is void, so no redirection
import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.raysep.maxlist.domain.post.image.Image;
public class ShowImageAction {
private static byte[] itemImage;
public static void execute() {
try {
Image slika = Image.fetchOne();
HttpServletResponse response = ServletActionContext.getResponse();
response.reset();
response.setContentType("multipart/form-data");
itemImage = slika.getImage().getBytes(1,(int) slika.getImage().length());
OutputStream out = response.getOutputStream();
out.write(itemImage);
out.flush();
out.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public byte[] getItemImage() {
return itemImage;
}
public void setItemImage(byte[] itemImage) {
this.itemImage = itemImage;
}
}
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();
}
%>