1

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>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
                        <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input name="save" type="submit" id="save" value="Save" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Kanika Deka
  • 11
  • 1
  • 2
  • 8
  • Yes. But unable to make workable – Kanika Deka May 05 '11 at 09:29
  • 1
    Which part causing a problem. Have you ever read some tutorials for these. Did you know how to pass the variable from jsp read some here http://stackoverflow.com/questions/3608891/pass-variables-from-servlet-to-jsp – ace May 05 '11 at 10:31

2 Answers2

4

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.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Call the servlet by its URL as you've definied in `web.xml`. If it is for example `/removeCourse` then you need to call it by `http://localhost:8080/ONLINE_EXAM/removeCourse`. You should however also change the `RequestDispatcher` path to `/removeCourse.jsp`. See also our wiki page to learn how to use servlets http://stackoverflow.com/tags/servlets/info – BalusC May 05 '11 at 14:22
  • I use RequestDispatcher to forward the response to jsp. But still it is not working. In my jsp what code should i've to write to get the response from the servlet – Kanika Deka May 05 '11 at 14:58
  • Nothing. You just use `request.setAttribute("courses", courses);` in servlet and it'll be available as `${courses}` in JSP. If you still see a blank page when you invoke the servlet URL, then read the server logs. You only need to ensure that your `web.xml` matches the highest servlet version as supported by the container you're running. – BalusC May 05 '11 at 15:05
  • I am using Netbeans 6.0.1 and my web.xml version is 2.5. Is any problem with this version? – Kanika Deka May 05 '11 at 16:30
  • This is fine. Your problem is caused by something else. Did you read the server logs? Did you read our servlet wiki page? Did you succeed in creating a simple hello world? – BalusC May 05 '11 at 16:31
  • My Other works are function properly. But i m getting problem only with this. – Kanika Deka May 05 '11 at 16:34
  • You need to be more clear about "it is not working". What's the exact use case, the problem symptoms and the detail in server logs? Did you really fix the incorrect code as per the answer and the comments? You also need to pay attention to the hello world example in our wiki page and base the code on that. – BalusC May 05 '11 at 16:35
  • When i give /removeCourse in web.xml then shows an error mark. how can i define it in web.xml – Kanika Deka May 05 '11 at 18:23
1
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>
jmj
  • 237,923
  • 42
  • 401
  • 438