Image not coming from servlet when called from jsp - image

I am trying to fetch image from oracle database.
Flow is : JSP (to read photo_id) -> JSP -> which internally calls Servlet from src attribute of HTML image tag.
ImageGetter.jsp (Asking for photo id)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>your Pic</title>
</head>
<body>
<form id="form2" enctype="multipart/form-data" action="getPhoto.jsp" method="get">
<table>
<tr>
<td>Enter Photo Id :</td>
<td><input type="text" name="id"/></td>
</tr>
</table>
<p/>
<input type="submit" value="fetch Photo"/>
</form>
</body>
</html>
getPhoto.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Your photo</title>
</head>
<body>
<% String p_id=request.getParameter("id");%>
<table>
<tr><td><%=p_id%></td></tr>
<tr><td><img src="/getPic?photoid=<%=p_id%>" /></td></tr>
</table>
</body>
</html>
getPic in src attribute of img tag is servlet.
getPic.java
package com.kp.imagehandler;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kp.imagehandler.Image;
/**
* Servlet implementation class getPic
*/
public class getPic extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public getPic() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String imageId = request.getParameter("photoid");
System.out.println(imageId);
InputStream photoStream = (new Image()).getImageStream(imageId);
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams
input = new BufferedInputStream(photoStream, 200000);
output = new BufferedOutputStream(response.getOutputStream(),
200000);
// Write file contents to response.
byte[] buffer = new byte[200000];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
output.close();
input.close();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Image.java:
package com.kp.imagehandler;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Image {
// Init ---------------------------------------------------------------------------------------
public InputStream getImageStream(String pid)
{
InputStream IS=null;
try {
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:#10.75.122.69:1521:devdb",
"s3", "s3");
Statement stmt = connection.createStatement ();
ResultSet rset = stmt.executeQuery ("SELECT photo FROM photo_holder where id="+pid);
while(rset.next())
{
IS=rset.getBinaryStream("photo");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return IS;
}
// Implement default getters and setters here.
}
web.xml :
<servlet>
<description>getPic</description>
<display-name>getPic</display-name>
<servlet-name>getPic</servlet-name>
<servlet-class>com.kp.imagehandler.getPic</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getPic</servlet-name>
<url-pattern>/getPic</url-pattern>
</servlet-mapping>
Table definition:
create table PHOTO_HOLDER
(
ID NUMBER(5) not null,
TITLE VARCHAR2(50),
PHOTO BLOB
)
but after hitting fetch photo I am just getting photo id but not image.
Here I am not sure whether servlet is getting fired or not.
please help.thanks in advance.

There may be an issue with the URL formed for the image.
Please validate it again by simply looking at the source code of the generated JSP in the browser.
Just debug your code or use logging to investigate the issue.
Try it again after appending context path before the Servlet/JSP path as shown below:
<form id="form2" enctype="multipart/form-data" action="<%=request.getContextPath() %>/getPhoto.jsp" method="get">
<img src="<%=request.getContextPath() %>/getPic?photoid=<%=p_id%>" />

Related

Spring boot authentication issue?

As you can see on : http://website-live-245110.appspot.com/ (gccloud hosted site) following the code logic, any username with 4 characters should be able to log in. Although this is not the case at the moment and i have trouble understanding why.
You should try logging in multiple times to grasp the issue.
CustomAuthenticationProvider.java
package com.spring.authprovider;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider{
#Autowired
private ThirdPartyAuthProviderClient thirdPartyAuthProviderClient;
// one a user logs in, the authentication variable is filled with the details of the authentication
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// when the user logs in to the application, our object will be filled by spring
String name = authentication.getName();
Object password = authentication.getCredentials(); //object that encapsulates password that user types
// not printing or storing password anyone
if(thirdPartyAuthProviderClient.shouldAuthenticate(name,password)) {
// the array list is for roles, because we are not using it now, we are sending it an empty one
return new UsernamePasswordAuthenticationToken(name, password, new ArrayList<>());
} else {
System.out.println("authentication failed for user: " + name);
}
return null;
}
#Override
public boolean supports(Class<?> authentication) {
// there are multiple ways of authentication, use use username and password
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
ThirdPartyAuthProviderClient.java
package com.spring.authprovider;
import org.springframework.stereotype.Component;
#Component
public class ThirdPartyAuthProviderClient {
//emulates request to third party application
public boolean shouldAuthenticate(String username, Object password) {
// 3rd party request to see if user is correct or no or should be logged in
// user with username with 4 digits can be logged in to the application
return username.length() == 4;
}
}
WebSecurityConfig.java
package com.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import com.spring.authprovider.CustomAuthenticationProvider;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private CustomAuthenticationProvider authProvider;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/home", "/time").permitAll() // any request matching /, /home, /time
// can be accessed by anyone
.anyRequest().authenticated() // any other request needs to be authenticated
.and().authorizeRequests().antMatchers("/admin/**") // only admin can access /admin/anything
.hasRole("ADMIN")
.and().formLogin().loginPage("/login") // permit all to form login--- we use loginPage to use custom page
.permitAll()
.and().logout() // permit all to form logout
.permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//specify auth provider
auth.authenticationProvider(authProvider);
}
// configuration of static resources
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/templates/**", "/assets/**");
}
}
MvcConfig.java
package com.spring;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
public class MvcConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}
Templates
hello.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="#{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
</body>
</html>
home.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1>
<p>Click <a th:href="#{/hello}">here</a> to see a greeting.</p>
</body>
</html>
login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="#{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
I expect it to either log me in when a username with 4 characters is entered, Or output Invalid username and password. Error.
Code is here : https://github.com/jeffpascal/Spring-and-springboot/tree/devs/SpringSecurity

Jsp ajax tag not working in jsp.. Unable to load tag handler class exception

Iam new to Ajax tags.. Whenever I try to execute these, HTML part works as expected. But Ajax tags not working..
Getting unable to load tag handler class exception "org.ajaxtags.tags.AjaxSelectTag"..
<%# taglib uri="/WEB-INF/ajaxtld/ajaxtags.tld" prefix="ajax" %>
<html>
<head>
<title>AJAX JSP Tag Library</title>
<script type="text/javascript" src="js/prototype-1.6.0.3.js"></script>
<script type="text/javascript" src="js/scriptaculous/scriptaculous.js"></script>
<script type="text/javascript" src="js/overlibmws/overlibmws.js"></script>
<script type="text/javascript" src="js/ajaxtags-1.2-beta1.js"></script>
<link type="text/css" rel="stylesheet" href="/WEB-INF/css/ajaxtags.css" />
<link type="text/css" rel="stylesheet" href="/WEB-INF/css/displaytag.css" />
</head>
<body>
<form>
Make:
<select id = "make" name = "make">
<option value="">Select make</option>
<c:forEach items="${makes}" var="make">
<option value="${make}">${make}</option>
</c:forEach>
</select>
Model:
<select id="model" name="model" >
<option value="">Select model</option>
</select>
<input type="button" value="read">
<div id="tar"></div>
</form>
<ajax:select baseUrl="$Sample/samplejava" source="make" target="model" parameters="make={make}" />
</body>
</html>
servlet part is defined below..
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class samplejava extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet samplejava</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet samplejava at " + request.getContextPath() + "</h1>");
out.println("Here is the response...");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
try {
String res = request.getParameter("make");
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
PrintWriter out = response.getWriter();
out.println(res);
response.getWriter().write("hai!! this is response...");
response.sendRedirect("success.jsp");
} catch (Exception e) {
response.sendRedirect("error.jsp");
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Anybody can suggest please...
Its working fine, when I just change doGet() method to doPost() method..
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class samplejava extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet samplejava</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet samplejava at " + request.getContextPath() + "</h1>");
out.println("Here is the response...");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)//I just changed the doGet() to doPost(), its working fine
throws ServletException, IOException {
processRequest(request, response);
try {
String res = request.getParameter("make");
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
PrintWriter out = response.getWriter();
out.println(res);
response.getWriter().write("hai!! this is response...");
response.sendRedirect("success.jsp");
} catch (Exception e) {
response.sendRedirect("error.jsp");
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

Receiving a single line of text from servlet using XMLHttp request

I am trying to send an XMLHttp request from a JSP to a servlet and display a message in alert() received from server. But I am basically receiving the <script> <script/> part with some html tag.
Here is my jsp code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
<script>
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function startRequest() {
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("post", "testServlet", true);
// var msg="Hello world";
xmlHttp.send(null);
}
function handleStateChange(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
alert("The server replied with: " +xmlHttp.responseText);
}
}
}
</script>
</head>
<body>
<form action="#">
<input type="button" value="Press ME!!"
onclick="startRequest();"/>
</body>
</html>
Here is my servlet code:
package pk1;
import java.io.IOException;
import java.io.PrintWriter;
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("/testServlet")
public class testServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public testServlet() {
super();
}
protected void doGet( HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
test(response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
test(response);
}
public void test(HttpServletResponse response) throws IOException{
response.setContentType("text/plain");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setCharacterEncoding("UTF-8");
String data = "This is a response from testServlet";
PrintWriter out=response.getWriter();
out.write(data);
out.flush();
out.close();
}
}
Since I am using Tomcat7 I guess I don't need to specify URL mapping? so what am I doing wrong here? kindly let me know.
Add this line
function startRequest() {
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("post", "testServlet", true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // add here
xmlHttp.send(null);
And also in your servlet first try with doPost,
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print("Hi ");
}
Hope it helps! notify if it works

servlet ajax nullpointerexception

i keep getting a null pointer exception whenever i try to read from the ajax parameters in my servlet.
heres the ajax code:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*;" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
function findNext(id,label){
alert(id);
alert(label);
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState===4 && xmlhttp.status===200)
{
var ret=xmlhttp.responseText;
var prob=ret.substring(0,ret.indexOf("///"));
var pdesc=ret.substring(3);
document.getElementById("prob").innerHTML=prob;
document.getElementById("pdesc").innerHTML=pdesc;
}
};
xmlhttp.open("POST","Servlet1",true);
var sendstr="pid="+id+"&labelid="+label;
xmlhttp.send(sendstr);
}
</script>
</head>
<body>
<%
Connection con;
Statement s;
ResultSet rs;
String sql,pid=null,prob=null,pdesc=null,yesL=null,noL=null;
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/cdt", "root", ".hack%//sign66");
s=con.createStatement();
sql="select * from cdt.problem where pid='1.01'";
rs=s.executeQuery(sql);
rs.next();
pid=rs.getObject("pid").toString();
prob=rs.getObject("problm").toString();
pdesc=rs.getObject("pdesc").toString();
yesL=rs.getObject("yesL").toString();
noL=rs.getObject("noL").toString();
}
catch(Exception e){
e.printStackTrace();
}
%>
<!--STYLE THESE 2 <P> STATEMENTS-->
<p id="prob"><%=prob%></p>
<p id="pdesc"><%=pdesc%></p>
<form>
<input type="button" value="Yes" onclick="findNext(<%=pid%>,<%=yesL%>);"/>
<input type="button" value="No" onclick="findNext(<%=pid%>,<%=noL%>);"/>
</form>
</body>
</html>
the variables that i pass to the function read fine through the alert.
heres the servlet code:
package cdt1;
import cdt.FindNextLabelLocal;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ejb.EJB;
public class Servlet1 extends HttpServlet {
Connection con;
Statement s;
ResultSet rs;
#EJB private FindNextLabelLocal obj;
#Override
public void init(ServletConfig config) throws ServletException{
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/cdt", "root", ".hack%//sign66");
s=con.createStatement();
}
catch(Exception e){
e.printStackTrace();
}
}
#SuppressWarnings("UnusedAssignment")
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String pid,label,res;
#SuppressWarnings("UnusedAssignment")
float current,next;
current=next = 0;
pid=request.getParameter("pid").toString(); // pid of the question
label=request.getParameter("labelid").toString(); //label of the next question or solution based on button press
current=Float.parseFloat(pid);
next=Float.parseFloat(label);
res=obj.findNext(current,next).toString();
out.write(res);
}
catch(Exception e){
e.printStackTrace();
}
finally {
out.close();
}
}
#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";
}
}
the null exception occurs java.lang.NullPointerException
at cdt1.Servlet1.processRequest(Servlet1.java:66)
at cdt1.Servlet1.doPost(Servlet1.java:124)
the 1st one occurs when i try to read the pid value
the 2nd one when processRequest is being called.
i have looked up a lot of resources on the web that show how to use ajax and servlets and as per the things i've read i am doing nothing wrong. If anyone can point me in the right direction it will be awesome. Thanks in advance. I am using netbeans 7.3 with glassfish 3.1.2 if that makes a difference
solved it. it is necessary to set the content-type http header when using post to send data.
also needed during put requests

MVC, Servlets, JSP, No Output

I'm trying to learn Servlets/JSP. When I tried the following code I dont get any output. Can someone please help me? When I run the code I get only the header and I dont see the values showing up in the dropdown.
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class VacationTrackerDAO {
public static List<VactionTrackerBean> list() throws SQLException{
List<VactionTrackerBean> appr= new ArrayList<VactionTrackerBean>();
try{
DBConnection conObj=new DBConnection();
Connection dbCon= conObj.getCon();
Statement stmt=conObj.getStmt();
String queryCPList="select * from Capacity_Plan";
String queryApprList="Select First_Last_Name from Vacation_Approvers";
PreparedStatement preStmtCPList=dbCon.prepareStatement(queryCPList);//get metadat
PreparedStatement preStmtApprList=dbCon.prepareStatement(queryApprList);//get names
//ResultSet rsCPList=preStmtCPList.executeQuery();
ResultSet rsApprList=preStmtCPList.executeQuery();
//ResultSetMetaData metaCPList=rsCPList.getMetaData();
VactionTrackerBean vtBean=new VactionTrackerBean();
while(rsApprList.next()){
vtBean.setApprover((rsApprList.getString("First_Last_Name")));
appr.add(vtBean);
}
}catch(Exception e){
System.out.println("In the Vacation TrackerDAO.java class:"+e);
}
return appr;
}
}
Bean:
public class VactionTrackerBean {
private String dates;
private String approver;
public String getDate() {
return dates;
}
public void setDate(String dates) {
this.dates = dates;
}
public String getApprover() {
return approver;
}
public void setApprover(String approver) {
this.approver = approver;
}
}
Servlet:
public class VacationTracker extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
List<VactionTrackerBean> vacTracker=VacationTrackerDAO.list();
request.setAttribute("vacTracker", vacTracker);
request.getRequestDispatcher("WEB-INF/VacationTracker.jsp").forward(request,response);
}catch (SQLException e){
System.out.println("Error in VacationTracker.java due to VactionTrackerDA.java:"+e);
request.getRequestDispatcher("WEB-INF/Error.jsp").forward(request,response);
}
}
}
JSP Page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Vacation Tracker</title>
</head>
<body>
<h1> Vacation Tracker </h1>
<div id="main">
<c:forEach items="${vacTracker}" var="vacTracker">
<select id="myselect" name="mydata" size="10">
<option value="${vacTracker.approver}">${vacTracker.approver}</option>
</select>
</c:forEach>
</div>
</body>
</html>
Check you are getting values in list.Put some S.O.P after while loop in DAO class.
Also,There is a mistake in code. It should be
<select id="myselect" name="mydata" size="10">
<c:forEach items="${vacTracker}" var="vacTracker">
<option value="${vacTracker.approver}">${vacTracker.approver}</option>
</c:forEach>
</select>
Otherwise, It will create new select for each item.

Resources