Assume that when a user accesses to my website, then he will see a lot of images which have stored in the database before. I know how to do that in JSP Scriptlet, and I also know how to fetch and retrieve data from the database in JSTL when the user submit a form by using servlet. But I don't know how to do it in JSTL without user submitting a form.
-
share code, what have you did already.Braj– Braj2014-07-31 05:12:37 +00:00Commented Jul 31, 2014 at 5:12
-
1I dont have the JSTL code. I only have have jsp scriptlet code, which I retrieve and store data into an hashmap, then inside the jsp body, I get and display the data from hashmap so that the user will be able to see that data. Since there are a lot of articles recommend using JSTL and JSF instead of JSP scriptlet, I want to learn and convert my code to JSTL. But seem like JSTL lacking of flexibility when involving custom java class.user3819470– user38194702014-07-31 05:25:29 +00:00Commented Jul 31, 2014 at 5:25
2 Answers
Yes, You can use JSTL & EL. For database access use JSTL SQL Tag library.
How to display images in JSP that is stored in database?
I hope you are using BLOB type column to store images in database. Simply hit a Servlet passing id of the records and send byte[] in response.
I have created separate request for each image for better user experience as well.
Note: It's better to move the database code in the Servlet.
JSP:
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<sql:setDataSource var="webappDataSource"
driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test"
user="root" password="root" />
<sql:query dataSource="${webappDataSource}"
sql="select id,username from users" var="result" />
<table width="100%" border="1">
<c:forEach var="row" items="${result.rows}">
<tr>
<td>${row.id}</td>
<td>${row.username}</td>
<td>
<img src="${pageContext.servletContext.contextPath }/photoServlet?id=${row.id}" />
</td>
</tr>
</c:forEach>
</table>
Servlet (PhotoServlet.java):
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost:3306/test";
final String User = "root";
final String Password = "root";
try {
Class.forName(JDBC_DRIVER);
Connection conn = DriverManager.getConnection(DB_URL, User, Password);
PreparedStatement stmt = conn.prepareStatement("select photo from users where id=?");
stmt.setLong(1, Long.valueOf(request.getParameter("id")));
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
response.getOutputStream().write(rs.getBytes("photo"));
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
web.xml:
<servlet>
<servlet-name>PhotoServlet</servlet-name>
<servlet-class>com.server.servlet.PhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PhotoServlet</servlet-name>
<url-pattern>/photoServlet</url-pattern>
</servlet-mapping>
Table structure: (users)
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| username | varchar(30) | YES | | NULL | |
| password | varchar(20) | YES | | NULL | |
| photo | blob | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
5 Comments
If your question is about displaying database content on JSP page using JSTL tags and if you are using native style JDBC database connection (not jpa or hibernate), take a look:
// make a class for you database table mapping
// assume you have id,name,salary in employee database table , make a Java class for it
class Employee{
int id;
String name;
float salary;
// now getter setter for fields
public int getId(){
return this.id;
}
public void setId(int id){
this.id = id;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public float getSalary(){
return this.salary;
}
public void setSalary(int salary){
this.salary = salary;
}
}
// now in your servlet class make a list of Employee class and set data from data base
List<Employee> empList = new ArrayList<Employee>();
// asume your db connection and query is here
ResultSet rs = your_result_Set
while(rs.next()){
Employee emp = new Employee();
emp.setId(rs.getInt("id"));
emp.setName(rs.getString("name"));
em.setSalary(rs.getFloat("slary"));
empList.add(em);
}
request.setAttribute("empList",empList);
request.getRequestDispacher("your_jsp_path").forward(request,response);
// now in your jsp add <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> on top of jsp
<table>
<c:forEach items="${empList}" var="e" >
<tr>
<td>${e.id}</td>
<td>${e.name}</td>
<td>${e.salary}</td>
</tr>
</c:forEach>
</table>
Custom MVC using servlet and jsp. Take a look using servlet 3.0 or higher
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;
@WebServlet(name="login", urlPatterns={"/login"})
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try{
// do your login logic here
request.setAttribute("message","login failed");
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
}
catch(Exception exp){
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
// now in login.jsp placed in WEB-INF/jsp
<span>${message}</span><!-- message is request attribute here assigned in servlet-->
Now whenever you call login url request 1st comes to login servlet after that transferred to jsp