Display blob on jsp page [duplicate] - java

This question already has answers here:
Display BLOB (image) through JSP
(4 answers)
Closed 9 years ago.
Ok so i am trying to display an image along with user first name and last name on a jsp page but i only get the image not the first name and last name...so what's the problem here? ...your help will be appreciated:)
<%# page language="java" contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256"%>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<!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=windows-1256">
<title>Insert title here</title>
</head>
<body>
<H1>Fetching Data From a Database</H1>
<%
Blob image = null;
byte[] imgData = null;
Connection con;
String url="jdbc:mysql://localhost:3306/image";
String uName="root";
String pwd="root";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection(url,uName,pwd);
String sql="Select * from image ";
PreparedStatement stmt=con.prepareStatement(sql);
ResultSet resultset=stmt.executeQuery();
while(resultset.next())
{
Blob bl = resultset.getBlob("image");
byte[] pict = bl.getBytes(1,(int)bl.length());
response.setContentType("image/jpg");
OutputStream o = response.getOutputStream();
%>
<TABLE BORDER="1">
<TR>
<TH>First Name</TH>
<TH>Last Name</TH>
<TH>picture</TH>
</TR>
<TR>
<td>Image</td><td><%o.write(pict);%></td>
<%o.flush();
o.close();%>
<TD> <%= resultset.getString(2) %> </TD>
<TD><%= resultset.getString(3) %></TD>
</TR>
</TABLE>
<BR>
<%
o.flush();
o.close();
}
%>
</body>
</html>

Your code includes calls to o.close() after writing the picture out and later on. That will close the response output stream, and nothing more will be sent out. Don't do that - let the web container take care of closing the output stream.
That should explain why the first name and last name shouldn't be displayed: the response stream was closed.
Also, I don't think the response content type should be "image/jpg" especially considering how the HTML meta tag says the content is "text/html". I think they should be the same - "text/html".
Finally - and maybe most importantly? - JSP is very old. You may want to consider using Facelets (JavaServer Faces technology).

Related

Loading Image From Server using path [duplicate]

This question already has answers here:
"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat
(8 answers)
Closed 2 years ago.
I am trying to create a simple application in which a user can add an image. The name of the image and the path of the folder where I am storing the image but when trying to retrieve it. It shows "Not allowed to load local resource: file:///H:/Projectpictures/BrowserForDataTables.PNG" Error on browser console. please have a look and let me know what is it I am doing wrong here.
Here is my code.
This is the DAOImplementation code for retrive:
#Override
#Transactional
public List<pictureModal> allImages() {
Session currentSession = sessionFactory.getCurrentSession();
Query<pictureModal> query = currentSession.createQuery("from pictureModal");
List<pictureModal> pictues= query.getResultList();
return pictures;
}
This is Controller code for getimages:
#RequestMapping("/seeAllImages")
public String getAllImage(Model theModal) {
List<pictureModal> myPictures= pictureServ.allImages();
theModal.addAttribute("myPicture",myPictures);
return "ImagePage";
}
And here is the code for JSP file:
<%# 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"%>
<html>
<head>
<title>Pictures will display here</title>
</head>
<body>
<h2>Display Pictures </h2>
<table border="1">
<thead>
<tr>
<th>Picture Name</th>
<th>Picture</th>
</tr>
</thead>
<c:forEach var="tempPic" items="${myPicture}">
<tbody>
<tr>
<td>${tempPic.name}</td>
<td><img src="${tempPic.path}"></td>
</tr>
</tbody>
</c:forEach>
</table>
</body>
</html>
Maybe your program tries to access a location where does not have the correct rights. Maybe that is an administrator folder, and your program isn't started as an Administrator.

passing dynamic value from one jsp page to another using session on button click

I am making a job search web application using java. I have alotted a job id to each job and i am displaying the list of jobs in a bootstrap table from database. on each button click i need to forward this job id to a jsp page where i am adding the applicant name to the database corresponding to the jobs.My code is:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="com.dbutil.CrudOperation"%>
<%# page import="java.util.*,java.sql.*" %>
<%# page import="javax.servlet.http.HttpSession" %>
<html>
<head>
<title>Job List</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/jobs.css">
<script src="jquery.js"></script>
<script src="bootstrap.min.js"></script>
</head>
<body data-spy="scroll" data-target=".navbar" data-offset="50">
<% Connection con = null;
ResultSet rs = null,rs1=null;
PreparedStatement ps = null;
HttpSession hs = null;
hs=request.getSession();
con = CrudOperation.createConnection();
%>
<div class="container">
<%String strsql = "select * from postjob1 where sr>0";
try {
ps = con.prepareStatement(strsql);
rs = ps.executeQuery(); %>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>Job Id</th><th>Job Category</th><th>Available Posts</th><th>Required Qualifications</th><th>Salary Details</th><th>Location</th><th>Last date of application</th><th></th>
</tr>
</thead>
<% while (rs.next()) {
%>
<tbody>
<tr><td><%=rs.getString("id")%></td><td><%=rs.getString("jobcategory")%></td><td><%=rs.getString("available")%></td><td><%=rs.getString("requiredqualification")%></td><td><%=rs.getString("salarydetails")%></td><td><%=rs.getString("location")%></td><td><%=rs.getString("lastdate")%></td><td><button type="button" class="btn btn-primary" onclick="<% hs.setAttribute("ID",rs.getString("id")); %>" >View Details </button></td></tr>
</tbody>
<%}
} catch (SQLException se) {
System.out.println(se);
}%>
</table>
</div
</div>
</body>
</html>
I am facing difficulty when I am retreiving the session value ID in other jsp page as i am getting id of the last row in the table irrespective of whichever button i click.Kindly help me run my code.Thanks!
<% hs.setAttribute("ID", rs.getString("id")); %>
In the excerpt above, you are setting the session attribute "ID". After executing the while loop, it stores the last "id" value. The same value is recovered in the destination page, whichever the clicked link.
A possible solution is passing the id in the invoked URL to the following page.
<a href="jobDetails.jsp?idJob=<%=rs.getString("id")%>">
<button type="button" class="btn btn-primary">View Details</button>
You can recover the parameter in jobDetails.jsp using
request.getParameter("idJob")
Note: I'm a bit rusty in JSP. Maybe I've forgotten a quote or something, but that's the idea.
You can pass job id like request's parameter.
For example you can call your jsp-page like that:
<a href="jobDetails.jsp?job_id=3" />
Where job_id is a parameter name and 3 is its value.
After that you can read parameter's value in your jobDetails.jsp in next way:
<%=request.getParameter("job_id")%>

Spring MVC having trouble getting JSP to display Controller Value

I am new to Spring MVC I have setup a test DB to try to get a single flow through and have a table displayed in a JSP page. I assume I have something configured wrong but I cannot find it. Maybe a naming convention.
I have a mySql DB
A DAO Class that just does a select * from my table that works as I can step into it.
My controller just gets a list of my Run Models. No errors are thrown The JSP simple loads an empty table. The controller seems to have the correct info in it.
Model (snippet all the getters and setters seem to work as the controller gets a list of them fine)
public class QAModel {
private int idRun;
private String SuiteID;
private String run_name;
Controller Code
#RequestMapping(value="/RunList")
public ModelAndView listRun(ModelAndView model) throws IOException{
//#ModelAttribute
System.out.println("**** Controller ******");
List<QAModel> listRun = runDao.list();
model.addObject("RunList", listRun);
model.setViewName("RunList");
return model;
}
That does get a list of Run Model Objects that contain the correct DB info I can see them if I step into it. However the JSP loads a blank table.
JSP Code (I assume I'm missing some mapping or naming convention?)
<%# page language="java" contentType="text/html; charset=UTF-8"
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>Contact Manager Home</title>
</head>
<body>
<div align="center">
<h1>Contact List</h1>
<h3>New Run</h3>
<table border="1">
<th>No</th>
<th>Suite ID</th>
<th>Run Name</th>
<c:forEach var="QAModel" items="${RunList}" varStatus="status">
<tr>
<td>${status.index + 1}</td>
<td>${QAModel.SuiteID}</td>
<td>${QAModel.run_name}</td>
<td>
Edit
Delete
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
If you are not able to print any jstl variable then one possible reason can be that your jstl core tag is not added.
Add this to begining of your JSP file.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

How do you show the content of a session in a JSP for java?

i try to get the information of a user on my database, store the object in a session then show the session's contents on a JSP page. Whenever I try to show it on my page, the content of the session does not appear. Please help.
THIS IS THE JSP PAGE I WAS TALKING ABOUT:
<%#page import="neospa.Client"%>
<%#page import="DAOs.ClientDAO"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CLIENT INFORMATION</title>
</head>
<body>
<h1>CLIENT INFORMATION</h1>
<br>
<%Client client = (Client)session.getAttribute("Client");%>
First Name <% client.getFname(); %> Last Name <% client.getLname();%>
<br>
Birthday <%client.getBirthday();%>
<br>
Home Number <%client.getHomeno();%>
<br>
Mobile Number <%client.getMobileno();%>
<br>
Office Number <%client.getOfficeno();%>
<br>
Email Address <%client.getEmail();%>
<br>
Address: <%client.getAddress();%>,<%client.getCity();%>,<%client.getRegion();%>,<%client.getCountry();%>
</body>
</html>
Is there something missing here that I need to put? :)

JSP Encoder Issue While sending Russian character in QueryString

I have two jsp pages. I am trying to add "Russian" language. Russian characters are shown perfectly on jsp page, but when I try to send this value to another jsp page from parameter then in second jsp page this value is changed to different characters. This problem is only in Russian Language and not in others such as Italy and French.
For example
On demo.jsp page the russian character "приветствие" is shown correctly.
but when I try to send it to another page "test.jsp" then some unknown
characters are shown like "!C<Cä5 Cô>CôCC´OD=Cä5!"
Code:
demo.jsp
String welcometext=langP.get("welcome");
<jsp:include page="<%=test.jsp%>">
<jsp:param name="wlc" value="<%=Encode.hex8Code(welcometext)%>" />
</jsp:include>
In test.jsp
String title = Encode.utfToUnicode(Decode.hex8Decode(request.getParameter("wlc")));
System.out.println(" Russial welcome test "+welcome);
Is there any special code we need to add for Russia while sending them in query parameters??
Please note* the following code are already written else it would have given problem for French and Italy language too..
<%# page contentType="text/html; charset=UTF-8" %>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
Also tried with following but didn't help out!
request.setCharacterEncoding("UTF-8")
Try to add <% request.setCharacterEncoding("UTF-8"); %> to your main jsp page:
Here is my example:
demo.jsp
<%#page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8"); %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Привет</h1>
<jsp:include page="/test.jsp" flush="true">
<jsp:param name="wlc" value="Привет"/>
</jsp:include>
</body>
</html>
test.jsp
<h1>Param values is</h1>
<%
String hello = request.getParameter("wlc");
out.print(hello);
%>
I don't know the better solution but the following code solved this issue. I kept the variable in session attribute.
demo.jsp
session.setAttribute("welcometext", welcometext);
test.jsp
String welcometest=(String) session.getAttribute("welcometext");

Categories