Jsp
<%#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">
<html>
<head>
<script type="text/javascript" language="Javascript" >
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add Course_Subject</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="#FFFF99"><label><span class="style17">Course and Subject 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>Coourse ID</strong></label>
</span></div></td>
<td><label>
<select name="cid" size="1" id="cid" align="left" onclick="loaadCourseName()">
<option selected="selected">None</option>
<option>C001</option>
<option>C002</option>
<option>C003</option>
<option>C004</option>
<option>C005</option>
<option>C006</option>
<option>C007</option>
<option>C008</option>
<option>C009</option>
<option>C010</option>
</select>
</label></td>
<td width="186" height="46" align="left"><div align="left"><span class="style19">
<label><strong>Coourse Name</strong></label>
</span></div></td>
<td width="310" align="left"><input name="cname" type="text" id="cname" size="25" maxlength="50" /></td>
</tr>
<tr>
<td width="186" height="46" align="left"><div align="left"><span class="style19">
<label><strong>Subject ID</strong></label>
</span></div></td>
<td><label>
<select name="sid" size="1" id="sid" align="left">
<option selected="selected">None</option>
<option>S01</option>
<option>S02</option>
<option>S03</option>
<option>S04</option>
<option>S05</option>
<option>S06</option>
<option>S07</option>
<option>S08</option>
<option>S09</option>
<option>S10</option>
</select>
</label></td>
<td width="186" height="46" align="left"><div align="left"><span class="style19">
<label><strong>Subject Name</strong></label>
</span></div></td>
<td width="310" align="left"><input name="sname" type="text" id="sname" size="25" maxlength="50" /></td>
</tr>
<tr>
<td> </td>
<td> <input name="save" type="submit" id="save" value="Save" onclick="validate(this.form)"/>
<input name="reset" type="reset" id="reset" value="Reset" /></td>
</tr>
</table>
</td></tr>
</table>
</form>
</body>
</html>
Servlet
package DBCon;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
/**
*
* #author Nayan
*/
public class searchCourseName 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();
String cname=null,courseid;
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();
courseid=request.getParameter("cid");
ResultSet rs=stmt.executeQuery("select course_name from course where course_id='"+courseid+"'");
while(rs.next())
{
cname=rs.getNString("course_name");
//String s=rs.getString(1);
}
request.getSession().setAttribute("courseName",cname);
//RequestDispatcher requestDispatcher=getServletContext().getRequestDispatcher("http://localhost:8080/ONLINEEXAMINATION/removeCourse2.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>
}
Now when I select an item in the dropdown cid I want to display the corresponding courname in the cname textfield. How can I achieve this?
Remove
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
They are superfluous and dangerous when using JSP. JSP already sets its own content type. When getting the response writer in the servlet, you'll only risk seeing IllegalStateException errors in server logs when forwarding to JSP.
Replace
request.getSession().setAttribute("courseName",cname);
//RequestDispatcher requestDispatcher=getServletContext().getRequestDispatcher("http://localhost:8080/ONLINEEXAMINATION/removeCourse2.jsp");
//requestDispatcher.forward(request,response);
by
request.setAttribute("courseName",cname);
request.getRequestDispatcher("/removeCourse2.jsp").forward(request, response);
This sets the variable in request scope so that it's available by ${courseName} and forwards the request back to same JSP where the form is in. The session scope will also work, but you don't want that here. It'll affect other requests (the visitor may for instance have opened the same form in multiple browser tabs).
Update
<input name="cname" type="text" id="cname" size="25" maxlength="50" />
with
<input name="cname" value="${courseName}" type="text" id="cname" size="25" maxlength="50" />
The ${courseName} will print the value of the request attribute. Doing so in the value attribute of the input element will make it to show up in the browser. If this is an user controlled value, you may want to use JSTL fn:escapeXml() to avoid XSS attacks.
See also:
Our Servlets wiki page - Contains a Hello World
Related
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
How do i call a servlet from a method?
One method is started by a button and I want that method to start the servlet but, I'm having difficultly because it's a servlet??
I want setRc to call doGet which, in-turn, calls processRequest.
public class rc extends HttpServlet {
public void setRc(String rc) throws ServletException, IOException {
rc test = new rc();
test.doGet(null, null);
this.rc = rc;
}
public String getRc() {
return rc;
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("FROM doGet");
response.setContentType("text/xml");
//this is where the debugger quits...
PrintWriterout = response.getWriter();
processRequest(request, response);
setRc(rc);
}
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
name = request.getParameter("rc");
IP = request.getRemoteAddr();
FileWriter fstream = new FileWriter("C:\\commands\\IPLog\\IP.txt");
BufferedWriter txt = new BufferedWriter(fstream);
txt.write(IP);
txt.close();
Process p = Runtime.getRuntime().exec("c:\\commands\\psexec \\\\" + IP + " -s -i C:\\Windows\\System32\\mstsc.exe /v:" + name);
}
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index</title>
</head>
<body>
<jsp:useBean id="info" scope="session" class="org.mypackage.WebTools.info" />
<jsp:setProperty name="info" property="info" />
<jsp:useBean id="hinv" scope="session" class="org.mypackage.WebTools.hinv" />
<jsp:setProperty name="hinv" property="hinv" />
<jsp:useBean id="rc" scope="session" class="org.mypackage.WebTools.rc" />
<jsp:setProperty name="rc" property="rc" />
<jsp:useBean id="remx" scope="session" class="org.mypackage.WebTools.remx" />
<jsp:setProperty name="remx" property="remx" />
<jsp:useBean id="SOne" scope="session" class="org.mypackage.WebTools.SOne" />
<jsp:setProperty name="SOne" property="SOne" />
<b><font color="blue">Please Enter your Full Name here:</font></b><br>
<form name="frm" method="get" action="rc.java">
<table border = "0">
<tr align="left" valign="top">
<td>First Name:</td>
<td><input type="text" name ="name" /></td>
</tr>
<tr align="left" valign="top">
<td></td>
<td><input type="submit" value="submit"/></td>
</tr>
</table>
</form>
<%-- --%>
<table border="1">
<tbody>
<tr>
<td><img src="UBLogo.jpg" class ="ublogo" alt="UBLogo"/></td>
<td><strong>RDWeb</strong><img src="RD.png" class ="rd" alt="UBLogo"/></td>
</tbody>
</table>
<table border="1">
<thead>
<tr><th colspan="2">Welcome to Web Tools</th><br>
<th colspan="2">${UserDetails.displayName0}
<br>${UserDetails.Full_User_Name0}</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<form name="info" action="index.jsp">
Enter the UB ID, User Name or Computer Name:</td>
<td><input type="text" name="info" />
<input type="submit" value="OK" />
</form>
</td>
<td><strong>Contact Details: </strong></td>
<td><strong>Email: </strong>${UserDetails.mail0}
<br><strong>IM: </strong>${UserDetails.givenName0} ${UserDetails.sn0}
<br><strong>phone:</strong>${UserDetails.telephoneNumber0}
<br><span style="font-size:smaller; font-style:italic;">
<em>last login: ${UserDetails.Login_Date}</em></span></td>
</tr>
<tr>
<td><strong>AD Site</strong></td>
<td><strong>${UserDetails.AD_Site}</strong></td>
<td><strong>Computer</strong></td>
<td><strong>PC: ${UserDetails.Computer_Name}</strong>
<br><strong>OS: ${UserDetails.Network_Operating_System0}</strong>
<br><strong>IP: ${UserDetails.IP_Address}</strong></td>
</tr>
<tr>
<td>
<form name="hinv" action="index.jsp" />
Hardware Inventory:<input type="submit" value="${UserDetails.Computer_Name}" onsubmit=jsp:setProperty name="hinv"/>
</form>
</td>
<td>
<form name="rc" action="index.jsp" />
Remote Control:<input type="submit" value="${UserDetails.Computer_Name}" onsubmit=jsp:setProperty name="rc"/>
</form>
</td>
<td>
<form name="remx" action="index.jsp" />
RemX_OKillX.exe:<input type="submit" value="${UserDetails.Computer_Name}" onsubmit=jsp:setProperty name="remx"/>
</form>
</td>
<td>
<form name="SOne" action="index.jsp" />
5685-SourceOne.exe:<input type="submit" value="${UserDetails.Computer_Name}" onsubmit=jsp:setProperty name="SOne"/>
</form>
</td>
</tr>
</tbody>
</table>
<br>
<table border="1">
<tbody>
<tr>
<c:forEach var="columnName" items="${result.columnNames}">
<th><c:out value="${columnName}"/></th>
</c:forEach>
</tr>
<!-- column data -->
<c:forEach var="row" items="${result.rowsByIndex}">
<tr>
<c:forEach var="column" items="${row}">
<td><c:out value="${column}"/></td>
</c:forEach>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
RequestDispatcher reqDisp = new RequestDispatcher("index.jsp");
reqDisp.forward(request,response);
or
reqDisp.forward(request,response);
or other way is
response.sendRedirect("/url to call");
RequestDispatcher
forward method pass the control of the request to another servlet or jsp without telling anything about the request dispatch to the client browser. Therefore client browser don't know whether the returned resource is from an another servlet/jsp or not.
sendRedirect
method stop further processing of the request and send http status code "301" and URL of the location to be redirected to the client browser in the response header. Server does not have control of this request after sending the redirect related HTTP header to the client browser. Client browser sees http status 301 and then it know it should send a new request to the url in "Location" http header which is set by server. and Client browser sends a new request to the new URL and it will be processed by the server as another normal request.
Therefore request dispatch happens completely in the server side.
But sendRedirect is handle through the client browser.
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>