I had tried from servlet set value by setattribute and it have to iterate in jsp by getattribute by setter and getter method without EL and JSTl but am getting this error .kindly help on this i searched in google but i cant found.
java.lang.NullPointerException
org.apache.jsp.Home_jsp._jspService(Home_jsp.java:138)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
here serlvet code
package servlet2;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.TreeSet;
import javafx.css.PseudoClass;
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;
import servlet.Dao;
import jdbc.jdbcconnection;
/**
* Servlet implementation class Homepage
*/
//#WebServlet(asyncSupported = true, urlPatterns = { "/Homepage" })
public class Homepage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Homepage() {
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
System.out.println("inside==========>");
String name=request.getParameter("name");
String password=request.getParameter("password");
String phone=request.getParameter("Phone");
String Deptmart=request.getParameter("Dep");
String gender=request.getParameter("gender");
String country=request.getParameter("country");
Dao d=new Dao();
try
{
jdbcconnection jc=new jdbcconnection();
Connection con=jc.getconnection();
String sql="insert into homepage(name,password,phone,Dept,gender,Country) values(?,?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, password);
ps.setString(3, phone);
ps.setString(4, Deptmart);
ps.setString(5, gender);
ps.setString(6, country);
System.out.println("ps=========>"+ps);
ps.execute();
con.commit();
String select="select * from homepage";
PreparedStatement ps1=con.prepareStatement(select);
ResultSet rs=ps.executeQuery();
ArrayList t=new ArrayList();
while(rs.next())
{
d.setid(rs.getInt(1));
d.setName(rs.getString(2));
d.setPassword(rs.getString(3));
d.setPhone(rs.getInt(4));
d.setDeptmart(rs.getString(5));
d.setGender(rs.getString(6));
d.setCountry(rs.getString(7));
t.add(d);
}
request.setAttribute("users",t);
RequestDispatcher rs1=request.getRequestDispatcher("/Home.jsp");
rs1.forward(request, response);
}
catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Jsp page:
<%#page import="servlet.Dao,java.util.*" %>
<!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>
</head>
<body>
<form action="Homepage" method="get">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="password" id="password"></td>
<tr>
<td>Phone:</td>
<td><input type="text" name="Phone" id="Phone">
</tr>
</td>
<tr>
<td>Department:</td>
<td><select id="Dep" name="Dep">
<option value="it">IT</option>
<option value="finace">Finace</option>
<option value="market">Marketing</option>
</select></td>
</tr>
<tr>
<td>Gender:</td>
<td><input type="radio" name="gender" id="gender" Value="Male">Male
<input type="radio" name="gender" id="gender" Value="Female">Female</td>
</tr>
<tr>
<td>Country:</td>
<td><input type="checkbox" name="country" id="country"
Value="India">India <input type="checkbox" name="country"
id="country" Value="Other">Other</td>
</tr>
<br>
<tr>
<td><input type="submit" name="Add" Value="ADD" ></td>
<td><input type="button" name="Clear" Value="CLEAR"></td>
</tr>
</table>
</form>
<table border="1">
<tr><td>Id</td><td>name</td>
<td>Password</td>
<td>Phone</td>
<td>Deptmart</td>
<td>Gender</td>
<td>country</td>
<td>Edit</td>
<td>Delete</td>
</tr>
<%
try
{
List<Dao> al1 = (List) request.getAttribute("users");
// System.out.println(al1); // prints null
for(Dao user : al1) {
%>
<tr>
<td><%=user.getid() %></td>
<td><%=user.getName() %></td>
<td><%=user.getPassword() %></td>
<td><%=user.getPhone() %></td>
<td><%=user.getDeptmart() %></td>
<td><%=user.getGender() %></td>
<td><%=user.getCountry() %></td>
<td></td>
<td></td>
</tr>
<%} }
catch(Exception e)
{
e.printStackTrace();
}
%>
</table>
</body>
</html>
web.xml
<servlet>
<servlet-name>Homepage</servlet-name>
<servlet-class>servlet2.Homepage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Homepage</servlet-name>
<url-pattern>/Homepage</url-pattern>
</servlet-mapping>
Related
I'm trying to insert data into database through a JSP page and a servlet. I have to store a timestamp value like this :"2016-FEB-12 10:45:22". When I try to enter the data into the database I'm being thrown the following error : "oracle.net.ns.NetException: Size Data Unit (SDU) mismatch".
This is my JSP PAGE:
<%# 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>Bid Form</title>
</head>
<body style="background:color=LightGreen">
<form action="BidInsert" method="post">
<table border=1 align="center">
<tr>
<th>Bid Number</th>
<td><input type="text" name="bid_no"></td>
</tr>
<tr>
<th>Amount</th>
<td><input type="text" name="amount"></td>
</tr>
<tr>
<th>User Id</th>
<td><input type="text" name="u_id"></td>
</tr>
<tr>
<th>Listing Id</th>
<td><input type="text" name="l_id"></td>
</tr>
<tr>
<th>Time stamp Info</th>
<td><input type="text" name="timestampinfo" size=50></td>
</tr>
</table>
<center>
<input type="submit" value="submit">
</center>
</form>
</body>
</html>
This is my Servlet:
package Serve;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class BidInsert
*/
public class BidInsert extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public BidInsert() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out= response.getWriter();
response.setContentType("text/html");
String bn,a,ui,li, tsi;
bn=request.getParameter("bid_no").toString();
a=request.getParameter("amount").toString();
ui=request.getParameter("u_id").toString();
li=request.getParameter("l_id").toString();
tsi=request.getParameter("timestampinfo");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection c=DriverManager.getConnection("jdbc:oracle:thin:#apollo.vse.gmu.edu:1521:ite10g","","");
String sql="insert into Bid values('"+bn+"','"+a+"','"+ui+"','"+li+"','"+tsi+"')";
PreparedStatement ps=c.prepareStatement(sql);
ps.executeUpdate(sql);
out.println("Data Inserted successfully");
} catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(out.checkError()==false)
{
out.println(" <input type=\"button\" value=\"Check Database\" onClick=\"window.location.href('Database contents.jsp')\"> ");
}
}
}
I've omitted the username & password of the database intentionally.Is there are any specific data type to be used to take timestamp values?.Please suggest if any. Any help will be much appreciated.
For a start consider using a PreparedStatement (or similar) to avoid create sql insert strings - which are open to sql injection attacks.
Secondly it looks like the time info should be inserted as a TIMESTAMP or DATE, so you need to convert the String into a Date using SimpleDateFormat
see https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html
Search SO and you can find thousands of examples
I'm new to mysql and teaching myself the ropes. I've come across a problem and hoping for some advice.
I created a form in a jsp page to insert data to a mysql database. All data is properly inserted, and when I do select* all data is properly displayed in a table I created. My problem is with my update page.
When I call data from the database back into a form on my editdata.jsp page, only everything before a space is returned. For example, I put the name 'Tom Jones' into a database, but when I go to retrieve it from the name field, only 'Tom' is returned; 'Jones' is not, but is still there in the database.
Here's my editdata.jsp code:
<%#page import="java.sql.ResultSet"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action ="UpdateData" method ="post">
<table border ="1" width="80%">
<%ResultSet res = (ResultSet) request.getAttribute("EditData");%>
<%if(res.next()){
%>
<tr>
<td>ID</td>
<td><input type="text" name="id" value=<%=res.getString("id")%>>
</td>
</tr>
<tr>
<td>Container Number </td>
<td><input type="text" name="id" value=
<%=res.getString("containerNumber")%> ></td>
</tr>
<tr>
<td>Size </td>
<td><input type="text" name="id" value=<%=res.getString("size")%>>
</td>
</tr>
<tr>
<td>Vessel </td>
<td><input type="text" name="id" value=<%=res.getString("vessel")%>>
</td>
</tr>
<tr>
<td>Full Out Date </td>
<td><input type="text" name="id" value=
<%=res.getString("fullOut")%>> </td>
</tr
<tr>
<td>Empty In Date </td>
<td><input type="text" name="id" value=<%=res.getString("emptyIn")%>
></td>
</tr>
<tr>
<td>Empty Out Date </td>
<td><input type="text" name="id" value=
<%=res.getString("emptyOut")%>> </td>
</tr>
<tr>
<td>Full In Date </td>
<td><input type="text" name="id" value=<%=res.getString("fullIn")%>>
</td>
</tr>
<tr>
<td>Comments </td>
<td><input type="text" name="id" value=
<%=res.getString("comments")%>> </td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Update" name="update"> </td>
</tr>
<%}%>
</table>
</form>
</body>
</html>
And my EditRecord servlet:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
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 EditRecord extends HttpServlet {
Connection conn;
ResultSet res;
Statement stmt;
String id, query;
DatabaseConnection dbconn;
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
id = request.getParameter("id");
dbconn = new DatabaseConnection();
conn = dbconn.setConnection();
stmt = conn.createStatement();
query = "select * from inventory where id = "+id;
res = dbconn.getResult(query, conn);
}catch(Exception e){
}
finally {
request.setAttribute("EditData", res);
RequestDispatcher rd = request.getRequestDispatcher("editdata.jsp");
rd.forward(request, response);
out.close();
}
}
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Again, the long and short of my problem is that full strings of data are not returned after spaces. So 'TOM JONES' only returns 'TOM' to the form above for editing. How do I get the full string of data to be returned. I don't know if it matters, but I used VARCHAR for all my record info.
Thanks for any and all help.
Attributes inside HTML tags are separated by spaces. That's why you're supposed to use quotes around the attribute values.
BAD:
<input type="text" name="id" value=<%=res.getString("comments")%>>
GOOD:
<input type="text" name="comments" value="<%=res.getString("comments")%>" />
I have a image in my sql and I want to retrieve it in web page
so i have developed a servlet. now when I hit the submit button then it calls to the servlet but image is not displayed but in the browser if if I am writing localhost:8080/y/testimageServlet then the image is displayed.
imagetestServlet.java
import java.sql.*;
import DB.DataBaseConnection;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class imagetestServlet
*/
#WebServlet("/imagetestServlet")
public class imagetestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public imagetestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException {
Blob image = null;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
DataBaseConnection db= new DataBaseConnection();
ServletOutputStream out = response.getOutputStream();
try {
Class.forName("com.mysql.jdbc.Driver");
con=db.connet();
stmt = con.createStatement();
rs = stmt.executeQuery("select img from one where id = '4'");
if (rs.next()) {
image = rs.getBlob(1);
} else {
response.setContentType("text/html");
out.println("<font color='red'>image not found for given id</font>");
return;
}
response.setContentType("image/gif");
InputStream in = image.getBinaryStream();
int length = (int) image.length();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
} catch (Exception e) {
response.setContentType("text/html");
out.println("<html><head><title>Unable To Display image</title></head>");
out.println("<body><h4><font color='red'>Image Display Error=" + e.getMessage() +
"</font></h4></body></html>");
return;
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
login
<form id="f1" name="f1" action="imagetest" method="post" onsubmit="return ccheck()">
<img src="header.png"><br><br><br><br><br>
<table >
<tr>
<td>
<table class="table">
<tr>
<td>
<table class="table">
<tr>
<td>
<div class="content"><div class="signin-header"><h3>Welcome to DiaEmr</h3></div></div>
</td>
</tr>
<tr>
<td>
<div class="content">
<div class="signin-box">
<p class="one">
Welcome to all at the <b>"Workshop on Ileal Interposition".</b><br>
<b>Brazil</b> to inaugurate & launch this very important Data Registry<br>
Key features of the solution-<br>
</div>
</div>
</td>
</tr>
</table>
</td>
<td>image</td>
<td>
<table class="table" >
<tr>
<td>
<div class="content">
<div class="signin-header">
<h3>Portal Login</h3>
</div>
</div>
</td>
</tr>
<tr>
<td>
<div class="content">
<div align="center" class="signin-box">
<table class="table">
<tr>
<td><b>User ID</b></td>
<td><input name="uid" type="text" /></td>
</tr>
<tr >
<td><b>Password</b></td>
<td><input name="cpass" type="password" /></td>
</tr>
<tr >
<td><input type="submit"
class="button button-submit" value="Submit" /></td>
<td><input type="reset" class="button button-submit"
value="Reset" /></td>
<tr>New UserRegister</tr><br>
</tr>
</table>
</div>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
<div class="footer-bar">
<img align="left" src="footer.png">
</div>
</form>
your form sends a post request,
<form id="f1" name="f1" action="imagetest" method="post" onsubmit="return ccheck()">
but you only define a doGet method in your servlet. This is resulting in your page working if you navigate in a browser (GET) but not when submitting your form (POST).
You will either need to change your form to use get or implement your code in the doPost method
My Servlet Code is
package DBCon;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
/**
*
* #author Nayan
*/
public class loadCourseId extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ArrayList ar1=new ArrayList();
ArrayList ar2=new ArrayList();
int i;
i=0;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/online_exam?"+"user=root&password=pass");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from course");
while(rs.next())
{
ar1.add(rs.getString(1));
ar2.add(rs.getString(2));
}
request.getSession().setAttribute("CourseID", ar1);
request.getSession().setAttribute("CourseName", ar2);
RequestDispatcher requestDispatcher=getServletContext().getRequestDispatcher("http://localhost:8080/ONLINE_EXAM/removeCourse.jsp");
requestDispatcher.forward(request,response);
}
catch(Exception e) {
out.println("<h1>"+e.getStackTrace()+"</h1>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* #param request servlet request
* #param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}
And Jsp Code is
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%#page import="javax.servlet.*"%>
<%# page import="java.util.ArrayList.*" %>
<%# page import="java.sql.*;" %>
<html>
<head>
<script type="text/javascript" language="Javascript" >
window.onload=function LoadCombo()
{
window.action="loadCourseId.do";
ArrayList cd=new ArrayList();
cd.add(request.getSession().getAttribute("CourseID"));
if(cd.isEmpty()==false)
{
for(int i=0;i<cd.size();i++)
{
var newOpt = cid.appendChild(document.createElement('option'));
newOpt.text = cd.get(i);
}
}
else
{
alert("Course table is empty")
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Remove Course</title>
<style type="text/css">
<!--
body {
background-color: #FFCCFF;
}
.style1 {
color: #0066FF;
font-weight: bold;
}
.style2 {font-size: 18px}
.style17 { font-family: "Monotype Corsiva";
font-size: 24px;
font-weight: bold;
font-style: italic;
color: #6633CC;
}
.style19 {color: #000099}
.style21 {color: #000099; font-weight: bold; }
-->
</style>
</head>
<body>
<jsp:include page="Log_Admin.jsp"/><br/>
<form action="" method="post" name="form1" id="form1" >
<table width="46%" height="43" border="3" bgcolor="##CCCC99" align="center">
<tr>
<td width="85%" align="center" bgcolor="##CCCC99"><label><span class="style17">Course Information</span></label></td>
</tr>
<tr><td>
<table width="666" height="207" border="0" align="center" bordercolor="#F0F0F0" bgcolor="#CCCC99" >
<tr>
<td width="186" height="46" align="left"><div align="left"><span class="style19">
<label><strong>Course ID</strong></label>
</span></div></td>
<td><label>
<select name="cid" size="1" id="cid" align="left">
</select>
</label></td>
</tr>
<tr>
<td height="53" align="left"><div align="left"><label><span class="style21">Course Name</span></label></div></td>
<td align="left"><input name="cname" type="text" id="cname" size="50" maxlength="50" /></td>
</tr>
<tr>
<td> </td>
<td> <input name="save" type="submit" id="save" value="Save" />
<input name="reset" type="reset" id="reset" value="Reset" /></td>
</tr>
</table>
</td></tr>
</table>
</form>
</body>
</html>
Bt by writing this code i am not able to add item CourseId to the combobox cid. Can you say me where is the problem? Thanks.
You've 2 synchronous lists whose items are related to each other. This is not really easy to maintain and traverse. Rather put the values of the two lists in a Map.
Map<String, String> courses = new LinkedHashMap<String, String>();
// ...
while(resultSet.next()) {
map.put(resultSet.getString(1), resultSet.getString(2));
}
// ...
request.setAttribute("courses", courses);
In JSP you can use the JSTL <c:forEach> tag to iterate over a List or a Map. In case of a Map, each iteration will give you a Map.Entry in the var attribute which in turn has getKey() and getValue() methods. So this should do:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<select name="cid" size="1" id="cid" align="left">
<c:forEach items="${courses}" var="course">
<option value="${course.key}">${course.value}</option>
</c:forEach>
</select>
Further, the first two lines in your processRequest() method
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
should be removed since that's the responsibly of the JSP, not the servlet. You will otherwise risk IllegalStateException errors when doing so.
Also get rid of the #page import in top of your JSP. They are at the wrong place, all associated code belongs in the servlet.
class MyBean{
String val;
String label;
//+getters setters method
}
Servlet
//fetching list of MyBean and setting it to request as attribute
request.setAttribute("beanList",beanList);
// forward this request to jsp
jsp
<select>
<c:forEach var="bean" items="${beanList}">
<option value="${bean.value}">${bean.label}</option>
</c:forEach>
</select>
My Servlet Code is
package DBCon;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
/**
*
* #author Nayan
*/
public class loadCourseId extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ArrayList ar1=new ArrayList();
ArrayList ar2=new ArrayList();
int i;
i=0;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/online_exam?"+"user=root&password=pass");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from course");
while(rs.next())
{
ar1.add(rs.getString(1));
ar2.add(rs.getString(2));
}
request.getSession().setAttribute("CourseID", ar1);
request.getSession().setAttribute("CourseName", ar2);
RequestDispatcher requestDispatcher=getServletContext().getRequestDispatcher("http://localhost:8080/ONLINE_EXAM/removeCourse.jsp");
requestDispatcher.forward(request,response);
}
catch(Exception e) {
out.println("<h1>"+e.getStackTrace()+"</h1>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* #param request servlet request
* #param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}
And Jsp Code is
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%#page import="javax.servlet.*"%>
<%# page import="java.util.ArrayList.*" %>
<%# page import="java.sql.*;" %>
<html>
<head>
<script type="text/javascript" language="Javascript" >
window.onload=function LoadCombo()
{
window.action="loadCourseId.do";
ArrayList cd=new ArrayList();
cd.add(request.getSession().getAttribute("CourseID"));
if(cd.isEmpty()==false)
{
for(int i=0;i<cd.size();i++)
{
var newOpt = cid.appendChild(document.createElement('option'));
newOpt.text = cd.get(i);
}
}
else
{
alert("Course table is empty")
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Remove Course</title>
<style type="text/css">
<!--
body {
background-color: #FFCCFF;
}
.style1 {
color: #0066FF;
font-weight: bold;
}
.style2 {font-size: 18px}
.style17 { font-family: "Monotype Corsiva";
font-size: 24px;
font-weight: bold;
font-style: italic;
color: #6633CC;
}
.style19 {color: #000099}
.style21 {color: #000099; font-weight: bold; }
-->
</style>
</head>
<body>
<jsp:include page="Log_Admin.jsp"/><br/>
<form action="" method="post" name="form1" id="form1" >
<table width="46%" height="43" border="3" bgcolor="##CCCC99" align="center">
<tr>
<td width="85%" align="center" bgcolor="##CCCC99"><label><span class="style17">Course Information</span></label></td>
</tr>
<tr><td>
<table width="666" height="207" border="0" align="center" bordercolor="#F0F0F0" bgcolor="#CCCC99" >
<tr>
<td width="186" height="46" align="left"><div align="left"><span class="style19">
<label><strong>Course ID</strong></label>
</span></div></td>
<td><label>
<select name="cid" size="1" id="cid" align="left">
</select>
</label></td>
</tr>
<tr>
<td height="53" align="left"><div align="left"><label><span class="style21">Course Name</span></label></div></td>
<td align="left"><input name="cname" type="text" id="cname" size="50" maxlength="50" /></td>
</tr>
<tr>
<td> </td>
<td> <input name="save" type="submit" id="save" value="Save" />
<input name="reset" type="reset" id="reset" value="Reset" /></td>
</tr>
</table>
</td></tr>
</table>
</form>
</body>
</html>
Bt by writing this code i am not able to add item CourseId to the combobox cid. Can you say me where is the problem? Thanks.
You've 2 synchronous lists whose items are related to each other. This is not really easy to maintain and traverse. Rather put the values of the two lists in a Map.
Map<String, String> courses = new LinkedHashMap<String, String>();
// ...
while(resultSet.next()) {
map.put(resultSet.getString(1), resultSet.getString(2));
}
// ...
request.setAttribute("courses", courses);
In JSP you can use the JSTL <c:forEach> tag to iterate over a List or a Map. In case of a Map, each iteration will give you a Map.Entry in the var attribute which in turn has getKey() and getValue() methods. So this should do:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<select name="cid" size="1" id="cid" align="left">
<c:forEach items="${courses}" var="course">
<option value="${course.key}">${course.value}</option>
</c:forEach>
</select>
Further, the first two lines in your processRequest() method
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
should be removed since that's the responsibly of the JSP, not the servlet. You will otherwise risk IllegalStateException errors when doing so.
Also get rid of the #page import in top of your JSP. They are at the wrong place, all associated code belongs in the servlet.
class MyBean{
String val;
String label;
//+getters setters method
}
Servlet
//fetching list of MyBean and setting it to request as attribute
request.setAttribute("beanList",beanList);
// forward this request to jsp
jsp
<select>
<c:forEach var="bean" items="${beanList}">
<option value="${bean.value}">${bean.label}</option>
</c:forEach>
</select>