This question already has answers here:
How to retrieve and display images from a database in a JSP page?
(6 answers)
Closed 5 years ago.
Please help me in displaying image in a particular section on a JSP page which is stored in mySql database and also tell me that can we store image in any datatype?
Web pages display images from URLs.
You can either encode the image in a data: URI, or write server-side code to serve it in response to some URL.
add this servlet to your project like this :
package com.app.meservlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import com.app.upload.UploadPicture;
/**
*
* #author user-sqli date: 12/05/2016 17:42
*/
#WebServlet(urlPatterns = "/upload", loadOnStartup = 1)
#MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50)
// 50MB
public class ControllerUploadPicture extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String appPath = request.getServletContext().getRealPath("");
Part part = request.getPart("file");
UploadPicture.createNewInstance().TranseferPicture(part, appPath);
getServletContext().getRequestDispatcher("/show.jsp").forward(request,
response);
}
}
and add this classto your project :
package com.app.upload;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.Part;
/**
*
* #author user-sqli date: 12/05/2016 17:30
*/
public class UploadPicture {
private static final String EXTENSION = ".";
public static final String SAVE_DIR = "uploadImage";
private static UploadPicture uploadPicture = null;
private static final Logger LOGGER = Logger.getLogger(UploadPicture.class
.getName());
private UploadPicture() {
}
public String TranseferPicture(Part part, String appPath) {
String savePath = appPath + File.separator + SAVE_DIR;
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String nameImage = fileName + EXTENSION + getExtensionImage(part);
try {
part.write(savePath + File.separator + nameImage);
LOGGER.log(Level.FINE, "Upload Picture to {0} ", savePath
+ File.separator + nameImage);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, ex.toString(), ex);
}
return nameImage;
}
private String getExtensionImage(Part part) {
return part.getContentType().split("/")[1];
}
public static UploadPicture createNewInstance() {
if (uploadPicture == null) {
uploadPicture = new UploadPicture();
}
return uploadPicture;
}
}
in your jsp like this :
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload file</title>
</head>
<body>
<form method="post" action="upload" enctype="multipart/form-data">
<input type="file" name="file" /><br /> <input type="submit"
value="Upload" />
</form>
</body>
</html>
and for shoing this image :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
uploaded image sucess.
<%-- <img width="100px" height="100px" src="<c:url value="/uploadImage/${name}" />"> --%>
</body>
</html>
this example require servlet >=3.1
Related
What I am trying to do is a blog page with jsp. For this purpose, I save the content of blogs in an html file. I am using a jsp file to update the content in the existing html file via the browser. I used the textarea tag in a jsp file to edit this html file through the browser. There is no encoding problem in the html content transferred to the textarea. But when I make changes to the html file and save it, the utf-8 characters turn out to be incorrect. For Example:
The html file is read and placed comfortably in the textarea without any encoding problems
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Evrim Üzerine Notlar</h1>
</body>
</html>
When i submit for save it:
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Evrim Ãzerine Notlar</h1>
</body>
</html>
There is the classes and jsp files:
setBlog.jsp (Html file is setting in this file)
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<jsp:include page="navbar.jsp"/>
<form action="adminBlogProcess?meth=update" method="post">
id:<input type="text" readonly="readonly" value="${setMe.textId}" name="tid">
<label>Text Title</label>
<input type="text" name="name" class="form-control" value="${setMe.name}"/>
<label>File Path</label>
<input type="text" name="textPath" class="form-control" value="${setMe.textPath}"/>
<label>Kategori</label>
<select class="form-control" name="selectedCategory">
<c:forEach items="${loc}" var="val">
<option value="${val.categoryId}">${val.categoryName}</option>
</c:forEach>
</select>
<label>İçerik:</label>
<textarea class="form-control" name="content" rows="100">${contentOfDoc}</textarea>
<input type="submit" class="btn btn-primary" value="Save Changes">
</form>
</body>
</html>
AdminBlogProcess.java
package Controller;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DataAccess.CategoryDao;
import DataAccess.TextDao;
import Model.Category;
import Model.Text;
#WebServlet("/adminBlogProcess")
public class AdminBlogProcess extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -7693704779591981580L;
private CategoryDao cd;
private TextDao td;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String meth = req.getParameter("meth");
String msg="";
if (meth.equalsIgnoreCase("update")) {
update(req);
msg="Yazı Güncellendi!";
} else if (meth.equalsIgnoreCase("add")) {
} else if (meth.equalsIgnoreCase("delete")) {
}
req.setAttribute("message", msg);
req.getRequestDispatcher("/admin/admin.jsp").forward(req, resp);
}
//This update method is write new content into the html file
private void update(HttpServletRequest req) {
String name=req.getParameter("name");
String textPath=req.getParameter("textPath");
int id=Integer.valueOf(req.getParameter("tid"));
Category ct=getCd().getCategoryById(Integer.valueOf(req.getParameter("selectedCategory")));
Text txt=new Text(name, textPath, ct, id);
getTd().update(txt);
String content=req.getParameter("content");
String path="C:\\Users\\90551\\Desktop\\Eclipse Projeler\\2022 Yaz-Haziran Arsiv\\JAVA SERVER PAGES\\004BlogSitesi\\src\\main\\webapp\\texts\\"+textPath;
try (FileWriter fw = new FileWriter(new File(path), StandardCharsets.UTF_8);
BufferedWriter bw = new BufferedWriter(fw)){
bw.write("");
bw.append(content);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public CategoryDao getCd() {
if (cd == null) {
cd = new CategoryDao();
}
return cd;
}
public void setCd(CategoryDao cd) {
this.cd = cd;
}
public TextDao getTd() {
if (td == null) {
td = new TextDao();
}
return td;
}
public void setTd(TextDao td) {
this.td = td;
}
}
What should i do for fix that encodin problem?
bookReg.jsp
<%#page import="classes.BooksDTO"%>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link type="text/css" href="css/mainStyle.css">
</head>
<body>
<%
//D:\Hayden\учеба\джава\JavaBigData\readers\WebContent\img - folder directory
%>
<form action="bookRegProc.jsp" method="post" enctype="multipart/form-data">
Title <input type="text" name="title"> <br>
Plot <textarea rows="30" cols="40" name="plot"></textarea> <br>
<input type="hidden" name="rating" value="0"> <br>
Author <input type="text" name="author"> <br>
Publisher <input type="text" name="publisher"> <br>
Genre <input type="text" name="genre"> <br>
Publication date <input type="text" name="date"> <br>
Cover <input type="file" name="cover" size="50"> <br>
<input type="submit" value="Register"> <br>
</form>
</body>
</html>
bookRegProc.jsp
<%#page import="classes.Uploader"%>
<%#page import="org.apache.commons.fileupload.FileItem"%>
<%#page import="java.util.Iterator"%>
<%#page import="java.util.List"%>
<%#page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%#page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%#page import="java.io.File"%>
<%#page import="classes.BooksDTO"%>
<%#page import="classes.BooksDAO"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Uploader upload = new Uploader();
upload.doPost(request, response);
%>
</body>
</html>
Uploader.java
package classes;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class Uploader extends HttpServlet {
BooksDTO dto = null;
BooksDAO dao = new BooksDAO();
String title = null;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String title = request.getParameter("title"); // Retrieves <input type="text" name="description">
String plot = request.getParameter("plot");
String rating = request.getParameter("rating");
String author = request.getParameter("author");
String publisher = request.getParameter("publisher");
String genre = request.getParameter("genre");
String date = request.getParameter("date");
Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
/*String fileName = title;
InputStream fileContent = filePart.getInputStream();*/
// ... (do your job here)
//DTO process
BooksDTO dto = new BooksDTO();
BooksDAO dao = new BooksDAO();
dto.setTitle(title);
dto.setAuthor(author);
dto.setDate(date);
dto.setGenre(genre);
dto.setPlot(plot);
dto.setPublisher(publisher);
dto.setRating(rating);
try {
dao.insert(dto);
//this inserts all the parameters into database
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//File process
File file;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
String filePath = "D:/Hayden/Eclipse workspace/bigdata/readers/WebContent/img/";
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(maxMemSize);
factory.setRepository(new File("C:/temp"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxFileSize);
try {
FileItem fi = (FileItem) filePart;
if(!fi.isFormField()) {
file = new File(filePath + dto.getTitle() + ".jpg");
fi.write(file);
}
}catch(Exception ex) {
System.out.println(ex);
}
}
}
I want to pass text parameters from bookReg.jsp to register it in my database.
I checked the methods for inserting into database works totally fine.
but in doPost method, Uploader.java, request.getParameter passes null to each String.
I searched how to pass text to a servlet for days and I finally followed this instruction : How to upload files to server using JSP/Servlet? (first answer)
but it still passes null only.
what is the difference between passing parameter using request.getParameter in jsp and in a java class as I wrote?
and what is causing the same problem even if I followed the instruction of the first answer in the page that I followed?
(I am using tomcat 8.5 and eclipse oxygen)
I'm creating a JSP/Servlet web application and I'd like to upload a file to a Servlet with progress bar.
This is an example of uploading file with jsp and servlet.
Its working but i want to add to it a progress bar.
The FileUploadHandler.java
import java.io.File;
import java.io.IOException;
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;
/**
* Servlet to handle File upload request from Client
* #author Javin Paul
*/
public class FileUploadHandler extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private final String UPLOAD_DIRECTORY = "uploads";
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uploadPath = getServletContext().getRealPath("")
+ File.separator + UPLOAD_DIRECTORY;
String name = null;
//process only if its multipart content
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
name = new File(item.getName()).getName();
item.write( new File(uploadPath+name));
}
}
//File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully "+uploadPath+ name);
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}else{
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
The upload.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>File Upload Example in JSP and Servlet - Java web application</title>
</head>
<body>
<div>
<h3> Choose File to Upload in Server </h3>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="upload" />
</form>
</div>
</body>
</html>
The result.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>File Upload Example in JSP and Servlet - Java web application</title>
</head>
<body>
<div id="result">
<h3>${requestScope["message"]}</h3>
</div>
</body>
</html>
The web.xml
<servlet>
<servlet-name>FileUploadHandler</servlet-name>
<servlet-class>FileUploadHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadHandler</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
Though late, try using following plugin, which makes your UI beautiful and super easy.
https://github.com/blueimp/jQuery-File-Upload
Java examples are as follows:
https://github.com/blueimp/jQuery-File-Upload/wiki
This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 6 years ago.
so all i want t do is a simple form which transfer text and image. For now, i can't do both at the same time !
Here is a simple form code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<center>
<h1>File Upload</h1>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<input type="text" name="CaptionBox" />
<input type="file" name="photo" />
<input type="submit" />
</form>
</center>
</body>
</html>
This code give me this error:
java.io.IOException: java.io.FileNotFoundException: C:\Users\poste hp\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\maroc_events\uploadFiles (Access denied)
But if a put away the text input and let only the file input, it works! And i can't figure out why !
Here is the servlet code:
#WebServlet("/UploadServlet")
#MultipartConfig
public class UploadServlet extends HttpServlet{
/**
* Name of the directory where uploaded files will be saved, relative to
* the web application directory.
*/
private static final String SAVE_DIR = "uploadFiles";
/**
* handles file upload
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
EventUtil.addImage(request);
request.setAttribute("message", "Upload has been done successfully!");
getServletContext().getRequestDispatcher("/message.jsp").forward(
request, response);
}
}
And finally the Eventutil class:
package com.utils;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
public class EventUtil {
private static final String SAVE_DIR = "uploadFiles";
public static void addImage(HttpServletRequest request) throws IOException, ServletException{
String appPath = request.getServletContext().getRealPath("");
// constructs path of the directory to save uploaded file
String savePath = appPath + File.separator + SAVE_DIR;
System.out.println(savePath);
// creates the save directory if it does not exists
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
part.write(savePath + File.separator + fileName);
}
}
private static String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
}
Thanks !
Edit:
StackTrace:
java.io.FileNotFoundException: C:\Users\poste hp\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\maroc_events\uploadFiles (Accès refusé)
java.io.FileOutputStream.open(Native Method)
java.io.FileOutputStream.<init>(Unknown Source)
java.io.FileOutputStream.<init>(Unknown Source)
org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.write(DiskFileItem.java:394)
com.utils.EventUtil.addImage(EventUtil.java:28)
com.servlets.UploadServlet.doPost(UploadServlet.java:54)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
The write() method throws the error because ...\maroc_events\uploadFiles is a directory, and you cannot write to a directory.
You can write to a file in that directory, but that would require a filename. Very likely, fileName is blank.
Not sure, but I believe getParts() also return non-file parts, which means it also returns a part for the CaptionBox field. Try printing part.getName() to check.
Since you only expect one file anyway, use request.getPart("photo") instead of looping.
Building a web application that uses google custom search API to fetch images related to the users search query. So if you search "cheese", you will get back images that are cheese related.
Here is an example of what it currently looks like:
There are two main problems.
Why are all the query results being stored in the first index of my ArrayList? I only want one link for the moment.
How could i get these links to display images?
Currently there are three pieces of code for this. a JSP, a Servlet and a Java class.
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>
</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:
<%=request.getAttribute("onelink") %>
</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.io.PrintWriter;
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 {
// Get query from user through http parameter
PrintWriter printWriter = response.getWriter();
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
printWriter.println(results);
String[] urlAry = results.split(" ");
ArrayList<String> ar = new ArrayList<String>();
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 = "*********privatekey*********";
URL url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key
+ "&cx=*********privatekey*********&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?
Thanks for your time.
In the LinkServlet.java file, the doGet method, you split the google.psuedomain answer with a space " ", but they where concatenated using a new line "\n". So, either split on new line or change the concatenation to use a space. Even better, why don't you return an ArrayList of String with the google.psuedomain method ?
To display all the links as images, use a foreach block in which you add an imgtag with the src attribute set to the current link.