Please help me, I cann't do this for 3rd day((
Here is my web.xml file
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>ebookshopservlet</servlet-name>
<servlet-class>
ebookshop.ShoppingServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ebookshopservlet</servlet-name>
<url-pattern>/eshop</url-pattern>
</servlet-mapping>
</web-app>
I have jsp project, and there is an issue with /ebookshop/eshop url, it constantly writes 404 error - not found. What is my mistake in configuring this web server and application?
there is my servlet
package ebookshop;
import java.util.Vector;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import ebookshop.Book;
import javax.servlet.annotation.WebServlet;
/**
*
* #author Ilqar
*/
public class ShoppingServlet extends HttpServlet{
public void init(ServletConfig conf) throws ServletException {
super.init(conf);
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
doPost(req,res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
// #WebServlet(name = "ShoppingServlet", urlPatterns = {"/eshop"})
HttpSession session;
session = req.getSession();
#SuppressWarnings("unchecked")
Vector<Book> shoplist=(Vector<Book>) session.getAttribute("ebookshop.cart");
String do_this=req.getParameter("do_this");
if (do_this==null)
{
Vector<String> blist=new Vector<String>();
blist.addElement("Learn HTML5 and JavaScript for iOS. Scott Preston $39.99");
blist.addElement("Java 7 for Absolute Beginners. Jay Bryant $39.99");
blist.addElement("Beginning Android 4. Livingston $39.99");
blist.addElement("Pro Spatial with SQL Server 2012. Alastair Aitchinson $59.99");
blist.addElement("Beginning Database Design. Clare Churcher $34.99");
session.setAttribute("ebookshop.list", blist);
ServletContext sc=getServletContext();
RequestDispatcher rd=sc.getRequestDispatcher("/");
rd.forward(req, res);
}
else {
if (do_this.equals("checkout"))
{
float dollars=0;
int books=0;
for (Book abook: shoplist)
{
dollars+=abook.getPrice()*abook.getQuantity();
books+=abook.getQuantity();
}
req.setAttribute("dollars", new Float(dollars).toString());
req.setAttribute("books", new Integer(books).toString());
ServletContext sc=getServletContext();
RequestDispatcher rd=sc.getRequestDispatcher("/Checkout.jsp");
rd.forward(req, res);
} // end if (do_this.equals("checkout"))
else {
if (do_this.equals("remove")){
String pos=req.getParameter("position");
shoplist.removeElementAt((new Integer(pos)));
}
else if (do_this.equals("add"))
{
boolean found=false;
Book abook=getBook(req);
if (shoplist==null)
{
shoplist=new Vector<Book>();
shoplist.addElement(abook);
}
else
{
for (int i=0;i<shoplist.size() && !found;i++)
{
Book b= (Book) shoplist.elementAt(i);
if (b.getTitle().equals(abook.getTitle()))
{
b.setQuantity(b.getQuantity()+abook.getQuantity());
shoplist.setElementAt(b, i);
found=true;
}
}
if (!found)
{
shoplist.addElement(abook);
}
}
}
session.setAttribute("ebookshop.cart", shoplist);
ServletContext sc=getServletContext();
RequestDispatcher rd=sc.getRequestDispatcher("/");
rd.forward(req, res);
}
}
}
public Book getBook(HttpServletRequest req){
String myBook=req.getParameter("book");
int n=myBook.indexOf("$");
String name=myBook.substring(0, n);
String price=myBook.substring(n+1);
String qty=req.getParameter("qty");
return new Book(name,Float.parseFloat(price),Integer.parseInt(qty));
}
}
and my index.jsp file
<%--
Document : ebookshop_index
Created on : 22.07.2015, 21:33:24
Author : Ilqar
--%>
<%#page contentType="text/html" pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%#page session="true" import="java.util.*,ebookshop.Book" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>E-bookshop</title>
<style type="text/css">
body {background-color: gray; font-size: 10pt;}
h1 {font-size: 20pt}
table {background-color: white;}
</style>
</head>
<body>
<h1>Your online Bookshop!</h1>
<% //Scriplet 1 checks whether the booklist is ready
Vector<ebookshop.Book> booklist=(Vector<ebookshop.Book>)session.getAttribute("ebookshop.list");
if (booklist==null)
{
response.sendRedirect("/ebookshop/eshop");
}
else {
%>
<form name="addForm" method="POST" action="eshop">
<input type="hidden" name="do_this" value="add">
Book:
<select name="book">
<% //Scriplet the booklist to the selection control
for (int i=0;i<booklist.size();i++)
{
out.println("<option>"+booklist.elementAt(i).getTitle()+"</option>");
}
%>
</select>
Quantity: <input type="text" name="qty" value="1" size="3">
<input type="submit" value="Add to Cart">
</form>
<p/>
<% //Scriplet 3 check whether the shopping cart is empty
Vector shoplist=
(Vector<ebookshop.Book>)session.getAttribute("ebookshop.cart");
if ((shoplist!=null) && (shoplist.size()>0)){
%>
<table style="border: 1px; padding: 2px">
<tr>
<td>TITLE</td>
<td>PRICE</td>
<td>QUANTITY</td>
<td></td>
</tr>
<% //Scriplet show the books in shopping cart
for (int i=0;i<shoplist.size();i++)
{
Book aBook=(Book)shoplist.elementAt(i);
%>
<tr>
<form name="removeForm" action="eshop" method="POST">
<input type="hidden" name="position" value="<%=i%>">
<input type="hidden" name="do_this" value="remove">
<td>
<%=aBook.getTitle()%>
</td>
<td style="text-align: right">
<%=aBook.getPrice()%>
</td>
<td style="text-align: right">
<%=aBook.getQuantity()%>
</td>
</form>
</tr>
<%
}
%>
</table>
<p/>
<form name="checkoutForm" action="eshop" method="POST">
<input type="hidden" value="checkout" name="do_this">
<input type="submit" value="Checkout">
</form>
<%
}
}
%>
</body>
</html>
I guess it sends redirect to the servlet when session attribute is null
It worked! I have forgotten to put annotation before the servlett class, that is why it couldn't find the page. Author of the book didn't put, maybe cause it wasn't used that time. I just put
#WebServlet(name = "ShoppingServlet", urlPatterns = {"/eshop"})
and standart web.xml and all worked! I used Tomcat server, and hope it will work for Glassfish also.
Related
I made my first Java Servlet application with JSPs to create a record about books and display them. The index.html page loads well but the other pages in the project don't work when deployed on GoogleAppEngine. The same project works well when run locally on App Engine through eclipse. I have also enabled sessions in the "appengine-web.xml" but the problem persists. The application works perfectly fine when run locally.
Running through the app engine I get the error -
Error: Not Found
The requested URL /BookApp was not found on this server.
Directory Structure
Servlet code :
package com.nh;
import com.books.Book;
import java.util.*;
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;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class BookApp
*/
#WebServlet("/BookApp")
public class BookApp extends HttpServlet {
private static final long serialVersionUID = 1L;
ArrayList<Book>Books = new ArrayList<Book>();
static int id = 0;
/*List<String> BookNames = new ArrayList<String>();
List<String> Authors = new ArrayList<String>();
List<String> Costs = new ArrayList<String>();*/
/**
* #see HttpServlet#HttpServlet()
*/
public BookApp() {
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
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
String bookName = request.getParameter("bookname");
String author = request.getParameter("authorname");
String bookCost = request.getParameter("cost");
String url = ("");
HttpSession session=request.getSession(true);
Book newBook = new Book();
if(bookName.length()!=0&&author.length()!=0&&bookCost.length()!=0)
{
newBook.setAuthorName(author);
newBook.setName(bookName);
newBook.setCost(Float.parseFloat(bookCost));
newBook.setId(id++);
Books.add(newBook);
}
session.setAttribute("Books", Books);
request.setAttribute("Books", Books);
System.out.println(Books.get(0).getName());
url = ("/listBooks.jsp");
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Create a book entry</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Create A Book</h2>
<form action="BookApp" method="post">
<div class="form-group">
<label for="Title">Title:</label>
<input type="text" class="form-control" id="tbBook" placeholder="Enter Title" name="bookname" required>
</div>
<div class="form-group">
<label for="author">Author:</label>
<input type="text" class="form-control" id="authorname" placeholder="Enter Author" name="authorname" required>
</div>
<div class="form-group">
<label for="cost">Cost:</label>
<input type="text" class="form-control" id="tbCost" placeholder="Enter Cost" name="cost" required>
</div>
<button type="submit" class="btn btn-default">Create</button>
</form>
</div>
</body>
</html>
listBook.jsp :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="com.books.Book" %>
<%# page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>List of books</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Book List</h2>
<table class="table table-hover">
<thead>
<tr>
<th>Sr No.</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<%
ArrayList<Book> posts=(ArrayList<Book>) request.getAttribute("Books");
for (Book book: posts) {
%>
<%session.setAttribute("Books", posts); %>
<tr>
<td><%=book.getId()+1 %></td>
<td><%=book.getName()%></td>
</tr>
<%}%>
</tbody>
</table>
</div>
</body>
</html>
appengine-web.xml
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<threadsafe>true</threadsafe>
<sessions-enabled>true</sessions-enabled>
<runtime>java8</runtime>
<system-properties>
<property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
</system-properties>
</appengine-web-app>
As you're using Java8 (<runtime>java8</runtime>) and as per Google App engine specification try implementing this way :
// With #WebServlet annotation the webapp/WEB-INF/web.xml is no longer required.
#WebServlet(name = "requests", description = "Requests: Trivial request", urlPatterns = "/requests")
public class RequestsServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
}
}
Reference : how-requests-are-handled-app-engine
One more advice : do not use camelCase while naming your url pattern.
This is my jsp code:-
<%#page import="java.sql.*"%>
<%# 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>
<body>
<div id="header">
<center>
<div id="over">
<p> <font size="18" color="Brown"><b>UBONA Technologies</b></font></p>
</div>
</center>
</div>
<br><br><br><br><br><br>
<form method="get" action="controller.java">
<div class="container">
<center>
<table tableborder=0>
<tr><td><label><font size="5" color="BLACK"><b>USERNAME</b></font></label></td>
<br>
<td><input type="text" placeholder="Enter User Name" name="username" class="inputi" required></td>
</tr><br>
<tr><td><label><font size="5" color="BLACK"><b>PASSWORD</b></font></label></td>
<br>
<td><input type="password" placeholder="Enter Password" name="password" class="inputi" required></td>
</tr><br>
</table><br>
<input type="submit" class="button" name="submit" value="LOGIN" />
</center></div>
</form>
</body>
</html>
This is my Servlets code :-
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.sql.*;
//#WebServlet("/controller")
public class controller extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e)
{
}
try
{
String uname = request.getParameter("username");
String paswd = request.getParameter("password");
Connection con= null;
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","6q190No6#");
Statement s = con.createStatement();
ResultSet rs=s.executeQuery("select * from credentials");
rs.next();
String username1 = rs.getString("username");
String password2 = rs.getString("password");
if(uname.equals(username1) && paswd.equals(password2))
{
response.sendRedirect("welcome.jsp");
}
else
{
response.sendRedirect("wrongpas.jsp");
}
rs.close();
}
catch(SQLException sqe)
{
System.out.println("home"+sqe);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
}
this is my web.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>/controller</url-pattern>
</servlet-mapping>
</web-app>
I have changed the location of tomcat server as suggested in some videos.
As I saw some replies to the same question which were saying that save class to the root folder/ web-inf/classes i am unable to find that folder too.
If you don't have WEB-INF/classes create it manually and save your class there.
Put your needed jars into WEB-INF/lib/.
First modify your form tag to
<form id="login" action="${pageContext.request.contextPath}/controller" method="GET">
Add id attribute
<input type="text" placeholder="Enter User Name" name="username" id="username" class="inputi" required>
also in here
<input type="password" placeholder="Enter Password" name="password" id="username" class="inputi" required>
Second remove your comment on annotation
//#WebServlet("/controller")
Make it
#WebServlet(name = "controller", urlPatterns = {"/controller"})
Import annotations
import javax.servlet.annotation.WebServlet;
Remove doPost it does nothing in your case.
You don't need web.xml also.
Recommends
Your class name should start with capital letter.
urlPatterns should be different from your class name.
Following changes will resolve your issue:
In JSP code:
<form role="form" method="get" action="${pageContext.request.contextPath}/controller">
In Servlet code:
#WebServlet("/controller")
Adding above line of code will prompt you to import Webservlet annotations library:
import javax.servlet.annotation.WebServlet;
Also it is considered a good practice to begin Java class names with Uppercase
i.e controller.java should be Controller.java
I have to load some values from servlet to jsp page
My "order_processing.jsp" JSP Page code is given below
<%#page import="test.abc.io.User_Objects"%>
<%# page import="java.util.Date" %>
<%# 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>Order Processing</title>
</head>
<body>
<form name="OrderProcessing" action="order_processing" method="post" onsubmit="return validateForm();">
<table align="center">
<tr align="center">
<td colspan="2">
<img src="images/otn_logo.jpg"/>
</td>
</tr>
<tr>
<td>First Name :</td>
<td><input type="text" id="txtFirstname" name="txtFirstname" value="${reqObj.firstname}" /></td>
</tr>
<tr>
<td>Last Name :</td>
<td><input type="text" id="txtLastname" name="txtLastname" value="${reqObj.lastname}" /></td>
</tr>
<tr>
<td>Communication Email :</td>
<td><input type="text" id="txtCommunicationEmail" name="txtCommunicationEmail" value="${reqObj.commEmail}" />
<label style="color: red;">*</label></td>
</tr>
<tr align="left">
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
My User_Objects code
public class User_Objects {
public String firstname;
public String lastname;
public String commEmail;
}
My "OrderProcessing" code
import java.io.IOException;
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 OrderProcessing extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
User_Objects fillObj = new User_Objects();
fillObj.firstname = "Test";
fillObj.lastname = "User1";
fillObj.commEmail = "tuser01#xyz.com";
request.setAttribute("reqObj", fillObj);
RequestDispatcher view = request.getRequestDispatcher("/order_processing.jsp");
view.forward(request, response);
} catch (Exception e) {
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("into OrderProcessing java");
}
}
My web.xml code
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>OrderProcessing</display-name>
<welcome-file-list>
<welcome-file>order_processing.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>order_processing</servlet-name>
<servlet-class>test.abc.io.OrderProcessing</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>order_processing</servlet-name>
<url-pattern>/order_processing</url-pattern>
</servlet-mapping>
</web-app>
When i debug this project and click on Submit button its gives the following error:
SEVERE: Servlet.service() for servlet jsp threw exception
javax.el.PropertyNotFoundException: Property 'firstname' not found on type test.abc.io.User_Objects
and I also want to do some task on "order_processing.jsp" page load.
but when i run this project, my order_processing.jsp page display successfully but on that case my doGet method of OrderProcessing.java did not call.
I am using JAVA with Eclipse Mars.
The object "User_Objects" is no java bean:
firstname, lastName and commEMail are fields and not properties.
Try to add a getter / setter for firstName, lastName and commEMail
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>