Posts Tagged ‘Apache Tomcat’

English: Logo of Русский: Логотип Apache Tomcat

Setting the JAVA_HOME , CATALINA_HOME Environment Variable on Windows

One can do using command prompt
1. set JAVA_HOME=C:\”top level directory of your java install”
2. set CATALINA_HOME=C:\”top level directory of your Tomcat install”
3. set PATH=%PATH%;%JAVA_HOME%\bin;%CATALINA_HOME%\bin

Or you can do the same

  1. Go to system properties.
  2. Go to environment variables and add a new variable with the name  JAVA_HOME and provide variable value as C:\”top level directory of your java install”.
  3. Go to environment variables and add a new variable with the name  CATALINA_HOME and provide variable value as C:\”top level directory of your Tomcat install”.
  4. In path variable add a new variable value as ;%CATALINA_HOME%\bin;

and write startup.bat on command Prompt and press enter tomcat will start up and for shutdown u just write shutdown.bat        once you start the tomcat you can access it like that http://localhost:8080     and access Application Manager using login and password …. if you dont know username and password you can  follow below instructions ….

User and password for Tomcat

By default, Tomcat does not enable admin or manager access. To enable it, you have to edit the “%TOMCAT_FOLDER%/conf/tomcat-users.xml” manually.

File : tomcat-users.xml (before update) , initially, Tomcat comments all users and roles like above.



<!--
  
  <role rolename="role1"/>
  
  
  
-->

File : tomcat-users.xml (after updated)

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
-->
  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="admin" password="admin" roles="admin,manager"/>
</tomcat-users>

To enable admin access, just update the content like above. Saved it and restart Tomcat, now you can access Tomcat admin or manger pages with user = “admin” and password = “admin“.

Introduction
This document is one of a series of tutorials to demonstrate the use of the Web Services tools in the Web Tools Platform Project using the WTP 1.5 drivers.
This tutorial shows how to create a simple Web service and Web service client from a Java class. The Java class in this scenario converts between the Celsius and Farenheit temperature scales.
Set Up
Before creating the Web service, there are two prerequisites:
  1. Install Apache Tomcat
  2. Create a dynamic Web project called ConverterProj .
Creating a bottom up Java bean Web service and Web service client
  1. Import the wtp/Converter.java class into ConverterProj/src (be sure to preserve the package).
  2. Select the Converter.java file.
  3. Open File -> New -> Other… -> Web Services -> Web Service.
  4. Click Next.
  5. Move the Service slider to the Start Service position .
  6. Move the Client slider to the Test Client position .
  7. Select Monitor the Web service .
  8. If you want to choose a server different from the one defaulted by the wizard, click the Server project link to select a server .
  9. Result:

  1. Click Finish .
  2. It will take about one minute for the wizard to assemble the Web service and Web service client Web projects,
  3. start Apache Tomcat, and deploy the projects to Tomcat. Once finished, the generated Sample JSP Web
  4. application will appear in the browser view, maximized here for clarity:

  1. Under Methods , click on celsiusToFarenheit(float) .
  2. Under Inputs , enter 37 into the celsius entry field.
  3. Click on Invoke. In the Result view, you should get a response of 98.6.

  1. Since you selected the “Monitor Web service” checkbox, a TCP/IP port is automatically created on the
  2. Tomcat server. When you invoke the Web service, the TCP/IP Monitor view comes up automatically
  3. showing the SOAP message request and response. Double-click on the TCP/IP Monitor view and
  4. select XML view in the drop-down combo for both request and response. Result:

Explanation
The Web Service wizard is orchestrating the end-to-end generation, assembly, deployment, installation and execution of the Web service, Web service client, and sample JSPs. In this scenario, we clicked Finish on page one. In effect, this is allowing the wizard to pick reasonable defaults according to the basic high-level choices made on the first page. If you repeat this scenario, but use the Next button to work through the wizard, you will learn more about the kinds of choices that are available and the kinds of defaults being assumed.
After completing this scenario, the WSDL for the Converter Web service can be found in ConverterProj/WebContent/wsdl/Converter.wsdl.
Now that your Web service is running, there are a few interesting things you can do with this WSDL file. Examples:
  1. You can double-click on the WSDL to open the WSDL graphical editor.
  2. You can right-click on the WSDL and choose Web Services -> Test with Web Services Explorer to test the service.
  3. You can right-click on the WSDL and choose Web Services -> Publish WSDL file to publish the service to a public UDDI registry.
  4. You can click on the WSDL and choose New -> Other… -> Web Services -> Web Service Client to generate a Web service client. Note, however, that we have already witnessed the internal and visual features of the Web Service Client wizard since, in addition to being its own wizard, it is quite literally embedded within the larger Web Service wizard.

 

 

Today we will create a Spring MVC based application that uses Freemarker FTL as view instead of JSP. This would give you a good insight in Spring MVC + Freemarker integration. The application is similar to previous tutorial’s User app, where a list of users will be displayed and also we can add new user.

The application is very simple:

  1. There is a table that displays user info like firstname, lastname.
  2. New user can be added via Add User form.

Below is the wireframe of our final freemarker based spring mvc 3 app.
freemarker-servlet-wireframe

So lets get started.

Things We Need

Before we starts with our Spring MVC 3 + FreeMarker example, we will need few tools.

  1. JDK 1.6 or above (download)
  2. Tomcat 6.x or above or any other container (Glassfish, JBoss, Websphere, Weblogic etc) (download)
  3. Eclipse 3.4.x or above (download)
  4. Spring MVC 3.1.2 or above (download)
  5. Freemarker JAR v2.3.15 or above(download)

Let us start with our Spring MVC based Freemarker application.

Step 1: Getting Started

Open Eclipse and goto File -> New -> Project and select Dynamic Web Project in the New Project wizard screen.

dynamic web project in eclipse

After selecting Dynamic Web Project, press Next.

eclipse dynamic web project

Write the name of the project. For example Freemarker_SpringMVC_example. Once this is done, select the target runtime environment (e.g. Apache Tomcat v6.0). This is to run the project inside Eclipse environment. After this press Finish.

Once the project is created, you can see its structure in Project Explorer. This is how the project structure would look like when we finish the tutorial and add all source code.

springmvc-freemarker-ftl-project-structure

Till this step, our basic Eclipse web project is ready. We will now add Spring MVC and Freemarker support to this project.

Step 2: Adding Spring MVC Support

First copy all required Spring MVC and supporting JAR files in WebContent > WEB-INF > lib folder. Create this folder if it does not exists. Don’t worry if you do not have these JARs. You can download the complete source code with JAR files at the end of this tutorial.

Next we change web.xml (deployment descriptor) and add Spring MVC support to it. If you do not know why we do this, I strongly recommends you to go through Spring 3 MVC Tutorial series.

Related: Spring 3 MVC hello world example

Update the web.xml with following code:

File: /WebContent/WEB-INF/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_3_0.xsd"
        id="WebApp_ID" version="3.0">
        
  <display-name>Freemarker_SpringMVC_example</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

The above code in web.xml will map DispatcherServlet with url pattern *.html. One thing to note here is the name of servlet in <servlet-name> tag in web.xml. Once the DispatcherServlet is initialized, it will look for a file name [servlet-name]-servlet.xml in WEB-INF folder of web application. In this example, the framework will look for file called spring-servlet.xml.

Create a new file spring-servlet.xml under /WebContent/WEB-INF/ folder. This is the spring configuration. Copy following code into it.
File: /WebContent/WEB-INF/spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    <!-- freemarker config -->
    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
      <property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
    </bean>
    
    <!--
      View resolvers can also be configured with ResourceBundles or XML files. If you need
      different view resolving based on Locale, you have to use the resource bundle resolver.
    -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
      <property name="cache" value="true"/>
      <property name="prefix" value=""/>
      <property name="suffix" value=".ftl"/>
    </bean>
    <context:component-scan
        base-package="net.viralpatel" />
         
</beans>

In the above xml configuration file, we have defined a tag <context:component-scan>. This will allow Spring to load all the components from package net.viralpatel and all its child packages. This will load our UserController class. Also we have defined a bean viewResolver. We uses org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver as view resolver. Also notice how we defined bean freemarkerConfig. This defines Freemarker configuration, in our case just one property templateLoaderPath; the path where we will store all our .ftl template files.

Thus the bean viewResolver will resolve the freemarker template view. Note that in our UserController class, we have return a view name “index”. This will be resolved to path /WEB-INF/ftl/index.ftl by FreeMarkerViewResolver.

Step 3: Create Spring MVC Controller

File: /src/net/viralpatel/UserController.java

package net.viralpatel;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class UserController {
    /**
     * Static list of users to simulate Database
     */
    private static List<User> userList = new ArrayList<User>();
    //Initialize the list with some data for index screen
    static {
        userList.add(new User("Bill", "Gates"));
        userList.add(new User("Steve", "Jobs"));
        userList.add(new User("Larry", "Page"));
        userList.add(new User("Sergey", "Brin"));
        userList.add(new User("Larry", "Ellison"));
    }
    /**
     * Saves the static list of users in model and renders it
     * via freemarker template.
     *
     * @param model
     * @return The index view (FTL)
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(@ModelAttribute("model") ModelMap model) {
        model.addAttribute("userList", userList);
        return "index";
    }
    /**
     * Add a new user into static user lists and display the
     * same into FTL via redirect
     *
     * @param user
     * @return Redirect to /index page to display user list
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@ModelAttribute("user") User user) {
        if (null != user && null != user.getFirstname()
                && null != user.getLastname() && !user.getFirstname().isEmpty()
                && !user.getLastname().isEmpty()) {
            synchronized (userList) {
                userList.add(user);
            }
        }
        return "redirect:index.html";
    }
}

The UserController is a simple Spring 3 MVC controller that handles request/response. We have created a private static List userList which stores the user entries. Note that in ideal example you would like to read data from database. But for sake of simplicity we will stick to static List :)

There are two methods index() and add(), both mapped via @RequestMapping annotation. The index() method will simply store the users list in model object and render “index” view (index.ftl). And the add() method gets the user details from html form and add it inside static List. Once the add() has added user, it simply redirects the request to /index.html which will render the user list.

Apart from the above UserController class, we will also need a bean class User which holds the user information like firstname, lastname etc.

File: /src/net/viralpatel/User.java

package net.viralpatel;
public class User {
    private String firstname;
    private String lastname;
    public User() {
    }
    public User(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }
    //Add Getter and Setter methods
}

Now add Freemarker view in your project.

Step 4: Create Freemarker Template Files

Create a new file index.ftl under folder /WebContent/WEB-INF/ftl/. Copy following content into it.

File: /WebContent/WEB-INF/ftl/index.ftl

<html>
<head><title>ViralPatel.net - FreeMarker Spring MVC Hello World</title>
<body>
<div id="header">
<H2>
    <a href="http://viralpatel.net"><img height="37" width="236" border="0px" src="http://viralpatel.net/blogs/wp-content/themes/vp/images/logo.png" align="left"/></a>
    FreeMarker Spring MVC Hello World
</H2>
</div>
<div id="content">
    
  <fieldset>
    <legend>Add User</legend>
  <form name="user" action="add.html" method="post">
    Firstname: <input type="text" name="firstname" /> <br/>
    Lastname: <input type="text" name="lastname" />   <br/>
    <input type="submit" value="   Save   " />
  </form>
  </fieldset>
  <br/>
  <table class="datatable">
    <tr>
        <th>Firstname</th>  <th>Lastname</th>
    </tr>
    <#list model["userList"] as user>
    <tr>
        <td>${user.firstname}</td> <td>${user.lastname}</td>
    </tr>
    </#list>
  </table>
</div
</body>
</html

This is a simple FTL template file. We just iterate model[“userList”] list in a loop and prints user’s firstname and lastname in table.

That’s All Folks

You may want to run the application see the result. I assume you have already configured Tomcat in eclipse. All you need to do:
Open Server view from Windows > Show View > Server. Right click in this view and select New > Server and add your server details.

To run the project, right click on Project name from Project Explorer and select Run as > Run on Server (Shortcut: Alt+Shift+X, R)

URL: http://localhost:8080/Freemarker_SpringMVC_example/index.html
freemarker-springmvc-ftl-example

Download Source Code

Freemarker_SpringMVC_example.zip (4.4 MB)

Reference : viralpatel.net

 

English: Logo of Apache Struts

Today we will create a Struts2 based application that uses Freemarker FTL as view instead of JSP. This would give you a good insight in Struts2 + Freemarker integration. The application is similar to previous tutorial’s User app, where a list of users will be displayed and we can add new user.

The application is very simple:

  1. There is a table that displays user info like firstname, lastname.
  2. New user can be added via Add User form.

Below is the wireframe of our final Freemarker based Struts2 app.
freemarker-servlet-wireframe

So lets get started.

Things We Need

Before we starts with our Struts2 + FreeMarker example, we will need few tools.

  1. JDK 1.6 or above (download)
  2. Tomcat 6.x or above or any other container (Glassfish, JBoss, Websphere, Weblogic etc) (download)
  3. Eclipse 3.4.x or above (download)
  4. Struts 2.3.4.1 or above (download)
  5. Freemarker JAR v2.3.15 or above(download)

Let us start with our Struts2 based Freemarker application.

Step 1: Getting Started

Open Eclipse and goto File -> New -> Project and select Dynamic Web Project in the New Project wizard screen.

dynamic web project in eclipse

After selecting Dynamic Web Project, press Next.

eclipse dynamic web project

Write the name of the project. For example Freemarker_Struts2_example. Once this is done, select the target runtime environment (e.g. Apache Tomcat v6.0). This is to run the project inside Eclipse environment. After this press Finish.

Once the project is created, you can see its structure in Project Explorer. This is how the project structure would look like when we finish the tutorial and add all source code.

struts2-ftl-eclipse-project-structure

Till this step, our basic Eclipse web project is ready. We will now add Struts2 and Freemarker support to this project.

Step 2: Adding Struts2 Support

First copy all required Struts2 JAR and supporting JAR files in WebContent > WEB-INF > lib folder. Create this folder if it does not exists. Don’t worry if you do not have these JARs. You can download the complete source code with JAR files at the end of this tutorial.

Next we change web.xml (deployment descriptor) and add Struts2 support to it. If you do not know why we do this, I strongly recommends you to go through Struts2 Tutorial series.

Related: Struts2 hello world example

Update the web.xml with following code:

File: /WebContent/WEB-INF/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/j2ee" xmlns:javaee="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/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_9" version="2.4">
  <display-name>Freemarker Struts2 example - viralpatel.net</display-name>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
          org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

The above code in web.xml will define a filter StrutsPrepareAndExecuteFilter and maps it with url pattern /*. Thus each request will go through the Struts2 framework and it will decide wheather an action is available which can be called or default action should be allowed. Also struts framework will try to load its configuration from struts.xml file. It expects this file to be present in classpath (WEB-INF/classes) of the application when the source is compiled. Thus we will create a source folder called Resources and put the struts.xml file in it.

To create a source folder, right click on your project in Project Explorer view of Eclipse and select New > Source Folder.

struts2-resource-folder

Specify folder name Resources and press Finish.

Create a new file struts.xml under Resources folder. Copy following code into it.

File: /Resources/struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

 <struts>
    <constant name="struts.enable.DynamicMethodInvocation"
        value="false" />
    <constant name="struts.devMode" value="false" />

    <package name="default" extends="struts-default" namespace="/">
        <action name="list" method="list"
           >
            <result type="freemarker" name="success">/WEB-INF/ftl/index.ftl</result>
        </action>
        <action name="add" method="add"
           >
            <result type="freemarker" name="success">/WEB-INF/ftl/index.ftl</result>
        </action>
    </package>
</struts>

Note that in above configuration file, we have defined User action of our application. We defined two actions using <action> tag. One to list the users and another to add new user. Note how we used attribute method="add" and method="list" to let Struts2 know which particular method needs to be called within the Action class. Also the result type mapped here is type="freemarker". Struts2 provides a first-class support to Freemarker template. All one has to do is to define result type freemarker. Struts automatically manage the view forwards in this case. On success of the action we forward the request to /WEB-INF/ftl/index.ftl freemarker view.

Step 3: Create Struts2 Action

Create new Struts2 action class UserAction under /src/net/viralpatel/struts2/ folder and copy following source code into it.

File: /src/net/viralpatel/struts2/UserAction.java

package net.viralpatel.struts2;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {

	private static final long serialVersionUID = -8366209797454396351L;

	private static List<User> userList = new ArrayList<User>();

	private User user;

	static {
		userList.add(new User("Bill", "Gates"));
		userList.add(new User("Steve", "Jobs"));
		userList.add(new User("Larry", "Page"));
		userList.add(new User("Sergey", "Brin"));
		userList.add(new User("Larry", "Ellison"));
	}

    /**
     * Action method to display user list. Uses <code>userList</code> array 
     * object defined as class level attribute to display list of users.
     * @return SUCCESS 
     */
    public String list() {
    	return SUCCESS;
    }

    /**
     * Action method to add new user. Read the user information
     * via <code>user</code> object defined as class level attribute.
     * @return SUCCESS if user is added successfully
     */
    public String add() {

    	System.out.println("User:"+user);

        userList.add(user);

    	return SUCCESS;
    }

    public List<User> getUserList() {
	return userList;
    }

    public void setUserList(List<User> userList) {
	UserAction.userList = userList;
    }

    public User getUser() {
	return user;
    }

    public void setUser(User user) {
	this.user = user;
    }
}

In above Struts2 action class, we defined two methods: add() and list() for our application. Also note that we have created a static ArrayList userList, which holds the user information. This is a dummy list just to mimic database values. In an ideal application, you may have to call Database and fetch list of users from a table. But for sake of simplicity we stores users in an arraylist.

Other than userList, we also defined User user object as class attribute. This object will store the user information when a new user is added. It act as a form bean object for action class.

Apart from the above UserController class, we will also need a bean class User which holds the user information like firstname, lastname etc.

File: /src/net/viralpatel/struts2/User.java

package net.viralpatel;

public class User {
	private String firstname;
	private String lastname;

	public User() {
	}

	public User(String firstname, String lastname) {
		this.firstname = firstname;
		this.lastname = lastname;

	}

	//Add Getter and Setter methods

}

Now add Freemarker view in your project.

Step 4: Create Freemarker Template File

Create a new file index.ftl under folder /WebContent/WEB-INF/ftl/. Copy following content into it.

File: /WebContent/WEB-INF/ftl/index.ftl

<html>
<head>
  <meta name="generator" content=
  "HTML Tidy for Linux/x86 (vers 11 February 2007), see www.w3.org" />

  <title>ViralPatel.net - FreeMarker Spring MVC Hello World</title>
</head>

<body>
  <div id="header">
    <h2><a href="http://viralpatel.net"><img height="37" width="236" border="0px" src=
    "http://viralpatel.net/blogs/wp-content/themes/vp/images/logo.png" align=
    "left" /></a> FreeMarker Struts2 Hello World</h2>
  </div>

  <div id="content">
    <fieldset>
      <legend>Add User</legend>

	<@s.form action="add" method="post">
	    <@s.textfield label="First name" name="user.firstname"/>
	    <@s.textfield label="Last name" name="user.lastname"/>
	    <@s.submit value="Save"/>
	</@s.form>    </fieldset><br />    <table>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
      </tr>
	<#list userList as user>
  	<tr>
  		<td>${user.firstname}</td> <td>${user.lastname}</td>
  	</tr>
    </#list>	  
    </table>
  </div>
</body>
</html>

This is a simple FTL template file. We just iterate model userList list in a loop and prints user’s firstname and lastname in table.

One last thing, the default index.jsp is opened when you tries to execute your application in eclipse. So just update it and add link to our User page. Modify the /WebContent/index.jsp file and add following code into it.

File: /WebContent/index.jsp

<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <a href="list">Freemarker Struts2 example</a>
</body>
</html>

That’s All Folks

You may want to run the application see the result. I assume you have already configured Tomcat in eclipse. All you need to do:
Open Server view from Windows > Show View > Server. Right click in this view and select New > Server and add your server details.

To run the project, right click on Project name from Project Explorer and select Run as > Run on Server (Shortcut: Alt+Shift+X, R)

URL: http://localhost:8080/Freemarker_Struts2_example/list
struts2-freemarker-ftl-example

Download Source Code

Freemarker_Struts2_example.zip (3.3 MB)

Reference : viralpatel.net

Ready for winter? Let's hibernate!

Here’s a long article to show you how to integrate JSF 2.0, Spring and Hibernate together. At the end of the article, you will create a page which display a list of the existing customer from database and a “add customer” function to allow user to add a new customer into database.

P.S In this example, we are using MySQL database and deploy to Tomcat 6 web container.

1. Project Structure

Directory structure of this example

jsf2-spring-hibernate-folder-1
jsf2-spring-hibernate-folder-2

2. Table Script

Create a customer table and insert 2 dummy records.

DROP TABLE IF EXISTS `mkyongdb`.`customer`;
CREATE TABLE  `mkyongdb`.`customer` (
  `CUSTOMER_ID` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `NAME` VARCHAR(45) NOT NULL,
  `ADDRESS` VARCHAR(255) NOT NULL,
  `CREATED_DATE` datetime NOT NULL,
  PRIMARY KEY (`CUSTOMER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

INSERT INTO mkyongdb.customer(customer_id, name, address, created_date)
VALUES(1, 'mkyong1', 'address1', now());
INSERT INTO mkyongdb.customer(customer_id, name, address, created_date)
VALUES(2, 'mkyong2', 'address2', now());

3. Hibernate Stuff

A model class and Hibernate mapping file for customer table.

File : Customer.java

package com.mkyong.customer.model;

import java.util.Date;

public class Customer{

	public long customerId;
	public String name;
	public String address;
	public Date createdDate;

	//getter and setter methods

}

File : Customer.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.mkyong.customer.model.Customer" 
        table="customer" catalog="mkyongdb">

        <id name="customerId" type="long">
            <column name="CUSTOMER_ID" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="NAME" length="45" not-null="true" />
        </property>
        <property name="address" type="string">
            <column name="ADDRESS" not-null="true" />
        </property>
        <property name="createdDate" type="timestamp">
            <column name="CREATED_DATE" length="19" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

4. Spring Stuff

Spring’s BO and DAO classes for business logic and database interaction.

File : CustomerBo.java

package com.mkyong.customer.bo;

import java.util.List;

import com.mkyong.customer.model.Customer;

public interface CustomerBo{

	void addCustomer(Customer customer);

	List<Customer> findAllCustomer();

}

File : CustomerBoImpl.java

package com.mkyong.customer.bo.impl;

import java.util.List;
import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.dao.CustomerDao;
import com.mkyong.customer.model.Customer;

public class CustomerBoImpl implements CustomerBo{

	CustomerDao customerDao;

	public void setCustomerDao(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}

	public void addCustomer(Customer customer){

		customerDao.addCustomer(customer);

	}

	public List<Customer> findAllCustomer(){

		return customerDao.findAllCustomer();
	}
}

File : CustomerDao.java

package com.mkyong.customer.dao;

import java.util.List;

import com.mkyong.customer.model.Customer;

public interface CustomerDao{

	void addCustomer(Customer customer);

	List<Customer> findAllCustomer();

}

File : CustomerDaoImpl.java

package com.mkyong.customer.dao.impl;

import java.util.Date;
import java.util.List;

import com.mkyong.customer.dao.CustomerDao;
import com.mkyong.customer.model.Customer;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class CustomerDaoImpl extends 
       HibernateDaoSupport implements CustomerDao{

	public void addCustomer(Customer customer){

		customer.setCreatedDate(new Date());
		getHibernateTemplate().save(customer);

	}

	public List<Customer> findAllCustomer(){

		return getHibernateTemplate().find("from Customer");

	}
}

File : CustomerBean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

   	<bean id="customerBo" 
         class="com.mkyong.customer.bo.impl.CustomerBoImpl" >
   		<property name="customerDao" ref="customerDao" />
   	</bean>

   	<bean id="customerDao" 
         class="com.mkyong.customer.dao.impl.CustomerDaoImpl" >
   		<property name="sessionFactory" ref="sessionFactory" />
   	</bean>

</beans>

5. Spring + Database

Configure database detail in Spring.

File : db.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mkyongdb
jdbc.username=root
jdbc.password=password

File : DataSource.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean 
   class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="location">
		<value>WEB-INF/classes/config/database/db.properties</value>
   </property>
</bean>

  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="${jdbc.driverClassName}" />
	<property name="url" value="${jdbc.url}" />
	<property name="username" value="${jdbc.username}" />
	<property name="password" value="${jdbc.password}" />
  </bean>

</beans>

6. Spring + Hibernate

Integrate Hibernate and Spring via LocalSessionFactoryBean.

File : HibernateSessionFactory.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<!-- Hibernate session factory -->
<bean id="sessionFactory" 
     class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

    <property name="dataSource">
      <ref bean="dataSource"/>
    </property>

    <property name="hibernateProperties">
       <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
         <prop key="hibernate.show_sql">true</prop>
       </props>
    </property>

    <property name="mappingResources">
	<list>
          <value>com/mkyong/customer/hibernate/Customer.hbm.xml</value>
	</list>
     </property>	

</bean>
</beans>

7. JSF 2.0

JSF managed bean to call Spring’s BO to add or get customer’s records from database.

File : CustomerBean.java

package com.mkyong;

import java.io.Serializable;
import java.util.List;

import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.model.Customer;

public class CustomerBean implements Serializable{

	//DI via Spring
	CustomerBo customerBo;

	public String name;
	public String address;
	//getter and setter methods

	public void setCustomerBo(CustomerBo customerBo) {
		this.customerBo = customerBo;
	}

	//get all customer data from database
	public List<Customer> getCustomerList(){
		return customerBo.findAllCustomer();
	}

	//add a new customer data into database
	public String addCustomer(){

		Customer cust = new Customer();
		cust.setName(getName());
		cust.setAddress(getAddress());

		customerBo.addCustomer(cust);

		clearForm();

		return "";
	}

	//clear form values
	private void clearForm(){
		setName("");
		setAddress("");
	}

}

A JSF page to display existing customer records via h:dataTable and a few text components to allow user to insert new customer record into database.

File : default.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!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"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      >
    <h:head>
    	<h:outputStylesheet library="css" name="table-style.css"  />
    </h:head>

    <h:body>

    	<h1>JSF 2.0 + Spring + Hibernate Example</h1>

 		<h:dataTable value="#{customer.getCustomerList()}" var="c"
    			styleClass="order-table"
    			headerClass="order-table-header"
    			rowClasses="order-table-odd-row,order-table-even-row"
    		>

    		<h:column>
    			<f:facet name="header">
    				Customer ID
    			</f:facet>
    				#{c.customerId}
    		</h:column>

    		<h:column>
    			<f:facet name="header">
    				Name
				</f:facet>
    				#{c.name}
    		</h:column>

 			<h:column>
    			<f:facet name="header">
    				Address
				</f:facet>
    				#{c.address}
    		</h:column>

    		<h:column>
    			<f:facet name="header">
    				Created Date
				</f:facet>
    				#{c.createdDate}
    		</h:column>

    	</h:dataTable>

 		<h2>Add New Customer</h2>
 		<h:form>

 			<h:panelGrid columns="3">

				Name : 
				<h:inputText id="name" value="#{customer.name}" 
					size="20" required="true"
					label="Name" >
				</h:inputText>

				<h:message for="name" style="color:red" />

				Address : 
				<h:inputTextarea id="address" value="#{customer.address}" 
					cols="30" rows="10" required="true"
					label="Address" >
				</h:inputTextarea>

				<h:message for="address" style="color:red" />

			</h:panelGrid>

			<h:commandButton value="Submit" action="#{customer.addCustomer()}" />

 		</h:form>

    </h:body>

</html>

8. JSF 2.0 + Spring

Integrate JSF 2.0 with Spring, see detail explanation here – JSF 2.0 + Spring integration example

File : applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<!-- Database Configuration -->
	<import resource="classes/config/spring/beans/DataSource.xml"/>
	<import resource="classes/config/spring/beans/HibernateSessionFactory.xml"/>

	<!-- Beans Declaration -->
	<import resource="classes/com/mkyong/customer/spring/CustomerBean.xml"/>

</beans>

File : faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    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-facesconfig_2_0.xsd"
    version="2.0">

	<application>
    	<el-resolver>
    		org.springframework.web.jsf.el.SpringBeanFacesELResolver
    	</el-resolver>
  	</application>

	<managed-bean>
		<managed-bean-name>customer</managed-bean-name>
		<managed-bean-class>com.mkyong.CustomerBean</managed-bean-class>
		<managed-bean-scope>session</managed-bean-scope>
		<managed-property>
			<property-name>customerBo</property-name>
			<value>#{customerBo}</value>
		</managed-property>
	</managed-bean>

</faces-config>

File : 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>JavaServerFaces</display-name>

  <!-- Add Support for Spring -->
  <listener>
	<listener-class>
		org.springframework.web.context.ContextLoaderListener
	</listener-class>
  </listener>
  <listener>
	<listener-class>
		org.springframework.web.context.request.RequestContextListener
	</listener-class>
  </listener>

  <!-- Change to "Production" when you are ready to deploy -->
  <context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
  </context-param>

  <!-- Welcome page -->
  <welcome-file-list>
    <welcome-file>faces/default.xhtml</welcome-file>
  </welcome-file-list>

  <!-- JSF mapping -->
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>  <!-- Map these files with JSF -->
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping></web-app>

9. Demo

Run it, fill in the customer data and click on the “submit” button.

jsf2-spring-hibernate-example-1
jsf2-spring-hibernate-example-2

Download Source Code

·

Introduction

 

In
this tutorial we will create a simple web service and a client web application
using eclipse IDE along with
Lomboz
plug
in.
We
will also deploy and test the web service on Tomcat 5.5.4 web application
server. This application, while simple, provides a good introduction to Web
service development and some of the Web development tools available.

 

·
Environment

 

J2SDK
1.4.2

http://java.sun.com/

 

Eclipse
3.1

 

http://www.eclipse.org/

 

 

Tomcat
5.5.4

 

http://tomcat.apache.org/

 

 

Lomboz
3.1RC2

http://lomboz.objectweb.org/

 

 

 

·
Installation

 

Install
JDK (in D:\j2sdk1.4.2_04)

 

Install
Tomcat (in E:\Tomcat5.5)

 

Install
Eclipse (in E:\Eclipse3.1)

 

Install
Lomboz (in E:\Eclipse3.1)

 

·
Setting up

 

  1. Set
    up the installed JRE in eclipse (Windows -> Preferences -> Java ->
    Installed JREs)
     

 

 

  1. Set
    up the installed runtime for server in eclipse (Windows -> Preferences
    -> Server -> Installed Runtimes)
     

 

 

  1. Set
    up the Server view in eclipse (Windows -> Show View -> Other)
     

 


 

 

  1. Set
    up the Tomcat Server by right clicking and selecting New -> Server option
    from the Server view in eclipse
     

 

 

 

 

 

 

·
Creating a Web service

 

  1. Create
    a new Dynamic Web Project in eclipse (File -> New -> Other)
     

 

 

 

  1. Enter
    name as ?WebServiceTutorial?, select project location as ?E:\Test?
    and select Apache Tomcat v5.5 as the Target server.
     

 

 

 

  1. Now
    create a new Java class from the Project Explorer (Dynamic Web Projects
    -> Java Source -> New -> Class)
     

 

 

 

  1. Enter
    name as ?Hello? and package as ?com.tutorial?.
     

 

 

  1. Add
    a simple method in the ?Hello? class as below.
     


public String sayHello(String name){

 


return “Hello ” + name;

 


}

 


 

 

  1. Save
    and build the project.
     
  2. Create
    a new Web service in eclipse (File -> New -> Other)
     

 

 

  1. Select
    Generate a proxy.
     
  2. Select
    Test the Web service.
     
  3. Select
    Overwrite files without warning.
     

 

 

  1. Select
    or enter the Bean name as ?com.tutorial.Hello?. This is the java class
    that we just now created.
     

 

 

  1. Continue
    the wizard by clicking Next and finish.
     
  2. On
    Finish, the Tomcat server starts up and launches the Test client.
     
  3. Verify
    the generated contents. Look for Hello.class and the generated JSPs as
    below.
     

 

 

 

 

 

  1. Verify
    the Tomcat folder and ensure the newly created web applications ?
    WebServiceTutorial, WebServiceTutorialClient.
     

 

 

 

 

  1. We
    can also run the following url from the browser to access/test the Web
    service.
     

http://localhost:8080/WebServiceTutorialClient/sampleHelloProxy/TestClient.jsp

 

 

  1. If
    servlet error ?org.eclipse.jst.ws.util.JspUtils cannot be resolved or is
    not a type? is thrown on the browser, then copy the webserviceutils.jar
    file from the E:\Eclipse3.1\eclipse\plugins\org.eclipse.jst.ws.consumption_0.7.0
    into the WEB-INF\lib folder of the WebServiceTutorialClient application and
    restart the Tomcat server.
     
  1. The
    browser displays the methods available in the web service.
     

 

 

 

  1. Click
    on the sayHello(..) method, enter your name (for e.g. ?Jeeva?) in
    the inputs section and click ?Invoke?.
     

 

 

 

  1. The
    browser greets using the web service.
     

 

 

 

 

 

  1. The
    WSDL for the Hello Web service can be found in E:\Test\WebServiceTutorial\WebContent\wsdl\Hello.wsdl.
    On double-click, the WSDL opens in a graphical editor.
     

 

 

 

  1. Right-click
    on the WSDL file and explore the options to test the web service / publish
    the WSDL file / generate client / etc.
     

 

 

 

 

·
Conclusion

 

In this
tutorial we learned how to create a simple web service and a client web
application using eclipse IDE along with
Lomboz
plug
in.
We
also deployed and tested the web service on Tomcat 5.5.4 web application server.
This application, while simple, provides a good introduction to Web service
development and some of the Web development tools available.

Reference # http://www.roseindia.net/webservices/buildingsimplewebservice.shtml