Java Servlet and Swing Code Examples
Result Servlet
This servlet generates random numbers and forwards to Guess.html.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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;
@WebServlet("/Result")
public class Result extends HttpServlet {
private static final long serialVersionUID = 1L;
public Result() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = getServletContext();
HttpSession session = request.getSession(true);
String seed = request.getParameter("seed");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println(seed);
Random r1 = new Random();
Integer rr1 = r1.nextInt(4) + 1;
Random r2 = new Random();
Integer rr2 = r2.nextInt(4) + 1;
Random r3 = new Random();
Integer rr3 = r3.nextInt(4) + 1;
System.out.println("The random number is: " + rr1 + " & " + rr2 +" & " +rr3);
session.setAttribute("random1", rr1);
session.setAttribute("random2", rr2);
session.setAttribute("random3", rr3);
RequestDispatcher dispatcher = context.getRequestDispatcher("/Guess.html");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
FinalResult Servlet
This servlet checks user guesses against random numbers.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.ServletContext;
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;
@WebServlet("/FinalResult")
public class FinalResult extends HttpServlet {
private static final long serialVersionUID = 1L;
public FinalResult() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = getServletContext();
HttpSession session = request.getSession(true);
String g1 = (String) request.getParameter("guess1");
String g2 = (String) request.getParameter("guess2");
String g3 = (String) request.getParameter("guess3");
int Realg1 = Integer.parseInt(g1);
int Realg2 = Integer.parseInt(g2);
int Realg3 = Integer.parseInt(g3);
PrintWriter out = response.getWriter();
response.setContentType("text/html");
System.out.println("Your guess is: " + Realg1 + " & " + Realg2 +" & " +Realg3);
Integer getr1 = (Integer) session.getAttribute("random1");
System.out.println(getr1);
Integer getr2 = (Integer) session.getAttribute("random2");
System.out.println(getr2);
Integer getr3 = (Integer) session.getAttribute("random3");
System.out.println(getr3);
if (Realg1 == getr1 && Realg2 == getr2 && Realg3 == getr3) {
out.println("All hit!");
}
if (Realg1 == getr1) {
out.println("Hit, ");
} else {
out.println("Miss! Your guess is [");
out.println("Miss, ");
}
if (Realg2 == getr2) {
out.println("Hit, ");
} else {
out.println("Miss, ");
}
if (Realg3 == getr3) {
out.println("Hit");
out.println("]");
} else {
out.println("Miss");
out.println("]");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
ShapeFrame (Swing)
This Swing application displays a random colored circle.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class ShapeFrame extends JFrame {
public ShapeFrame() {
setLayout(new GridLayout(1,2,5,5));
ImageIcon iconblue = new ImageIcon(new ImageIcon("/Users/calvinlee/Desktop/Test3/Test3A/CircleBlue.jpg").getImage().getScaledInstance(200, 100, Image.SCALE_DEFAULT));
ImageIcon iconred = new ImageIcon(new ImageIcon("/Users/calvinlee/Desktop/Test3/Test3A/CircleRed.jpg").getImage().getScaledInstance(200, 100, Image.SCALE_DEFAULT));
ImageIcon icongreen = new ImageIcon(new ImageIcon("/Users/calvinlee/Desktop/Test3/Test3A/CircleGreen.jpg").getImage().getScaledInstance(200, 100, Image.SCALE_DEFAULT));
JLabel newimglabel = new JLabel();
add(newimglabel);
JButton jbtGet = new JButton("Random");
JPanel panel = new JPanel();
add(panel);
panel.add(jbtGet);
jbtGet.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
Random r1 = new Random();
Integer rand1 = r1.nextInt(3);
System.out.println(rand1);
if (rand1 == 0) {
newimglabel.setIcon(iconblue);
} else if (rand1 == 1) {
newimglabel.setIcon(iconred);
} else if (rand1 > 1) {
newimglabel.setIcon(icongreen);
}
}
});
}
public static void main(String[] args){
ShapeFrame frame = new ShapeFrame();
frame.setTitle("ShowGridLayout");
frame.setSize(400,200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
ShapeFrame (Swing with Shape Calculations)
This Swing application calculates area and perimeter of shapes.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ShapeFrame extends JFrame {
public ShapeFrame(){
GridLayout GridLayout1 = new GridLayout(7,2,5,5);
JButton jbtGet = new JButton("Get results");
setLayout(GridLayout1);
add(new JLabel("Choose shape:'s','r'or'c'"));
JTextField JTFtype= new JTextField(1);
add(JTFtype);
add(new JLabel("Input radius of circle"));
JTextField JTFRadius= new JTextField(8);
add(JTFRadius);
add(new JLabel("Input length of square or rectangle"));
JTextField JTFLength= new JTextField(8);
add(JTFLength);
add(new JLabel("Input width of rectangle"));
JTextField JTFWidth= new JTextField(8);
add(JTFWidth);
add(new JLabel("Area"));
JTextField JTFArea= new JTextField(8);
add(JTFArea);
add(new JLabel("Perimeter"));
JTextField JTFPerimeter = new JTextField(8);
add(JTFPerimeter);
JPanel panel = new JPanel();
add(panel);
panel.add(jbtGet);
jbtGet.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
String type = JTFtype.getText();
float length;
switch(type){
case "c": //circle
float radius = Float.parseFloat(JTFRadius.getText());
Circle circle = new Circle(radius);
circle.computeArea();
circle.computePerimeter();
JTFArea.setText(String.valueOf(circle.area));
JTFPerimeter.setText(String.valueOf(circle.perimeter));
break;
case "s": //square
length = Float.parseFloat(JTFLength.getText());
Square square = new Square(length);
square.computeArea();
square.computePerimeter();
JTFArea.setText(String.valueOf(square.area));
JTFPerimeter.setText(String.valueOf(square.perimeter));
break;
case "r": //rectangle
length = Float.parseFloat(JTFLength.getText());
float width = Float.parseFloat(JTFWidth.getText());
Rectangle rectangle = new Rectangle(length,width);
rectangle.computeArea();
rectangle.computePerimeter();
JTFArea.setText(String.valueOf(rectangle.area));
JTFPerimeter.setText(String.valueOf(rectangle.perimeter));
break;
}
}
});
}
public static void main(String[] args){
ShapeFrame frame = new ShapeFrame();
frame.setTitle("ShowGridLayout");
frame.setSize(500,500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Drawable Interface
public interface Drawable {
void draw();
}
Abstract Shape Class
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public abstract class Shape {
public float area;
public float perimeter;
public int x;
public Shape() {
area = 0;
}
abstract public String getClassName();
abstract public void readShape();
abstract public void computeArea();
abstract public void computePerimeter();
abstract public void displayShape();
}
Picture Class
public class Picture {
private int arrayCounter;
private Shape[] shapes = new Shape[10];
public Picture() {
}
public void addShape(Shape s) {
shapes[arrayCounter] = s;
arrayCounter = arrayCounter + 1;
}
public void computeShape() {
for (int i = 0; i < arrayCounter; i++) {
shapes[i].computeArea();
shapes[i].computePerimeter();
}
}
public void listAllShapeTypes() {
for (int i = 0; i < arrayCounter; i++) {
shapes[i].displayShape();
}
}
public void listSingleShapeType(String className) {
for (int i = 0; i < arrayCounter; i++) {
if (className.equals(shapes[i].getClassName())) {
shapes[i].displayShape();
}
}
}
}
JavaUser Class
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class JavaUser {
public JavaUser() {
}
public static void main(String[] args) throws IOException {
boolean exitFlag = true;
while (exitFlag) {
System.out.println("**************************************");
System.out.println("* Please choose one the followings: *");
System.out.println("* Press 'c' - circle *");
System.out.println("* Press 's' - square *");
System.out.println("* Press 'r' - rectangle *");
System.out.println("* Press 'x' - exit *");
System.out.println("**************************************");
char input = (char) System.in.read();
switch (input) {
case 'c':
Shape circle = new Circle();
circle.readShape();
circle.computeArea();
circle.computePerimeter();
circle.displayShape();
break;
case 's':
Shape square = new Square();
square.readShape();
square.computeArea();
square.computePerimeter();
square.displayShape();
break;
case 'r':
Shape rectangle = new Rectangle();
rectangle.readShape();
rectangle.computeArea();
rectangle.computePerimeter();
rectangle.displayShape();
break;
case 'x':
exitFlag = false;
break;
default:
System.out.println("Invalid command!");
break;
}
}
}
}
Circle Class
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Circle extends Shape {
private float radius;
private Scanner scanner;
private String stringIn;
public void readShape() {
System.out.println("Please input the radius: ");
scanner = new Scanner(System.in);
radius = scanner.nextFloat();
}
public void computeArea() {
area = (float) Math.PI * radius * radius;
}
public void computePerimeter() {
perimeter = 2 * radius * (float) Math.PI;
}
public void displayShape() {
System.out.println("Area of circle = " + Float.toString(area));
System.out.println("Perimeter of circle = " + Float.toString(perimeter));
}
public Circle() {
this.radius = 0;
}
public Circle(float r) {
this.radius = r;
}
public String getClassName() {
return (this.getClass().getSimpleName());
}
}
Rectangle Class
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Rectangle extends Shape {
private float width;
private float length;
private Scanner scanner;
private String stringIn;
public String getClassName() {
return (this.getClass().getSimpleName());
}
public void readShape() {
System.out.println("Please input the length: ");
scanner = new Scanner(System.in);
length = scanner.nextFloat();
System.out.println("Please input the width: ");
scanner = new Scanner(System.in);
width = scanner.nextFloat();
}
public void computeArea() {
area = length * width;
}
public void computePerimeter() {
perimeter = 2 * (length + width);
}
public void displayShape() {
System.out.println("Area of rectangle = " + Float.toString(area));
System.out.println("Perimeter of rectangle= " + Float.toString(perimeter));
}
public Rectangle() {
this.length = 0;
}
public Rectangle(float l, float w) {
this.length = l;
this.width = w;
}
}
Canvas Class
import javax.swing.*;
import java.awt.*;
public class Canvas {
private JFrame frame;
private CanvasPane canvas;
private Graphics2D graphic;
private Color backgroundColour;
private Image canvasImage;
public Canvas(String title) {
this(title, 300, 300, Color.white);
}
public Canvas(String title, int width, int height) {
this(title, width, height, Color.white);
}
public Canvas(String title, int width, int height, Color bgColour) {
frame = new JFrame();
canvas = new CanvasPane();
frame.setContentPane(canvas);
frame.setTitle(title);
canvas.setPreferredSize(new Dimension(width, height));
backgroundColour = bgColour;
frame.pack();
}
public void setVisible(boolean visible) {
if (graphic == null) {
Dimension size = canvas.getSize();
canvasImage = canvas.createImage(size.width, size.height);
graphic = (Graphics2D) canvasImage.getGraphics();
graphic.setColor(backgroundColour);
graphic.fillRect(0, 0, size.width, size.height);
graphic.setColor(Color.black);
}
frame.show();
}
public boolean isVisible() {
return frame.isVisible();
}
public void draw(Shape shape) {
graphic.draw(shape);
canvas.repaint();
}
public void fill(Shape shape) {
graphic.fill(shape);
canvas.repaint();
}
public void erase() {
Color original = graphic.getColor();
graphic.setColor(backgroundColour);
Dimension size = canvas.getSize();
graphic.fill(new java.awt.Rectangle(0, 0, size.width, size.height));
graphic.setColor(original);
canvas.repaint();
}
public void erase(Shape shape) {
Color original = graphic.getColor();
graphic.setColor(backgroundColour);
graphic.fill(shape);
graphic.setColor(original);
canvas.repaint();
}
public void eraseOutline(Shape shape) {
Color original = graphic.getColor();
graphic.setColor(backgroundColour);
graphic.draw(shape);
graphic.setColor(original);
canvas.repaint();
}
public boolean drawImage(Image image, int x, int y) {
boolean result = graphic.drawImage(image, x, y, null);
canvas.repaint();
return result;
}
public void drawString(String text, int x, int y) {
graphic.drawString(text, x, y);
canvas.repaint();
}
public void eraseString(String text, int x, int y) {
Color original = graphic.getColor();
graphic.setColor(backgroundColour);
graphic.drawString(text, x, y);
graphic.setColor(original);
canvas.repaint();
}
public void drawLine(int x1, int y1, int x2, int y2) {
graphic.drawLine(x1, y1, x2, y2);
canvas.repaint();
}
public void setForegroundColour(Color newColour) {
graphic.setColor(newColour);
}
public Color getForegroundColour() {
return graphic.getColor();
}
public void setBackgroundColour(Color newColour) {
backgroundColour = newColour;
graphic.setBackground(newColour);
}
public Color getBackgroundColour() {
return backgroundColour;
}
public void setFont(Font newFont) {
graphic.setFont(newFont);
}
public Font getFont() {
return graphic.getFont();
}
public void setSize(int width, int height) {
canvas.setPreferredSize(new Dimension(width, height));
Image oldImage = canvasImage;
canvasImage = canvas.createImage(width, height);
graphic = (Graphics2D) canvasImage.getGraphics();
graphic.drawImage(oldImage, 0, 0, null);
frame.pack();
}
public Dimension getSize() {
return canvas.getSize();
}
public void wait(int milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
}
}
private class CanvasPane extends JPanel {
public void paint(Graphics g) {
g.drawImage(canvasImage, 0, 0, null);
}
}
}
OrderServlet
package bookstore;
import java.io.IOException;
import java.util.ArrayList;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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;
@WebServlet("/OrderServlet")
public class OrderServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public OrderServlet() {
super();
}
@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = "/show-order.jsp";
ShoppingCart cart;
ArrayList<Book> books;
HttpSession session = request.getSession(false);
if (session == null) {
url = "/SearchBook.html";
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher(url);
dispatcher.forward(request, response);
} else {
session = request.getSession(true);
PrintWriter out = response.getWriter();
out.println("fuck");
}
cart = (ShoppingCart) session.getAttribute("cart");
if (cart == null) {
cart = new ShoppingCart();
session.setAttribute("cart", cart);
}
books = (ArrayList<Book>) session.getAttribute("foundBooks");
int index = Integer.parseInt(request.getParameter("index"));
cart.addBook(books.get(index));
url = "/show-order.jsp";
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
QueryServlet
package bookstore;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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;
@WebServlet("/QueryServlet")
public class QueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public QueryServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
java.sql.Connection connection = null;
java.sql.Statement statement = null;
java.sql.ResultSet resultSet = null;
String DATABASE_URL = "jdbc:mysql://localhost:3306/books";
ArrayList<Book> foundBooks = new ArrayList<Book>();
HttpSession session = request.getSession(true);
String isbn = (String) request.getParameter("isbn");
String author = (String) request.getParameter("author");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
connection = java.sql.DriverManager.getConnection(DATABASE_URL, "guest", "guest");
statement = connection.createStatement();
String query = "SELECT * FROM bookinfo WHERE ISBN=" + "'" + isbn + "'" + " or Author=" + "'" + author + "'";
System.out.println(query);
resultSet = statement.executeQuery(query);
while (resultSet.next() == true) {
isbn = (String) resultSet.getObject(1);
String title = (String) resultSet.getObject(2);
author = (String) resultSet.getObject(3);
int edition = (Integer) resultSet.getObject(4);
String publisher = (String) resultSet.getObject(5);
String copyright = (String) resultSet.getObject(6);
double price = (Double) resultSet.getObject(7);
foundBooks.add(new Book(isbn, author, title, price, edition, publisher, copyright));
System.out.println(title + "; " + edition + "; " + publisher + "; " + copyright);
}
session.setAttribute("foundBooks", foundBooks);
String url = "/BookInfo.jsp";
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher(url);
dispatcher.forward(request, response);
} catch (java.sql.SQLException sqlException) {
sqlException.printStackTrace();
} finally {
try {
resultSet.close();
statement.close();
connection.close();
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
}
BookInfo.jsp
Book Info.
<% ArrayList books = (ArrayList)session.getAttribute("foundBooks");
int numBooks = books.size();
%>
The time now is:
<th>ISBN</th>
<th>Title</th>
<th>Author</th>
<th>Edition Number</th>
<th>Publisher</th>
<th>Copyright</th>
<% for (int i = 0; i < numBooks; i++) {
Book book;
String author = "?";
String isbn = "?";
String title = "?";
String editionNumber = "?";
String publisher = "?";
String copyright = "?";
int index = i;
book = books.get(i);
author = book.getAuthor();
isbn = book.getIsbn();
title = book.getTitle();
editionNumber = String.valueOf(book.getEdition());
publisher = book.getPublisher();
copyright = book.getCopyright();
%>
<th><a href= "OrderServlet?index=<%=i%>" > Add to Cart</a></th>
check-out.jsp
Check Out
<% ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
double total = cart.getTotalPrice();
%>
Your total purchase is: <%=total %>
To purchase the item in your shopping cart, please provide us the following information:
Name:
Credit Card Number
remove-all.jsp
Remove All Items
<% ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
cart.clear();
session.setAttribute("cart",cart);
%>
SearchBook.jsp
Online
Bookstore
function validateForm() {
var isbn = document.search.isbn.value;
var author = document.search.author.value;
// Make sure that either of the text boxes has been filled
// Put your code here
}
function isBlank(s) {
var i
for (i = 0; i
if (s.charAt(i) != ” “)
return false
}
return true
}
// Create a Date object using new Date(). Then call the getHours(), getMinutes(),
// getDate(), getMonth(), and getFullYear() method of the Date object.
// Put your code here
Please choose
either ISBN or Author to search books:
Search
by ISBN: “text”
name=“isbn” size=20 value=“0132404168”>
Search
by Author: “text”
name=“author” size=19 value=“Paul Deitel”>
//show-order.jsp
pageEncoding=“ISO-8859-1”%>
Show
Order
// Get the shopping cart object. From the cart object, get the number of books
// Put your code here
ShoppingCart cart = (ShoppingCart)session.getAttribute(“cart”);
int numBooks = cart.size();
%>
You have
item(s) in your shopping cart
if (numBooks > 0) { %>
//Receiptservlet.java
package bookstore;
import java.io.IOException;
import java.io.PrintWriter;
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 ReceiptServlet
*/
@WebServlet(“/ReceiptServlet”)
public class ReceiptServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ReceiptServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get the customer name that the user inputs in the check-out.jsp
// Get a PrintWriter object and set content type to “text/html”
HttpSession session = request.getSession(true);
response.setContentType(“text/html”);
String customerName = (String)request.getParameter(“customerName”);
PrintWriter out = response.getWriter();
/*
* Assume perform credit card transaction here
*/
// Print transaction info and foward to SearchBook.html after 5 seconds
// Note that it is better to implement the following part in another JSP.
// It is put here because the information is simple enough to be displayed by a servlet.
String outStr = “”;
outStr
+= “Dear ” + customerName + ” , thanks for purchasing books from
BookStore
\n”;
outStr
+= “This page will be automatically go back to
SearchBook.html
\n”;
outStr
+= “
\n”;
                               outStr
+= “
\n”;
                               out.print(outStr);
                               out.close();                            Â
               }
}
//shopping Cart
package bookstore;
import java.util.ArrayList;
public class ShoppingCart extends ArrayList {
      private static final long serialVersionUID = 1L;
      public ShoppingCart() {
      }
      public void addBook(Book book) {
             this.add(book);
      }
      public Book getBook(int i) {
             return this.get(i);
      }
      public double getTotalPrice() {
             double price = 0.0;
             for (Book book : this) {
                    price += book.getPrice();
             }
             return price;
      }
}
//Bookstore
package bookstore;
import java.io.Serializable;
public class Book implements Serializable {
      private static final long serialVersionUID = 1L;
      private String isbn;
      private String author;
      private String title;
      private double price;
      private int edition;
      private String publisher;
      private String copyright;
      public Book(String isbn, String author, String title, double price, int edition, String publisher, String copyright) {
             this.isbn = isbn;
             this.author = author;
             this.title = title;
             this.price = price;
             this.edition = edition;
             this.publisher = publisher;
             this.copyright = copyright;
      }
      public String getIsbn() {
             return isbn;
      }
      public String getAuthor() {
             return author;
      }
      public int getEdition() {
             return edition;
      }
      public String getPublisher() {
             return publisher;
      }
      public String getCopyright() {
             return copyright;
      }
      public String getTitle() {
             return title;
      }
      public void setTitle(String title) {
             this.title = title;
      }
      public double getPrice() {
             return price;
      }
      public void setPrice(double price) {
             this.price = price;
      }
}
//Bookstore.java
package bookstore;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class bookstore
 */
@WebServlet(“/bookstore”)
public class bookstore extends HttpServlet {
               private static final long serialVersionUID = 1L;
   /**
    * @see HttpServlet#HttpServlet()
    */
   public bookstore() {
       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);
               }
}
//ATM.html
Insert
title here
     Â
Please select the amount that you want to withdraw from your account?
            Â
“radio” name=“Amount” value=“1”>1Â Â Â Â Â Â Â Â Â Â Â Â Â
“radio” name=“Amount” value=“10”>10Â Â Â Â Â Â Â Â Â Â Â Â Â
“radio” name=“Amount” value=“100”>100Â Â Â Â Â Â Â Â Â Â Â Â Â
“radio” name=“Amount” value=“1000”>1000Â Â Â Â Â Â Â Â Â Â Â Â Â
Please select the amount that you want to deposit123 into your account?
            Â
“radio” name=“Amount” value=“1”>1Â Â Â Â Â Â Â Â Â Â Â Â Â
“radio” name=“Amount” value=“10”>10Â Â Â Â Â Â Â Â Â Â Â Â Â
“radio” name=“Amount” value=“100”>100Â Â Â Â Â Â Â Â Â Â Â Â Â
“radio” name=“Amount” value=“1000”>1000//CreditServlet.java
package eie3320;
import java.io.IOException;
import java.io.PrintWriter;
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 CreditServer
 */
@WebServlet(“/CreditServer”)
public class CreditServer extends HttpServlet {
               private static final long serialVersionUID = 1L;
   String amount=””;
   int netAmount;
   String cTotal;
   /**
    * @see HttpServlet#HttpServlet()
    */
   public CreditServer() {
       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
                               try{
                                               amount= request.getParameter(“Amount”);
                                               //response.getWriter().append(amount).append(request.getContextPath());
                                               PrintWriter out = response.getWriter();
                                               HttpSession session = request.getSession(false);
                                               if(session ==null) {
                                               session = request.getSession(true);
                                               netAmount = 1000;
                                               netAmount = netAmount + Integer.parseInt(amount);
                                               amount = “”+ netAmount;
                                               session.setAttribute(“netAmount”, amount);
                                               out.println(“Your account Balance is: “+ amount);
                                               out.println(“http://localhost:8080/EIE3320WebApp/ATM.html\“> Click here to return to the main page.”);}
                                               else {
                                                               cTotal = (String) session.getAttribute(“netAmount”);
                                                               session = request.getSession(true);
                                                               netAmount= Integer.parseInt(cTotal)+Integer.parseInt(amount);
                                                               amount = “”+ netAmount;
                                                               session.setAttribute(“netAmount”, amount);
                                                               out.println(“Your account balance is: ” + amount);
                                                               out.println(“http://localhost:8080/EIE3320WebApp/ATM.html\“> Click here to return to the main page..”);
                                               }
                               } catch(Exception exception) {
                                               exception.printStackTrace();
                                               }
               }
               /**
                * @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);
               }
}
//CheckBalanceServlet.java
package eie3320;
import java.io.IOException;
import java.io.PrintWriter;
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 CheckBalanceServlet
 */
@WebServlet(“/CheckBalanceServlet”)
public class CheckBalanceServlet extends HttpServlet {
               private static final long serialVersionUID = 1L;
   String amount=””;
   /**
    * @see HttpServlet#HttpServlet()
    */
   public CheckBalanceServlet() {
       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
                               try{
                                               //amount= request.getParameter(“Amount”);
                                               //response.getWriter().append(amount).append(request.getContextPath());
                                               //response.setContentType(“text/plain”);
                                               PrintWriter out = response.getWriter();
                                               HttpSession session = request.getSession(false);
                                               if(session ==null) {
                                               session = request.getSession(true);
                                               session.setAttribute(“netAmount”, “1000”);      Â
                                               out.println(“Your account balance is: ” + amount);
                                               out.println(“http://localhost:8080/EIE3320WebApp/ATM.html\“> Click here to return to the main page.”);}
else {
amount = (String) session.getAttribute(“netAmount”);
                                                               out.println(“Your account balance is: ” + amount);
                                                               out.println(“http://localhost:8080/EIE3320WebApp/ATM.html\“> Click here to return to the main page..”);
}
                               } catch(Exception exception) {
                                               exception.printStackTrace();
                                               }
               }
/**
                * @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);
               }
}
//Tut 3
public class Course
{
   private String courseName;
   private int testMarks;
   /**
    * Constructor for objects of class Course
    */
   public Course(String courseName, int testMarks)
   {
       this.courseName=courseName;// initialise instance variables
this.testMarks=testMarks;
   }
   public String toString(){
       return courseName + “, “+Integer.valueOf(testMarks);}
}
public class UniversityStudent
{
   // instance variables – replace the example below with your own
   private int x;
   private String studentName;
   private int courseNumber;
   private Course[] list = new Course[10];
   /**
    * Constructor for objects of class UniversityStudent
    */
   public UniversityStudent(String studentName, int courseNumber,Course[] list)
   {
      this.studentName=studentName;
      this.courseNumber=courseNumber;
      System.arraycopy(list, 0, this.list, 0, 10);// initialise instance variables
   }
   public void print(){
       System.out.println(studentName+” “+Integer.valueOf(courseNumber));
   for(int i=0; i
       {System.out.println(list[i]);}
   }
   public static void main(String[] args)
   {Course[] listA=new Course[10];
       listA[0]= new Course(“EIE3320”, 60);
       listA[1]= new Course(“EIE3105”, 40);
       UniversityStudent studentA = new UniversityStudent(“John”, 2, listA);
   studentA.print();
   Course[] listB=new Course[10];
       listB[0]= new Course(“COMP1001”, 84);
       listB[1]= new Course(“EIE3105”, 68);
       listB[2]= new Course(“EIE3320”, 52);
       UniversityStudent studentB = new UniversityStudent(“Mary”, 3, listB);
   studentB.print();
   }
}
//abc.HTML
JS TUT 6
var display123 = “Name:”;
function isBlank(s){
 var i
 for(i=0; i
 if(s.charAt(i)!=” “)
      return false
 }
 return true
}
function validate(fieldName,fieldValue)
{
 if(isBlank(fieldValue)){
  alert(fieldName + ” cannot be left blank.”)
  return false
 }
 return true
}
function AddValidateForm(){
 if(validate(“The name field”,document.testing.fullname.value)&&
   validate(“The telephone number field”,document.testing.telephone.value))
  {alert( “Name: ” + document.testing.fullname.value +” Telephone number: ” + document.testing.telephone.value + ” Add is being pressed”)
  return true}
 else
  return false
}
function SearchValidateForm(){
 if(validate(“The name field”,document.testing.fullname.value)&&
   validate(“The telephone number field”,document.testing.telephone.value))
  {alert( “Name: ” + document.testing.fullname.value +” Telephone number: ” + document.testing.telephone.value + ” Search is being pressed”)
  return true}
 else
  return false
}
Name:
Telephone number:
//tut 1
import java.io.IOException;
import java.util.Scanner;
/**
 * Write a description of class Q1 here.
 * @author (your name)
 * @version (a version number or a date)
 */
public class Q1
{
   // instance variables – replace the example below with your own
   private int x;
   private int row;
private int counter;
   /**
    * Constructor for objects of class Q1
    */
   public Q1()
   {
       // initialise instance variables
       x = 0;
   }
   /**
    * An example of a method – replace this comment with your own
    * @param y a sample parameter for a method
    * @return   the sum of x and y
    */
   public static void printBlanks(int counter)
   {
       int i;// put your code here
       for(i=0; i
       System.out.print(“  “);
   }
   public static void printTriangleOne(int counter)
   {
       int i;// put your code here
       for(i=counter; i>0; i–)
       {if (i
        else System.out.print(i+” “);
       }
       for(i=1; i
 {if (i+1
   else System.out.print((i+1)+” “);
   }
   }
   public static void main(String[] args) throws IOException
   {  int i;
       int counter=16;
       int k;
       int input;
       System.out.print(“Enter the number of lines”);
       Scanner scanner = new Scanner(System.in);
       counter=Integer.parseInt(scanner.nextLine());
       System.out.println(“Hello: Cheung Geoffrey Kai Laam”);
       if (counter
       {for(i=1; i
       {
       printBlanks(counter+1-i);
       printTriangleOne(i);
          //for(k=0; k
       //{System.out.print(i);}
       System.out.println();
   }
} else{System.out.println(“Your input is too large”);}
}
}