Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Saturday, May 18, 2013

Struts 2 - Sample MVC

See project structure.

























Core files -
1 web.xml
2 action classes: Login.java and SearchTicket.java
2 struts xml: login.xml and struts.xml
3 JSP pages: index.jsp, searchTicket.jsp and showTicket.jsp

web.xml

 
 Struts2Demo
 
  index.jsp
 

 
  struts2
  org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
 

 
  struts2
  /*
 



StrutsPrepareAndExecuteFilter deals with all requests and it is responsible for selecting which action to be executed.

index.jsp
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Please login...</title>
</head>
<body>
    <s:form action="login">
        <s:textfield label="User ID" key="userId"></s:textfield>
        <s:password label="Password" key="password"></s:password>
        <s:submit></s:submit>
    </s:form>
</body>
</html>

Once the login form is submitted, OGNL calls setter method of the action to store the values.

Login.java
package com.mqin.struts2.demo.login;

import com.opensymphony.xwork2.Action;

public class Login implements Action {
    private String userId;
    private String password;

    public String execute() throws Exception {
        if (getUserId().equals("James") && getPassword().equals("Bond")) {
            return SUCCESS;
        }
        return ERROR;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}


The business logic is done in execute and return SUCCESS or ERROR to the framework, and since Action class has both business logic and data, it acts like both controller and model.

login.xml


 
 
  
   /searchTicket.jsp
   /index.jsp
  
 



Set struts.devMode to true to get more log information, and it defines the business flow by the result of action, here success and error.

If error, stay at index and if success, go to searchTicket page.

searchTicket.jsp
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Ticket Search</title>
</head>
<body>

    <s:form action="searchTicket">
        <s:textfield label="From" key="fromCity"></s:textfield>
        <s:textfield label="To" key="toCity"></s:textfield>
        <s:submit></s:submit>
    </s:form>

</body>
</html>

Submit the form to action SearchTicket.
package com.mqin.struts2.demo.search;

import com.opensymphony.xwork2.Action;

public class SearchTicket implements Action {
    private String fromCity;
    private String toCity;
    private int ticketNo;

    public String execute() throws Exception {
        if (getFromCity().equals("Adelaide") && getToCity().equals("Melbourne")) {
            setTicketNo(10);            
        }
        return SUCCESS;
    }

    public String getFromCity() {
        return fromCity;
    }

    public void setFromCity(String fromCity) {
        this.fromCity = fromCity;
    }

    public String getToCity() {
        return toCity;
    }

    public void setToCity(String toCity) {
        this.toCity = toCity;
    }

    public int getTicketNo() {
        return ticketNo;
    }

    public void setTicketNo(int ticketNo) {
        this.ticketNo = ticketNo;
    }

}


struts.xml


 

 
  
   /showTicket.jsp
  
 



showTicket.jsp
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Ticket Search Result</title>
</head>
<body>

    <s:property value="ticketNo" />
    tickets found from
    <s:property value="fromCity" />
    to
    <s:property value="toCity" />
    .

</body>
</html>

Please notice that you don't have to specify object.attribute to get the value, that is because object and attribute is decoupled and stored in Value Stack and can be received by OGNL directly.

Execution flow.










Sunday, May 5, 2013

Sample Java MVC Web Application - Part III

In this part, we add JDBC and MySQL to our sample project. Hence, we divide the src package to four parts: entity, jdbc, servlet and test.

Take a look at the project structure -




























Execution Results -














Create data in MySQL -
create database testdb;

use testdb;

create table person (
id int not null auto_increment primary key,
firstname varchar(20),
lastname varchar(20)
);

insert into person (firstname, lastname) values ("James","Bond");
insert into person (firstname, lastname) values ("James","White");

DBConnection.java -
package com.mqin.example.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {

    public static Connection getConnection() {
        Connection conn = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/testdb?" + "user=root&password=root");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return conn;
    }
}


PersonOperation.java - 
package com.mqin.example.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.mqin.example.entity.PersonModel;

public class PersonOperation {

    private Connection conn = null;

    public PersonOperation() {
        conn = DBConnection.getConnection();
    }

    public void insertPerson(PersonModel p) {
        String sql = "insert into person (firstname, lastname) valus (?,?)";

        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, p.getFirstName());
            ps.setString(2, p.getLastName());
            ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public PersonModel getPerson(int id) {
        PersonModel p = null;
        String sql = "select * from person where id = ?";

        try {
            PreparedStatement ps = conn.prepareCall(sql);
            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                p = new PersonModel();
                p.setId(rs.getInt("id"));
                p.setFirstName(rs.getString("firstname"));
                p.setLastName(rs.getString("lastname"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return p;
    }

    public ArrayList<PersonModel> getPerson(String firstname) {
        ArrayList<PersonModel> parray = new ArrayList<PersonModel>();
        String sql = "select * from person where firstname = ?";

        try {
            PreparedStatement ps = conn.prepareCall(sql);
            ps.setString(1, firstname);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                PersonModel p = new PersonModel();
                p.setId(rs.getInt("id"));
                p.setFirstName(rs.getString("firstname"));
                p.setLastName(rs.getString("lastname"));
                parray.add(p);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return parray;
    }

}

PersonTest.java -
package com.mqin.example.test;

import java.util.ArrayList;
import java.util.Iterator;

import com.mqin.example.entity.PersonModel;
import com.mqin.example.jdbc.PersonOperation;

public class PersonTest {

    private PersonOperation pop = null;

    public PersonTest() {
        pop = new PersonOperation();
    }

    public boolean testGetById(int id) {
        PersonModel p = pop.getPerson(id);

        if (p == null) {
            return false;
        }

        log(p.getFirstName() + " " + p.getLastName());
        return true;
    }

    public boolean testGetByFirstName(String firstname) {
        ArrayList<PersonModel> parray = new ArrayList<PersonModel>();
        PersonModel p = null;

        parray = pop.getPerson(firstname);

        if (parray.isEmpty()) {
            return false;
        }

        Iterator<PersonModel> iterator = parray.iterator();

        while (iterator.hasNext()) {
            p = iterator.next();
            log(p.getFirstName() + " " + p.getLastName());
        }

        return true;
    }

    private void log(String string) {
        System.out.println(string);
    }

    public static void main(String[] args) {
        PersonTest pt = new PersonTest();

        int id = 2;
        String firstname = "James";

        if (!pt.testGetById(id)) {
            pt.log("Cannot find person with id = " + id);
        }

        if (!pt.testGetByFirstName(firstname)) {
            pt.log("Cannot find person with firstname = " + firstname);
        }
    }

}


SearchByID.java -
package com.mqin.example.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mqin.example.entity.PersonModel;
import com.mqin.example.jdbc.PersonOperation;

public class SearchByID extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public SearchByID() {
        super();
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {

        if (request.getParameter("id") == null || request.getParameter("id") == "") {
            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

        int id = (new Integer(request.getParameter("id"))).intValue();
        PersonOperation pop = new PersonOperation();
        PersonModel person = pop.getPerson(id);

        request.setAttribute("person", person);

        getServletContext().getRequestDispatcher("/searchidoutput.jsp").forward(request, response);
    }

}


SearchByFirstName.java -
package com.mqin.example.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mqin.example.entity.PersonModel;
import com.mqin.example.jdbc.PersonOperation;

public class SearchByFirstName extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public SearchByFirstName() {
        super();
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {

        if (request.getParameter("firstname") == null || request.getParameter("firstname") == "") {
            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

        String firstName = request.getParameter("firstname");
        PersonOperation pop = new PersonOperation();
        ArrayList<PersonModel> parray = new ArrayList<PersonModel>();
        parray = pop.getPerson(firstName);

        request.setAttribute("parray", parray);

        getServletContext().getRequestDispatcher("/searchnameoutput.jsp").forward(request, response);
    }

}


index.jsp -
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
    <form action="" method="post">
        <table border="0">
            <tr>
                <td>ID:</td>
                <td><input type="text" name="id" /></td>
            </tr>
            <tr>
                <td>First Name:</td>
                <td><input type="text" name="firstname" /></td>
            </tr>
            <tr>
                <td>Last Name:</td>
                <td><input type="text" name="lastname" /></td>
            </tr>
            <tr>
                <td><input type="submit" value="SearchByID"
                    onclick="form.action='searchbyid';" /></td>
                <td><input type="submit" value="SearchByFirstName"
                    onclick="form.action='searchbyfirstname';" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

searchidoutput.jsp -
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<jsp:useBean id="person" scope="request" class="com.mqin.example.entity.PersonModel" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
    <table>
        <tr>
            <td>First Name:</td>
            <td><jsp:getProperty name="person" property="firstName" /></td>
        </tr>
        <tr>
            <td>Last Name:</td>
            <td><jsp:getProperty name="person" property="lastName" /></td>
        </tr>
    </table>
</body>
</html>

searchnameoutput.jsp -
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.ArrayList"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="com.mqin.example.entity.PersonModel"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
    <table>
        <%
            ArrayList<PersonModel> parray = (ArrayList<PersonModel>) request.getAttribute("parray");
            PersonModel p = null;
            Iterator<PersonModel> iterator = parray.iterator();
            while (iterator.hasNext()) {
                p = iterator.next();
        %>
        <tr>
            <td>Person ID:</td>
            <td><%=p.getId()%></td>
        </tr>
        <tr>
            <td>First Name:</td>
            <td><%=p.getFirstName()%></td>
        </tr>
        <tr>
            <td>Last Name:</td>
            <td><%=p.getLastName()%><%}%></td>
        </tr>
    </table>
</body>
</html>




Saturday, May 4, 2013

Sample Java MVC Web Application - Part II

In sample-java-mvc-web-application-part-i, we have created a web application with jsp (view) and servlet (controller), now we are going to add java bean (model) to encapsulate person's properties like first name and last name.

Now the project looks like -





















PersonModel.java -
package com.mqin.example;

public class PersonModel {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

Update service code in ServletController -
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        
        String firstName = request.getParameter("firstname");
        String lastName = request.getParameter("lastname");

        if (firstName == null 
                || lastName == null
                || firstName == "" 
                || lastName == "") {
            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);    
            return;
        }
        
        PersonModel person = new PersonModel();
        person.setFirstName(firstName);
        person.setLastName(lastName);

        request.setAttribute("person", person);

        getServletContext().getRequestDispatcher("/output.jsp").forward(request, response);
    }

Also update output page with <jsp:useBean> and <jsp:getProperty> tag -
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<jsp:useBean id="person" scope="request" class="com.mqin.example.PersonModel" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
    <h1>Your first and last name is:</h1>

    <table>
        <tr>
            <td>First Name:</td>
            <td><jsp:getProperty name="person" property="firstName" /></td>
        </tr>
        <tr>
            <td>Last Name:</td>
            <td><jsp:getProperty name="person" property="lastName" /></td>
        </tr>
    </table>
</body>
</html>

Now we have finished the simplest Java MVC web application.


Friday, May 3, 2013

Sample Java MVC Web Application - Part I

Let us create a dynamic java web application in eclipse with 2 jsp files and 1 servlet. See project structure as -



No model at this stage and let us see the code -

index.jsp -
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
    <form action="servletcontroller" method="post">
        <table border="0">
            <tr>
                <td>First Name:</td>
                <td><input type="text" name="firstname" /></td>
            </tr>
            <tr>
                <td>Last Name:</td>
                <td><input type="text" name="lastname" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Submit" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

output.jsp -
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
    <h1>Your first and last name is:</h1>

    <%
        String firstName = (String) request.getAttribute("firstname");
        String lastName = (String) request.getAttribute("lastname");
    %>

    <table>
        <tr>
            <td>First Name:</td>
            <td><%=firstName%></td>
        </tr>
        <tr>
            <td>Last Name:</td>
            <td><%=lastName%></td>
        </tr>
    </table>
</body>
</html>

ServletController.java -
package com.mqin.example;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ServletController() {
        super();
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {

        if (request.getParameter("firstname") == null 
                || request.getParameter("lastname") == null
                || request.getParameter("firstname") == "" 
                || request.getParameter("lastname") == "") {
            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

        String firstName = request.getParameter("firstname");
        String lastName = request.getParameter("lastname");

        request.setAttribute("firstname", firstName);
        request.setAttribute("lastname", lastName);

        getServletContext().getRequestDispatcher("/output.jsp").forward(request, response);
    }

}


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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>JavaMVC</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>ServletController</display-name>
    <servlet-name>ServletController</servlet-name>
    <servlet-class>com.mqin.example.ServletController</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ServletController</servlet-name>
    <url-pattern>/servletcontroller</url-pattern>
  </servlet-mapping>
</web-app>


Step 1, run index.jsp -











Step 2, click submit with empty value -











Step 3, input value -











Step 4, click submit - 











*Note* Good explanation about forward and redirect -
forward vs redirect
getServletContext().getRequestDispatcher("/output.jsp").forward(request, response);
response.sendRedirect(request.getContextPath() + "/output.jsp");