Chapter 12. JSP, MVC

ITSS Java Programming  NGUYEN Hong Quang, HUT

Content

 Principle of JSP  Elements of JSP  JavaBeans  MVC architecture

Principle of JSP

Outline of JSP

 JSP Page : embedded Java code into HTML

page

Principle of JSP

Mecanism of calling JSP page

JSP Compiler

Server

Temporary  Servlet

JSP Page Web Browser

Principle of JSP

JSP Servlet (Temporary Servlet)

public final class HelloWorld_jsp extends

org.apache.jasper.runtime.HttpJspBase implements  org.apache.jasper.runtime.JspSourceDependent {

public void _jspInit() { … }

public void _jspDestroy() { … }

public void _jspService (HttpServletRequest request,  HttpServletResponse response) throws java.io.IOException,  ServletException { … }

}

Principle of JSP

Life cycle of JSP Servlet

Principle of JSP

Sample application (1)

Principle of JSP

Sample application (2)

Principle of JSP

Start of JSP (Calling a JSP page)

 Direct start from Web browser:

 input directly URL of JSP page into Web browser  http://servername:8080/JSP/HelloWorld.jsp

 Start by “Action” attribute of Form tag

 Start when you push the summitting button on

form

 Start from JSP (or Servlet) :

 Start by being specified with other JSP files 

Elements of JSP

 JSP basic tag  Directive tag  Defined object  Action tag

Elements of JSP

JSP basic tags (1)

 Comment :

 Syntax : 

 Scriptlet :

 Embedded Java code into JSP page  Syntax :

<%    // Java code %>    // Java code

Elements of JSP

JSP basic tags : Declaration

 Syntax : <%! … %>  Declaration variable example  <%! int count = 12; %> <%! String description = “Increase count variable”; %>  Declaration method example <%!

public int maxNumber (int x, int y) {

if (x>y) return x; else return y;

} %>

Elements of JSP

Basic Tag Example (1)

JSP Basic Tags

int n = 12;  <%!  int m = 20;

%> <%! public int maxNumber (int x, int y) {

if (x>y) return x;  else return y;

} %>

Elements of JSP

Basic Tag Example (2)

 JSP Basic Tags 


n = <%= n %> 
m = <%= m %> 
m + n = <%= m+n %> 
Max m, n : <%= maxNumber(m,n) %>

Elements of JSP

Basic Tag Example Result

Elements of JSP

Directive tag : <%@ include file %>

 Syntax : <%@ include file = “URL or FilePath” %>  Insert a JSP page or HTML page into JSP page

Test "include file" Tags 

Test "include file" Tags  

<%@ include file = "HelloWorld.jsp" %>
<%@ include file = "basicTags1.jsp" %> 

Elements of JSP

Directive tag: <%@page %> (1)

 Syntax : <%@page Attribute = “Value” %>  Default attributes :  language : the script language used in the scriptlet is

 import : Specify the list of the library of the class to import.

specified. Example: language=“Java”

 session : Specify whether to use the session object.

Example: import=“java.util.*”

 contentType : Specify the encoding form of the JSP page  and the MIME type when making a response. Example:  contentType=“text/html ; charset=utf8”

Example: session=“true”

Elements of JSP

Directive tag: <%@ page %> (2)

 Default attributes :  errorPage: Specify the URL to forward when the exception is

 isErrorPage: Specify whether it is JSP error page.

generated. Example: <%@page errorPage=“error.html” %>

Elements of JSP

Defined object (1)

 ”request” object :

 Request information from client  Corresponding with javax.servlet.HttpServletRequest in

 ”response” object :

 output information to client  Corresponding with javax.servlet.HttpServletResponse in

Servlet programs

 Replace by “out” object

Servlet programs

Elements of JSP

Defined object (2)

 ”out” object

 output information from client  Subclass of javax.servlet.jsp.JSPWriters

 “session” object   Manager session

Elements of JSP

JSP default object example  (1)

 Display a form so the client could input name  Take the name and display welcome phrase.

Elements of JSP

JSP default object example  (2)

JSP Default Object : Getting Parameters 

 JSP Post data Demo 

 

<%

String username = request.getParameter("yourname"); if (username == null) {

// Open JSP page the first time // Display form to get information from client

%>

Your name :   

<%

}

Elements of JSP

JSP default object example  (3)

// Receive client information

else {

out.println("Username : " + username + "
"); out.println("IP Address : " + request.getRemoteHost()); out.println("
 Welcome to JSP page ");

}

%>

Elements of JSP

JSP default object example  (4)

Elements of JSP

JSP Hands­on exercises

 Write a program to display an online

shopping cart Web page with a drop down list  of items.

 The Web page should have one button to

add an item to the cart, and another button to  remove an item from the cart.

 The Web page should display the changes

made to the cart.

Elements of JSP

JSP Hands­on exercises (2)

Elements of JSP

Solution

The file used in this exercise is cart.jsp

<% java.util.Vector v = (java.util.Vector)session.getAttribute("array"); if (v == null) {

v = new java.util.Vector();

}     String i = null;     String submit = request.getParameter("submit");      }

Elements of JSP

Solution (2)

if (submit == null)  {

submit = "";

}

if (submit.equals("add") || submit.equals(""))

{

v.addElement(request.getParameter("item")); %>
 Your cart Contains :

    <%

    String[] items = new String[v.size()]; v.copyInto(items); for (int ix=1; ix < items.length; ix++) {

    %>

  1.  <% out.print(items[ix]);  }

    %>

<%    }

Elements of JSP

Solution (3)

if (submit.equals("remove"))  {

String removeitem=request.getParameter("item");

if(v.contains(removeitem)) {

v.removeElement(removeitem);

} else {

out.println("element not found in vector");

}

%>

Elements of JSP

Solution (4)


 Your cart Contains :

    <%

    String[] items = new String[v.size()]; v.copyInto(items); for (int i=1; i

    %>

  1.  <% out.print(items[i]);  }

    %>

<%

}

session.setAttribute("array",v); %>

Elements of JSP

Solution (5)


 
Please Select the item to add or remove:

Add / Remove Item:


 

Action tags

Action tags

 JavaBean Definition   Using JavaBean in JSP page  Forwarding tag

Action tags

What is JavaBean?

 JavaBeans is a specification for creating

reusable software component

 In general, the class is created in accordance  with the JavaBeans specification is called a  Bean.

Action tags

Attributes of JavaBean

 With each attribute (named ABC) in a

JavaBean :  private Object ABC;

 Setter method :

 to set a new value to the attribute  Syntax : public Object setABC (Object value);

 Getter method :

 to get the value of the attribute  Syntax : public Object getABC ();

Action tags

Specification of JavaBean

 Specify as the “public” specification  Define the constructor that doesn’t have the

argument of the “public” specification

 Packaging  Implement the “java.io.Serializable”

Action tags

JavaBean example

package bean; import java.io.Serializable;

public class SimpleBean implements Serializable { private String message = “Default message"; public String getMessage() {

return message;

} public void setMessage(String message) {

this.message = message;

}

}

Action tags

Using JavaBean in JSP page (1)

 tag

 Syntax : 

 Example :

name=“object name”  property=“property name”  value=“set value” />

Action tags

Using JavaBean in JSP page (3)

 tag

 Syntax : 

name=“object name”  property=“property name”

 Example :

/>

property="message" />

Action tags

JSP page example using SimpleBean (1)

<%@page import="bean.*" %>

JSP page : Test Bean  

 Call Bean in JSP webpage 

Action tags

JSP page example using SimpleBean (2)

/>

 Message : "  

Action tags

Result

MVC Architecture : Outline

Model

 MVC : Model – View – Controller

 Model : Define the data structure in the application and

View Controller

 View : The application data is displayed, and it becomes

the business rule of data.

 Controller : Execute the processing of the application.  Start the business logic of the model, and return the  result as a view.

an interface with the user.

Servlet/JSP/JavaBeans and MVC

Client Server

Controller

1. Transmit  input data Servlet

2. Business  logic execution

3. Making a  result view

View Model

JavaBean JSP Page

4. Display  view

Sample application,

MvcServlet

valid.jsp

Customer

invalid.jsp

http://localhost:8080/JSP/mvc.htm

mvc.htm

Name        

Password



MvcServlet.java (1)

public class MvcServlet extends HttpServlet {

public void doPost(HttpServletRequest req,  HttpServletResponse res)  throws ServletException,  IOException {

String name = req.getParameter( "name"); String password = req.getParameter("password"); System.out.println(name + " " + password); Customer cust = new Customer(); cust.setName(name); cust.setPassword(password); req.setAttribute("customer", cust);

MvcServlet.java (2)

String page = null; if (cust.isValid()) {

page = "/valid.jsp";

} else {

page = "/invalid.jsp";

} try {

getServletContext().getRequestDispatcher(page).forward(re q, res);

} catch (Exception ex) { ex.printStackTrace();

}

Customer.java (1)

package bean; import java.io.Serializable; public class Customer implements Serializable {

private String name; private String password; private String validName = "HUT Student“; private String validPassword = "hut“; public Customer() {} public void setName(String name) {

this.name = name;

}

Customer.java (2)

public String getName() { return name; } public void setPassword(String password) {

this.password = password;

} public String getPassword() {

return password;

} public boolean isValid() {

if (!name.equals("") && name.equals(validName) &&

password.equals(validPassword)) { return true;

} else {return false; }

}

valid.jsp

<%@page contentType="text/html; charset=utf­8" %>

scope="request" />

ValidJSP

Welcome 
 Mr./Ms. : 

invalid.jsp

<%@page contentType="text/html; charset=utf­8" %> InValidJSP

The user name or the password is illegal.

Hand­ons exercices

 JSP : input personal information and then

display to the client

 JavaBean :

 SimpleCalculator.java  add/substract/multiply/divide two numbers

Hand­ons exercices

 MVC :

 valid.jsp (View)  invalid.jsp (View)  SimpleCalculator.java (Model)  calculator.htm (View)  ControllerServlet :

 if two input number aren’t on good format, forward to

 If not : call SimpleCalculator and display the result by

invalid.jsp

valid.jsp

MVC hand­ons exercices