Simple Java Servlet Example

I am currently attending at Java EE course and I made a simple example how to send information to another page. This was part of course homework. This program takes user book information from index.jsp and sends it to another jsp-page.

First we have to create Book Bean:

package com.iinurmi.wordpress.beans;

public class Book {
	
	private String name;
	private String isbn;
	
	public Book(String name, String isbn) {
		this.name = name;
		this.isbn = isbn;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getIsbn() {
		return isbn;
	}
	public void setIsbn(String isbn) {
		this.isbn = isbn;
	}
	
	@Override
	public String toString() {
		return "Book [name=" + name + ", isbn=" + isbn + "]";
	}
}

Just a simple bean which has the default constructors and methods.

Next step is to create the jsp page and the servlet which will direct the information for another page.

Index jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Books</title>
	</head>
	<body>
		<p>Tervetuloa Iiro Nurmen täydelliseen kirjajärjestelmään!</p>
		<form action="sendbook" method="post">
			<table>
				<tr><td>Kirjan Nimi</td><td><input type="text" name="bookname"/></td</tr>
				<tr><td>ISBN</td><td><input type="text" name="isbn"/></td></tr>
				<tr><td>&nbsp;</td><td><button type="submit">Lähetä!</button></td></tr>
			</table>
		</form>
	</body>
</html>

The form action tells where the request will be sent. This is where you put your servlet name. I’m using post as a method. Next we have to create the servlet, which takes the info and sends it to next page.

package com.iinurmi.wordpress.servlets;

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;
import com.iinurmi.wordpress.beans.*;

/**
 * Servlet implementation class showBook
 */
@WebServlet("/sendbook")
public class SendBook extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SendBook() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
			
			String bookn = request.getParameter("bookname");
			String is = request.getParameter("isbn");
			
			Book book = new Book(bookn,is);
			
			request.setAttribute("book1", book);
			request.getRequestDispatcher("books.jsp").forward(request, response);
			
	}

}

That is a basic servlet that takes request and response and forwards it to jsp-called books.jsp. First this servlet finds parameter ”bookname” and ”isbn” from request. These are values from index.jsp. These values are storet to local variables. From local variables we create a book object. Book object is the bean which we created in the beginning. The book object is then saved as a request attribute ”book1”. Then we forvard request and response to the page where the information will be shown.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Books</title>
</head>
<body>
	<table>
		<tr><th>Kirjan nimi: </th><td><c:out value="${book1.name}"/></td></tr>
		<tr><th>Kirjan ISBN: </th><td><c:out value="${book1.isbn}"/></td></tr>
	</table>
	<a href="index.jsp">Takaisin kirjan syöttövaiheeseen</a>
</body>
</html>

Here we simply print out book objects information. This is done by jstl (Java Standard Tag Library). With jstl, it is much more easier and faster to print to jsp pages.

Project Italian Pizza Restaurant

Last semester me and my team made a pizzeria web service for fictional pizzeria Lorenzo. We used agile development method, scrum, coded with java and used tomcat for server. In the website you can order pizza and drinks online. The information goes do database and the delivery is made.

Pizzeria Lorenzo frontpage
Pizzeria Lorenzo frontpage

When user arrives to the ordering page, the information will be downloaded from the pizzerias database and compiled to the menu. The drinks are listed in other tab, thanks for jquery UI.
In the ordering page you can choose which pizza you want how many etc. The order will be kept in the cart for the session. If the user accidentally presses the back button or another page, the order will be in the cart.

"Ordering" -page
”Ordering” -page

After rthe order is ready the user will have to fill in information of himself and the payment.

User information filling
Users can’t fill in the wrong information, or the order will not get trough.

Finally the the ”receipt” is printed to the user and sent to database.

Order Information -page
Order Information -page

Java appletit

Jdk-kit asennus

Java kitin asennus tapahtuu linuxin terminaalista seuraavasti:
Ennen pakettien lataamista, päivitä pakettilista komennolla:
$ sudo apt-get update

Asenna javakit:

$ sudo apt-get install openjdk-7-jdk

Koska minulla oli jo javakit asennettuna asensin Eclipsen (joka asentaa jdk-kitin toimiakseen), jolla on
mukavaa väsäillä javan parissa:

$sudo apt-get install eclipse

Eclipse on helpompi valinta, jos haluaa tehdä javalla appletteja, sillä
toisin kuin esimerkiksi netbeansissa, voit ajaa appletit suoraan run as
java applet.

Hei maailma appletilla:

Eclipsellä on helppo kokeilla appletteja. Ensin luodaan uusi javaprojekti, johon tehdään uusi java luokka (new java project -> new Class).
Seuraava koodi eclipseen:


import java.applet.Applet;
import java.awt.Graphics;

public class Apletti extends Applet {
public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25); // draws "String" to x - y coordinates
}
}

Sitten vain yläpalkista run as applet (shift+alt+X A)

Appletti aukeaa ruudun yläkulmaan:

applet

Päädyin lopulta tekemään henkilötunnuksen tarkistajan. Appletti kysyy käyttäjän henkilötunnusta ja tarkistaa onko se normaalimuodossa. Tarkistus tapahtuu regular expressionin avulla. Jos käyttäjä on syöttänyt henkilötunnuksen oikein, ohjelma toteaa sen olevan kelvollinen tunnus:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class HenkiloTunnus extends Applet implements ActionListener {
Button nappi;
TextField laatikko;
Label teksti1, teksti2;

public void init() {
setSize(400,250);
teksti1 = new Label("Kirjoita henkilötunnuksesi: ");
teksti2 = new Label("Tarkastuksen tulos:");
add(teksti1);
add(laatikko = new TextField(24));
add(nappi = new Button("Tarkista"));
add(teksti2);
nappi.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
String hetu = laatikko.getText();

if (hetu.matches("\\d{6}[A+-]\\d{3}[A-Z0-9]") == true) {
teksti2.setText("Annoit kelpaavan henkilötunnuksen");
}else{
teksti2.setText("Annoit kelpaamattoman henkliötunnuksen");
}
}

}

Hyviä java linkkejä:

http://docs.oracle.com/
Kasapäin documentaatiota ja manuaalia!
Oraclen nettisivuilta ladattavissa myös viralliset javaversiot.

http://javatester.org/version.html
Testaa onko selaimessasi java käytössä. Kertoo myös javan version.