Setting image from database - java

I am trying to get the image stored in the MYSQL database and set it on a JSP page, but I am getting the following error:
Servlet.service() for servlet [SearchStudentControlling] in context
with path [/Roomantech] threw exception
[java.lang.IllegalStateException: getOutputStream() contain error so i
didn,t the image in my jsp page
I am using the following code to get and set the image. I am getting the error on line number 339 which doesn't exist (my code has only 312 lines). I have been struggling for last two hours but couldn't pinpoint the problem.
session = request.getSession(false);
if(session!=null)
{
%>
<div style="width:100%;height:70%;">
<%#include file="header.jsp"%>
<div align="center" style="margin-top:150px">
<table align="center" width="73%;" height="100%;" class="abc">
<form action="nextpersonalinformation.do" method="post">
<strong><h2 style="color: darkblue;margin-bottom:30px;"><b><u>Person Information****</b></u></h2></strong>
<tr><td></td><td></td></tr>
<tr style="background-color: #003366;color: white;border-radius:5px"><td><h4 style="color: darkblue"><b style="color: white"> Your Hostel details****:</b></h4></td><td><b style="color: white">Enter Values:</b></td></tr>
<tr><td></td><td></td></tr>
<tr style="background-color: teal;font-size: 20px"></tr>
<%
ArrayList<PersonDetaildto>pa = (ArrayList<PersonDetaildto>)session.getAttribute("InformationPerson");
for(PersonDetaildto kk : pa)
{
System.out.println(kk.getFirst_nm()+" "+kk.getMiddle_nm());
%>
<tr>
<td>Person Image</td>
<td><img height="75px" width="75px" align="left" src="
<% byte[] imgbytes = kk.getPerson_image();
InputStream images = kk.getPersonimagee();
int size1=0;
response.reset();
response.setContentType("image/jpeg");
response.addHeader("Content-Disposition","filename=logo.jpg");
while((size1=images.read(imgbytes))!= -1 )
{
response.getOutputStream().write(imgbytes,0,size1);
}
response.flushBuffer();
images.close();
%>"/></td>
</tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr>
</table>
</div>
<div style="width:100%;height:200px;">
</div>
<%
}
}
else
{
response.sendRedirect("welcome.do");
}
%>
<%#include file="footer.jsp"%>
</body>
</html>

EDIT:
You cannot add images by inserting the bytes into HTML (as Funtik already pointed out).
But you can insert it by converting your image-bytes into Base64:
<img alt="YourEmbeddedImage" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgkAAAJNCAIAAAA0yXHVAAAACXBIWXMA..." />

As #Ben pointed out, you can output the bytes of an image inside your src tag by encoding it in base64.
But still, I advice you to use another solution for your problem.
A better solution would be to store the images on the hard drive, but keep the filenames inside the database. In this case your solution would be something like:
<td>Person Image</td>
<td><img height="75px" width="75px" align="left" src="<% kk.getPersonimagee() %>"></td>

Related

Replace GET request by POST without form in JSP

So i have this JSP page which having data from table and forming a GET request to render more data on another page , by clicking one of the table line
Problem is i have to transforming it into POST method , to avoid getting information in the http request link
i know how to use post with form, but here i have to take the date from a table line and not a form
Any idea how to do that. i'm new to JSP so i don't know how to do it
<table border=0 bgcolor=#92ADC2 cellspacing=1 cellpadding=3 width=95% align=center>
<tr class=entete>
<td class=texte8 align=center> <spring:message code="nom"/></td>
<td class=texte8 align=center> <spring:message code="date_naissance"/></td>
<td class=texte8 align=center> <spring:message code="numero"/></td>
</tr>
<%
String v_Person = "";
String v_date = "";
String v_numero = "";
for (int i = 0; i < PersonListeBean.getPerson(); i++)
{
Gen_rechBean cb = PersonListeBean.getPerson(i);
v_Person = cb.getname();
v_date=cb.getdate();
v_numero=cb.getNumero();
}
%>
<tr class="<%=class_cell%>" onMouseOver="this.className='over';" onMouseOut="this.className='<%=class_cell%>';" onclick="javascript:parent['gauche'].document.location='ResultServlet?name=<%=v_Person%>&numero=<%=v_numero%>&date_naissance=<%=v_date%>">
<td class=texte7 align=left > <%=cb.getname()%></td>
<td class=texte7 align=left > <%=cb.getdate()%></td>
<td class=texte7 align=left > <%=cb.getNumero()%></td>
</tr>
</table>
<br>
<table width="95%" align="center" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="right">
<a target="corps" href="rechResult.jsp" class="rub2" </a>
</td>
</tr>
</table>
I see what are you trying to do.
The easiest way to do that is using a form. So you can call a js method when you click the
<tr onclick="myMethod()">
that you want.
The method can fill your form and send the submit. Using this you can be redirected without sending data in you url.
A basic example could be:
(Supposing these are elements printed by server-side)
<tr onclick="myMethod(<%=getName()%>, <%=getDate()%>, <%=getNumero()%>)">
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<form id="myForm" action="targetFile.jsp" method="post">
//Hidden inputs to prevent users form touching this fields
<input type="hidden" name="name" id="data1">
<input type="hidden" name="date" id="data2">
<input type="hidden" name="numero" id="data3">
</form>
<script>
function myMethod(data1, data2, data3){
//Im gonna use jQuery. Is like javascript but quite faster to use
//Filling the form
$("#data1").val(data1);
$("#data2").val(data2);
$("#data3").val(data3);
//Submiting it
$("myForm").submit();
}
</script>
Let me know if it was helpful.
c:

jsp paging problem when i go to next page searching keyword doesn't apply

when i search specific word only first page is classified. it shows pages and posts well on first page.
but when i go to page 2 or next page, seaching keyword doesn't apply on
is this address problem?
i guess this is sql or Paging.java problem because when i print log of page at BDAO it shows page well which i clicked.
also I don't know how can i transfer keyWord &keyField for that..!
I use oracle DB.
<%
String keyWord = (String)request.getParameter("keyWord");
String keyField = (String)request.getParameter("keyField");
%>
<script>
function searchCheck(frm){
//검색
if(frm.keyWord.value ==""){
alert("검색 단어를 입력하세요.");
frm.keyWord.focus();
return;
}
frm.submit();
}
function PageMove(page){
var keyWord = '<%=keyWord%>'
var keyField = '<%=keyField%>'
console.log(keyWord);
if(keyWord !=''){
location.href = "list.do?page="+page+"&keyWord=" + keyWord + "&keyField=" + keyField;
}
location.href = "list.do?page="+page;
}
</script>
</head>
<body>
<table width="800" cellpadding="0" cellspacing="0" border="1">
<tr>
<td>번호</td>
<td>이름</td>
<td>제목</td>
<td>날짜</td>
<td>히트</td>
</tr>
<c:forEach items="${list}" var="dto">
<tr>
<td>${dto.bId}</td>
<td>${dto.bName}</td>
<td>
<c:forEach begin="1" end="${dto.bIndent}">-</c:forEach>
${dto.bTitle}</td>
<td>${dto.bDate}</td>
<td>${dto.bHit}</td>
</tr>
</c:forEach>
<tr>
<td colspan="5">
<form action="list.do" method="post" name="search">
<select name="keyField">
<option value="bTitle">글 제목</option>
<option value="bContent">글 내용</option>
<option value="bName">작성자</option>
</select>
<input type="text" name="keyWord">
<input type="button" value="검색" onclick="searchCheck(form)">
</form>
</td>
</tr>
<tr>
<td colspan="5"> 글작성 </td>
</tr>
</table>
<div class="toolbar-bottom">
<div class="toolbar mt-lg">
<div class="sorter">
<ul class="pagination">
<li>맨앞으로</li>
<li>앞으로</li>
<c:forEach var="i" begin="${paging.startPageNo}" end="${paging.endPageNo}" step="1">
<c:choose>
<c:when test="${i eq paging.pageNo}">
<li class="active">${i}</li>
</c:when>
<c:otherwise>
<li>${i}</li>
</c:otherwise>
</c:choose>
</c:forEach>
<li>뒤로</li>
<li>맨뒤로</li>
</ul>
</div>
</div>
</div>
You never seem to be passing the keyword or keyfield when you call pageMove(). You might as well look up their values inside the function instead of having them as parameters:
function PageMove(page){
var keyWord = document.getElementById("keyWord").value;
var keyField = document.getElementById("keyField").value;
location.href = "list.do?page=" + page + "&keyWord=" + keyWord + "&keyField=" + keyField;
}

Modifying HTML using java

I am trying to read a HTML file and add link to some of the texts :
for example :
I want to add link to "Campaign0" text. :
<td><p style="overflow: hidden; text-indent: 0px; "><span style="font-family: SansSerif;">101</span></p></td>
<td><p style="overflow: hidden; text-indent: 0px; "><span style="font-family: SansSerif;">Campaign0</span>
<td><p style="overflow: hidden; text-indent: 0px; "><span style="font-family: SansSerif;">unknown</span></p></td>
Link to be added:
<a href="Second.html">
I need a JAVA program that modify html to add hyperlink over "Campaign0" .
How i do this with Jsoup ?
I tried this with JSoup :
File input = new File("D://First.html");
Document doc = Jsoup.parse(input, "UTF-8", "");
Element span = doc.select("span").first(); <-- this is only for first span tag :(
span.wrap("");
Is this correct ?? It's not working :(
In short : is there anything like-->
if find <span>Campaign0</span>
then replace by <span>Campaign0</span>
using JSoup or any technology inside JAVA code??
Your code seems pretty much correct. To find the span elements with "Campaign0", "Campaign1", etc., you can use the JSoup selector "span:containsOwn(Campaign0)". See additional documentation for JSoup selectors at jsoup.org.
After finding the elements and wrapping them with the link, calling doc.html() should return the modified HTML code. Here's a working sample:
input.html:
<table>
<tr>
<td><p><span>101</span></p></td>
<td><p><span>Campaign0</span></p></td>
<td><p><span>unknown</span></p></td>
</tr>
<tr>
<td><p><span>101</span></p></td>
<td><p><span>Campaign1</span></p></td>
<td><p><span>unknown</span></p></td>
</tr>
</table>
Code:
File input = new File("input.html");
Document doc = Jsoup.parse(input, "UTF-8", "");
Element span = doc.select("span:containsOwn(Campaign0)").first();
span.wrap("");
span = doc.select("span:containsOwn(Campaign1)").first();
span.wrap("");
String html = doc.html();
BufferedWriter htmlWriter =
new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.html"), "UTF-8"));
htmlWriter.write(html);
htmlWriter.close();
output:
<html>
<head></head>
<body>
<table>
<tbody>
<tr>
<td><p><span>101</span></p></td>
<td><p><span>Campaign0</span></p></td>
<td><p><span>unknown</span></p></td>
</tr>
<tr>
<td><p><span>101</span></p></td>
<td><p><span>Campaign1</span></p></td>
<td><p><span>unknown</span></p></td>
</tr>
</tbody>
</table>
</body>
</html>

JSOUP - Extract data directly in a specific format from a page

I am currently experimenting with jsoup and my goal is to extract data from this retail website, in the form of:
Title: blabl
Link: foba
Grösse: 9999
KP: FALSE
Miete: TRUE
Preis: 1923,23
I have written so far this test program:
public class jsoup_test {
public static void main(String[] args) throws IOException {
String url = "http://derstandard.at/anzeiger/immoweb/Suchergebnis.aspx?Regionen=9&Bezirke=&Arten=&AngebotTyp=&timestamp=1363305908912";
print("Fetching %s...", url);
Document doc = Jsoup.connect(url).get();
Elements price = doc.select("tr.topangebot");
Elements price1 = doc.select("tr.white");
System.out.println("--------------------------------");
System.out.println(price);
System.out.println("--------------------------------");
System.out.println(price1);
}
private static void print(String msg, Object... args) {
System.out.println(String.format(msg, args));
}
}
However, this program gives me my data like that:
<tr id="ctl00_Body_mc_cErgebnisListe1_ctl02_InseratInfoTR" class="topangebot">
<td class="BildTD" rowspan="2"> <img border="0" src="http://images.derstandard.at/t/22/upload/imagesanzeiger/immoupload/2013/02/27/277515f7-f935-4a13-83fb-dbe3af930e28.jpg" alt="" /> </td>
<td class="TitleTD" rowspan="2"> <span class="neu">TOP!</span> <strong>Gehobene Qualität, Design und exquisite Ausführung: Dachausbau mit Weitblick und 100 m² Terrasse</strong><br />Wien 16.,Ottakring, Dachgeschoss<br /><span style="color: gray">Erstbezug, Küche, Parkettboden, Hauptmiete, Terrasse, Lift, Keller, Altbau, Kabel/Sat-TV, Barrierefrei</span> </td>
<td class="GroessenTD" rowspan="2"> <span class="strong">125 m²</span><br /><span class="strong">4 </span>Zimmer </td>
<td class="PreisTD" style="border:none;"> <span class="light">Miete</span> 2.190 <br /> </td>
</tr>
<tr id="ctl00_Body_mc_cErgebnisListe1_ctl02_MerklisteTR" class="topangebot">
<td class="merkliste"> </td>
</tr>
<tr id="ctl00_Body_mc_cErgebnisListe1_ctl03_InseratInfoTR" class="topangebot">
<td class="BildTD" rowspan="2"> <img border="0" src="http://images.derstandard.at/t/22/upload/imagesanzeiger/immoimporte/justimmo2/files.justimmo.at/public/pic/big/AEs_YegpKC.JPG" alt="" /> </td>
<td class="TitleTD" rowspan="2"> <span class="neu">TOP!</span> <strong>HS-IMMO: 14. PREISSENSATION Eckzinshaus 1414m² Leerstand - Gesamtnutzfläche 1670m² + Rohdachboden ca. 700m² erzielbar ( Baubescheid ) € 1555.-/m² NFL</strong><br />Wien 14.,Penzing, Zinshaus<br /><span style="color: gray">Parkettboden, Altbau, Kabel/Sat-TV</span> </td>
<td class="GroessenTD" rowspan="2"> <span class="strong">1.670 m²</span><br /> </td>
<td class="PreisTD" style="border:none;"> <span class="light">KP</span> 2.590.000 <br /> </td>
</tr>...
Which is not in a human readable format. Therefore my question is. How to get jsoup, that it extracts the data DIRECTLY in the Format I want?
Thx for your replies?
For example for selecting title you need to do something like this
String title = doc.select("tr.topangebot > td.TitleTD").first.text();
you can navigate the page using DOM if you know the page structure:
http://jsoup.org/cookbook/extracting-data/dom-navigation
This question has a bunch of good web scrapers
Web scraping with Java
I like to use Jsoup because it's methods were literally built for DOM traversal. So, if you are good at HTML, CSS, and Jquery, this library was built for you. Yes, the Jsoup approach may be too fast. Yes, it may not suit your needs. But, when it comes to gathering any type of information from any type of website, Jsoup is flexible enough to meet your needs.

Ending a table row in jstl

I'm trying to use a table to display some images, I'm allowed 3 images per row but I'm not sure how to end the table row when I have a row with less then 3 images. See the snippet below for what I've been trying.
Using a ul I would not have to worry about it but I'm directed to use a table. How can I make sure the last row is properly terminated ? I'm newer to jstl.
Thanks,
<% int endTRFlag = 0; %>
<table width="100%">
<tr>
<core:forEach var="imageURL" items="${actionBean.imageURLs}" varStatus="rowCounter">
<td align="center" valign="middle">
<div class="item">
<img src="${imageURL}" alt="Photo 1" class="img" />
</div>
</td>
<% endTRFlag = 1; %>
<core:if test="${ (rowCounter.count % 3 == 0) }">
</tr>
<tr>
<% endTRFlag = 0; %>
</core:if>
<core:if test="${ (rowCounter.count % 3 != 0) && (endTRFlag == 0)}">
</tr>
</core:if>
</core:forEach>
In the code below, I use .index instead of .count because it is 0-based, and so will work better for modulus (0/3, 3/3, etc.). .last is true if the current element is the last element in the list. This solution does cause validation errors in Eclipse (at least Ganymede), which is annoying.
<c:forEach var="imageURL" items="${actionBean.imageURLs}" varStatus="rowCounter">
<c:if test="${rowCounter.index mod 3 eq 0}">
<tr>
</c:if>
<td>stuff</td>
<c:if test="${(rowCounter.index+1) mod 3 eq 0 or rowCounter.last}">
</tr>
</c:if>
</c:forEach>
Just put the </tr> after the loop.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<c:set var="imageCnt" value="${fn:length(actionBean.imageURLs)}"/>
<table width="100%">
<tr>
<c:forEach var="imageURL" items="${actionBean.imageURLs}"
varStatus="rowCounter">
<td align="center" valign="middle">
<span class="item">
<img src="${imageURL}" alt="Photo 1" class="img" />
</span>
</td>
</c:forEach>
<c:forEach begin="${imageCnt}" end="2">
<td/>
</c:forEach>
</tr>
</table>

Categories