display an image from a blob field using servlet - java

i created a jsp page that calls another jsp page that show an image took from a blob field in my mysql db:
<img src="blob.jsp">
it works. But, somewhere in this forum i read that this is not the right way to do it. I should, instead, using a servlet this way:
<img src="servlet_name">
I created a servlet, but it doesent show me the image it shows me this
ÿØÿàJFIFHHÿí$Photoshop 3.08BIMí ResolutionHH8BIM FX Global Lighting Anglex8BIMFX Global Altitude8BIMó Print Flags 8BIM Copyright Flag8BIM'Japanese Print Flags 8BIMõColor Halftone SettingsH/fflff/ff¡™š2Z5-8BIMøColor Transfer Settingspÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿè8BIM Layer State8BIM Layer Groups8BIMGuides##8BIM URL overrides8BIMSlicesuƒD Untitled-1Dƒ8BIMICC Untagged Flag
This is my simple servlet
package Jeans;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.sql.ResultSet;
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("/BlobDisplay")
public class BlobDisplay extends HttpServlet {
private static final long serialVersionUID = 1L;
GestioneDB gestioneDB ;
public BlobDisplay() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Blob image = null;
byte[ ] imgData = null ;
String query = null;
query = request.getParameter(query);
gestioneDB = new GestioneDB();
ResultSet rs = gestioneDB.rs("select immagine_principale from news where id ='217'");
try{
if (rs.next()) {
image = rs.getBlob("immagine_principale");
imgData = image.getBytes(1,(int)image.length());
response.setContentType("image/jpg");
OutputStream o = response.getOutputStream();
o.write(imgData);
o.flush();
o.close();
}
}
catch(Exception e){}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}

Here is a debugging hint for now.
JSPs are just "inside out" servlets and they are translated to servlets by the container. Since your JSP works and your servlet doesn't, why don't you check out (and post) the generated servlet. If you are using tomcat, it would be in a file called blob__jsp.java deep in the work directory. Then compare the calls and set up of your servlet and the generated servlet.
(My first guess is the content type, but you seem to be setting that)

Related

getResource() nullPointerException

I am trying to get the contents of a local JSON file in Java. Instead I am getting the following stacktrace:
java.lang.NullPointerException
fi.avaliaho.ottoautomaatitv2.Webservice.doGet(Webservice.java:24)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.apache.catalina.filters.CorsFilter.handleNonCORS(CorsFilter.java:352)
org.apache.catalina.filters.CorsFilter.doFilter(CorsFilter.java:171)
I already made sure that the file coordinates.json is located in the same directory as the Webservice.java file. I am aware of this question, but the answers do not solve my problem. Here is my servlet:
import java.net.URL;
import java.io.*;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Webservice extends HttpServlet {
URL path = null;
Reader file = null;
BufferedReader input = null;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
path = Webservice.class.getResource("coordinates.json");
file = new FileReader(path.getFile());
}
}
Try to use getSystemResource() method
path = ClassLoader.getSystemResource("coordinates.json")
or how it was mentioned by #LaksithaRanasingha in comments add / in the begining:
path = Webservice.class.getResource("/coordinates.json");
Also this might be useful Class.getResource and ClassLoader.getSystemResource: is there a reason to prefer one to another?

Previously working Java servlet now no longer working after 'Clean' - Tomcat v7.0 and Eclipse

So I had an Eclipse project given to me, which I opened in Eclipse and converted to a web project and began writing a servlet + JSP pages for it. It was working fine, until this morning when I cleaned the project using Eclipse's in-built clean function.
Now I am getting the 404 with 'Requested resource is not available' where it was working fine before.
Here is the Servlet code:
package servlets;
import is2.data.SentenceData09;
import is2.lemmatizer.Lemmatizer;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class FYPServlet
*/
#WebServlet("/FYPServlet")
public class FYPServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public FYPServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("sentence")!=null){
//Create container
SentenceData09 sentence = new SentenceData09();
//Split input up
String[] words = request.getParameter("sentence").split(" ");
String lastword = words[words.length-1];
int sizeoflastword = lastword.length();
//If sentence has a full stop, remove it
if(lastword.charAt(sizeoflastword-1)=='.'){
words[words.length-1] = lastword.substring(0,sizeoflastword-1);
}
//Add <root> to start and a full stop to end
String[] fullsentencewords = new String[words.length+2];
fullsentencewords[0] = "<root>";
int i=1;
for(String word : words){
fullsentencewords[i] = word;
i++;
}
fullsentencewords[fullsentencewords.length-1] = ".";
//Initialise the container
sentence.init(fullsentencewords);
//Give lemmatizer location of model
is2.lemmatizer.Options optsLemmatizer = new is2.lemmatizer.Options(new String[] {"-model","C:/Users/Illuria/Downloads/small-models-english/small-models-english/models/lemmatizer-eng-4M-v36.mdl"});
//Create lemmatizer
Lemmatizer lemmatizer = new Lemmatizer(optsLemmatizer);
//Apply the lemmatizer
lemmatizer.apply(sentence);
//Display the lemmata
for (String l : sentence.plemmas) System.out.println("lemma : "+l); //TODO: Push this to the new page
request.setAttribute("lemmas", sentence.plemmas);
request.getRequestDispatcher("ParseDisplay.jsp").forward(request, response);
}else{
response.sendRedirect("EntryForm.jsp");
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
The exact 404 I am getting is:
HTTP Status 404 - /mate-tools-2/FYPServlet
type: Status report
message: /mate-tools-2/FYPServlet
description: The requested resource is not available
Unfortunately I'm a bit of a newbie at web development so any help would be greatly appreciated!
Not sure if you are still having trouble but sometimes just cleaning wont help. I remove webapp from Tomcat eclipse (right click on Tomcat and do 'Add or Remove'), clean it and add it back. Let us know if this helps.

Why does this HTTP servlet behave inconsistently?

An intranet site has a search form which uses AJAX to call a servlet on a different domain for search suggestions.
This works in Internet Explorer with the intranet domain being a "trusted site" and with cross-domain requests enabled for trusted sites, but doesn't work in Firefox.
I have tried to work around the problem by creating a servlet on the intranet server, so there's a JS call to my servlet on the same domain, then my servlet calls the suggestions servlet on the other domain. The cross-domain call is server-side, so it should work regardless of browser settings.
The AJAX call and my servlet's call to the other servlet both use a HTTP POST request with arguments in the URL and empty request-content.
The reason I'm sticking with POST requests is that the JS code is all in files on the search server, which I can't modify, and that code uses POST requests.
I've tried calling the customer's existing suggestions servlet with a GET request, and it produces a 404 error.
The problem is that the result is inconsistent.
I've used System.out.println calls to show the full URL and size of the result on the server log.
The output first seemed to change depending on the calling browser and/or website, but now seems to change even between sessions of the same browser.
E.g. entering "g" in the search box, I got this output from the first few tries on the Development environment using Firefox:
Search suggestion URL: http://searchdev.companyname.com.au/suggest?q=g&max=10&site=All&client=ie&access=p&format=rich
Search suggestion result length: 64
Initial tries with Firefox on the Test environment (different intranet server but same search server) produced a result length of 0 for the same search URL.
Initial tries with Internet Explorer produced a result length of 0 in both environments.
Then I tried searching for different letters, and found that "t" produced a result in IE when "g" hadn't.
After closing the browsers and leaving it for a while, I tried again and got different results.
E.g. Using Firefox and trying "g" in the Development environment now produces no result when it was previously producing one.
The inconsistency makes me think something is wrong with my servlet code, which is shown below. What could be causing the problem?
I think the search suggestions are being provided by a Google Search Appliance, and the JS files on the search server all seem to have come from Google.
The actual AJAX call is this line in one file:
XH_XmlHttpPOST(xmlhttp, url, '', handler);
The XH_XmlHttpPOST function is as follows in another file:
function XH_XmlHttpPOST(xmlHttp, url, data, handler) {
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = handler;
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-Length",
/** #type {string} */ (data.length));
XH_XmlHttpSend(xmlHttp, data);
}
Here is my servlet code:
package com.companyname.theme;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class suggest extends HttpServlet {
Properties props=null;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String result = "";
String args = req.getQueryString();
String baseURL = props.getProperty("searchFormBaseURL");
String urlStr = baseURL + "/suggest?" + args;
System.out.println("Search suggestion URL: " + urlStr);
try {
int avail, rCount;
int totalCount = 0;
byte[] ba = null;
byte[] bCopy;
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write("".getBytes());
os.close();
InputStream is = conn.getInputStream();
while ((avail = is.available()) > 0) {
if (ba == null) ba = new byte[avail];
else if (totalCount + avail > ba.length) {
// Resize ba if there's more data available.
bCopy = new byte[totalCount + avail];
System.arraycopy(ba, 0, bCopy, 0, totalCount);
ba = bCopy;
bCopy = null;
}
rCount = is.read(ba, totalCount, avail);
if (rCount < 0) break;
totalCount += rCount;
}
is.close();
conn.disconnect();
result = (ba == null ? "" : new String(ba));
System.out.println("Search suggestion result length: " + Integer.toString(result.length()));
} catch(MalformedURLException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
PrintWriter pw = resp.getWriter();
pw.print(result);
}
#Override
public void init() throws ServletException {
super.init();
InputStream stream = this.getClass().getResourceAsStream("/WEB-INF/lib/endeavour.properties");
props = new Properties();
try {
props.load(stream);
stream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
Solution: don't rely on InputStream.available().
The JavaDoc for that method says it always returns 0.
HttpURLConnection.getInputStream() actually returns a HttpInputStream, in which available() seems to work but apparently sometimes returns 0 when there is more data.
I changed my read loop to not use available() at all, and now it consistently returns the expected results.
The working servlet is below.
package com.integral.ie.theme;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class suggest extends HttpServlet implements
javax.servlet.Servlet {
Properties props=null;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//super.doPost(req, resp);
final int maxRead=200;
String result="";
String args=req.getQueryString();
String baseURL=props.getProperty("searchFormBaseURL");
String urlStr=baseURL+"/suggest?"+args;
//System.out.println("Search suggestion URL: "+urlStr);
try {
int rCount=0;
int totalCount=0;
int baLen=maxRead;
byte[] ba=null;
byte[] bCopy;
URL url=new URL(urlStr);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
// Setting these properties may be unnecessary - just did it
// because the GSA javascript does it.
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length","0");
InputStream is=conn.getInputStream();
ba=new byte[baLen];
while (rCount>=0) {
try {
rCount=is.read(ba,totalCount,baLen-totalCount);
if (rCount>0) {
totalCount+=rCount;
if (totalCount>=baLen) {
baLen+=maxRead;
bCopy=new byte[baLen];
System.arraycopy(ba,0,bCopy,0,totalCount);
ba=bCopy;
bCopy=null;
}
}
} catch(IOException e) {
// IOException while reading - allow the method to return
// anything we've read so far.
}
}
is.close();
conn.disconnect();
result=(totalCount==0?"":new String(ba,0,totalCount));
//System.out.println("Search suggestion result length: "
//+Integer.toString(result.length()));
} catch(MalformedURLException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
PrintWriter pw=resp.getWriter();
pw.print(result);
}
#Override
public void init() throws ServletException {
super.init();
InputStream stream=this.getClass().getResourceAsStream("/WEB-INF/lib/endeavour.properties");
props=new Properties();
try {
props.load(stream);
stream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
Start with a unit test. Servlets are pretty straightforward to unit test and HttpUnit has worked for us.
Debugging Servlet code in a browser and with println calls will cost more time in the long run and it's difficult for someone on SO to digest all of that information to help you.
Also, consider using a JavaScript framework such as JQuery for your AJAX calls. In my opinion there's little reason to touch an xmlHttp object directly now that frameworks will hide that for you.

405 http method get is not supported by this url

I have written a servlet for approval of leaves. In this servlet I have also written code to send a mail. Due to this, it shows HTTP 405 error. If I remove the code which sends a mail, then it does not show the error, but I need the mail code.
package mis;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.jdo.PersistenceManager;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.jdo.Query;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
public class approve extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
try{
HttpSession session = req.getSession(true);
PersistenceManager pm1 = PMF.get().getPersistenceManager();
Query query1 = pm1.newQuery(Leave_bal.class);
query1.setFilter("emp_Id == emp");
query1.declareParameters("String emp");
List<Leave_bal> results1 = (List<Leave_bal>)query1.execute(session.getAttribute("emp_Id").toString());
String plan="";
String unplan="";
String planleave_result="" ;
String unplanleave_result="";
for (Leave_bal e : results1)
{
plan=e.getplan_leave();
resp.getWriter().println("Planned_Leave"+plan);
unplan=e.getunplan_leave();
resp.getWriter().println("Unplanned:"+unplan);
}
int plan_leave=Integer.parseInt(plan);
int unplan_leave=Integer.parseInt(unplan);
String ID=req.getParameter("id");
resp.getWriter().println(ID);
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(Leave_detail.class);
query.setFilter("id == ID");
query.declareParameters("String ID");
List<Leave_detail> results = (List<Leave_detail>)query.execute(ID);
String plan_detail="";
String duration="";
for (Leave_detail e : results)
{
plan_detail=e.getLeave_Type();
duration=e.getdurtn();
//f=e.getfrom();
//t=e.getto();
}
resp.getWriter().println("duration "+duration);
resp.getWriter().println("Planned_selected "+plan_detail);
int duration_integer=Integer.parseInt(duration);
resp.getWriter().println("duration "+duration_integer);
//String duration=req.getParameter("date");
// resp.getWriter().println("diffrence:"+duration);
//int workingdays=Integer.parseInt(duration);
//String Leave = req.getParameter("a");
// resp.getWriter().println("planned:"+Leave);
if(plan_detail.equals("UNPLAN"))
{
unplan_leave=unplan_leave-duration_integer;
unplanleave_result=String.valueOf(unplan_leave);
planleave_result=plan;
resp.getWriter().println("Planned After Change"+unplanleave_result);
//st="Applied";
}
if(plan_detail.equals("PLAN"))
{
plan_leave= plan_leave-duration_integer;
planleave_result=String.valueOf(plan_leave);
resp.getWriter().println("Planned After Change"+planleave_result);
unplanleave_result=unplan;
}
if(plan_detail.equals("LWP"))
{
plan_leave= plan_leave-duration_integer;
planleave_result=String.valueOf(plan_leave);
resp.getWriter().println("Planned After Change"+planleave_result);
unplanleave_result=unplan;
}
if(plan_detail.equals("Onduty"))
{
planleave_result=plan;
unplanleave_result=unplan;
}
Leave_detail status_update = pm.getObjectById(Leave_detail.class,ID);
status_update.setstatus("Approved");
pm.makePersistent(status_update);
Leave_bal ed1=new Leave_bal(session.getAttribute("emp_Id").toString(),planleave_result,unplanleave_result);
pm.makePersistent(ed1);
//code for mail
RequestDispatcher dispatcher = getServletConfig ( ) .getServletContext ().getRequestDispatcher("/MailServiceapply");
dispatcher.forward (req, resp) ;
pm.close();
}
catch(Exception a )
{
resp.getWriter().println(a .getMessage());
} finally{
}
resp.sendRedirect("hr.jsp#LMS");
}
}
This thread on Java Forums provides some hints for this error, like
HTML form invokes POST operation and servlet doesn't implement doPost (direct link)
Inital HTML form not declared in web.xml file (or misspelled) (direct link)
At the bottom of this servlet you're forwarding the request to another servlet:
RequestDispatcher dispatcher = getServletConfig().getServletContext().getRequestDispatcher("/MailServiceapply");
dispatcher.forward(req, resp);
This is not only a poor approach, certainly because you've written data to the HTTP response before in the servlet and you thus risk IllegalStateException (writing to the response should take place in a JSP), but doing so also requires that the servlet in question also implements doGet(). The error which you're facing suggests that this mail service servlet has only the doPost() implemented.
You need to add a doGet() method to the mail service servlet and use RequestDispatcher#include() to invoke it.
dispatcher.include(req, resp);
Needless to say that this is still a poor approach. You'd rather like to refactor the mail code logic into a standalone Java class which you then import and invoke in both servlets and put all the presentation logic in a JSP.

Easy way to write servlet that returns table data in xml format

Easy way to write servlet that returns table data in xml format - ?
Data comes from a database table.
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;
public class TableServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("application/xml");
PrintWriter writer = response.getWriter();
writer.println("<?xml version=\"1.0\"?>");
writer.println("<table>");
writer.println("<style>");
writer.println("<finish>polished</finish>");
writer.println("<material>oak</material>");
writer.println("</style>");
writer.println("<legs>4</legs>");
writer.println("</table>");
writer.flush();
}
}
You may found jersey useful it works for XML, also supports JSON . Here is a good tutorial (Look section 4) .

Categories

Resources