程序代写代做代考 Java graph go jvm C html junit Hive JDBC database Developing a Spring Framework MVC application step-by-step This document is created by Yu Zhao and edited by Chunfeng Liu.

Developing a Spring Framework MVC application step-by-step This document is created by Yu Zhao and edited by Chunfeng Liu.
Table of Contents
Developing a Spring Framework MVC application step-by-step………………………………………… 1 Chapter 0: Things You Need to Know……………………………………………………………………………………………..2 Integrated development environment (IDE): ……………………………………………………………………………………………. 2 Download JDK …………………………………………………………………………………………………………………………………………….. 2 Code:……………………………………………………………………………………………………………………………………………………………… 2 Proxy: ……………………………………………………………………………………………………………………………………………………………. 2 Useful Maven Commands: …………………………………………………………………………………………………………………………. 3 Chapter 1: Basic Application and Environment Setup……………………………………………………………………4
1.1 Install and configure tomcat server on STS …………………………………………………………………………………. 4
1.2 Create a basic SpringMVC project ……………………………………………………………………………………………….. 6
Chapter 2: Developing and Configuring the Views and the Controller ……………………………………… 10 2.1 Configure JSTL and add JSP header file …………………………………………………………………………………………..10 2.2 Create a controller for the view…………………………………………………………………………………………………………..12 2.3 Decouple the view from the controller ………………………………………………………………………………………………13 Chapter 3: Developing the Business Logic……………………………………………………………………………………. 17 3.0 Refine packages ……………………………………………………………………………………………………………………………………17 3.1 Review the business case of the Inventory Management System…………………………………………………..19 3.2 Add some classes for business logic…………………………………………………………………………………………………..19 Chapter 4: Developing the Web Interface…………………………………………………………………………………….. 29 4.1 Add reference to business logic in the controller ……………………………………………………………………………..29 4.2 Modify the view to display business data and add support for message bundle …………………………..31 4.3 Add some test data to automatically populate some business objects …………………………………………… 33 4.4 Add the message bundle………………………………………………………………………………………………………………………33 4.5 Adding a form……………………………………………………………………………………………………………………………………….34 4.6 Adding a form controller……………………………………………………………………………………………………………………..39 Chapter 5: Implementing Database Persistence…………………………………………………………………………… 45 5.1 Using database (MySQL) in a web application ………………………………………………………………………………..45 5.2 Dependency and configuration……………………………………………………………………………………………………………45 5.3 Annotation based web application development (Important)………………………………………………………….50 5.3 Others…………………………………………………………………………………………………………………………………………………….60

Chapter 0: Things You Need to Know
We recommend using your personal computer to complete the practice in tutorials.
Integrated development environment (IDE):
Download recommended IDE Spring Tool Suite (STS) from https://spring.io/tools3/sts/all Download the latest/stable version based on your OS of personal computer.
Note: Please make sure you download the right version. All the contents in this document are created based on the version of 3.9.*
Download JDK
The version (3.9.4) of STS only supports version 8 or higher version of JDK. If your JDK version is lower than 8, make sure you update your JDK to 8 or higher version. You can download JDK 8 from this page (http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html). Please select the correct JDK based on your OS.
Code:
The final source codes of this project is available at: https://bitbucket.org/ianliu0420/springapp-2016
* In this document, all screenshots have the URL http://localhost:8080/XXX/XXX, which is my own
configuration of Tomcat. You need to use your own Tomcat (or other server) port number. (Default is 8080)
Proxy:
If you are using your own laptop, please skip the following section, and continue the tutorial from Chapter 1. If you are working on the lab computer, you need to configure the proxy settings of Maven as follow to make everything work fine.
Please go through the document of “elec5619-maven.doc” to set up the proxy and install maven into your STS.
If the above proxy instruction does not work for the computer, please try to use Maven in command line.
Steps to take configure the computers:
1. Unzip the distribution archive, i.e. apache-maven-3.1.0-bin.zip to the directory you wish to install Maven 3.1.0 (in our case, unzip the file to the Desktop). These instructions assume you chose C:\Program Files\Apache Software Foundation. The subdirectory apache-maven-3.1.0 will be created from the archive.
2. Add the M2_HOME environment variable by opening up the system properties (WinKey + Pause), selecting the “Advanced” tab, and the “Environment Variables” button, then adding the M2_HOME variable in the user variables with the value C:\Program Files\Apache Software Foundation\apache-

maven-3.1.0. Be sure to omit any quotation marks around the path even if it contains spaces. Note:
For Maven 2.0.9, also be sure that the M2_HOME doesn’t have a ‘\’ as last character.
3. In the same dialog, add the M2 environment variable in the user variables with the
value %M2_HOME%\bin.
4. Optional: In the same dialog, add the MAVEN_OPTS environment variable in the user variables
to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can
be used to supply extra options to Maven.
5. In the same dialog, update/create the Path environment variable in the user variables and prepend
the value %M2% to add Maven available in the command line.
6. In the same dialog, make sure that JAVA_HOME exists in your user variables or in the system
variables and it is set to the location of your JDK, e.g.C:\Program Files\Java\jdk1.5.0_02 and
that %JAVA_HOME%\bin is in your Path environment variable.
7. Open a new command prompt (Winkey + R then type cmd) and run mvn –version to verify that it
is correctly installed.
Useful Maven Commands:
ref: http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html 1. mvn –version ⇒ check the version of the Maven installation
2. mvn test ⇒ run tests within the test package
3. mvn install or mvn compile ⇒ build the project
4. mvn clean ⇒ clean the project that has been built, remove the binary files
5. mvn tomcat:run ⇒ run project on built-in Tomcat server
6. mvn -Dmaven.tomcat.port=8181 tomcat:run-war ⇒ run your application on Tomcat on port 8181.

Chapter 1: Basic Application and Environment Setup
1.1 Install and configure tomcat server on STS
You can follow this video (https://www.youtube.com/watch?v=n14rpj_08wM) to complete this step.
1. Download the Tomcat 8.0.53 server from https://tomcat.apache.org/download-80.cgi
2. Then, decompress Tomcat into a folder, such as “C:\Elec5619\”
3. On STS, Select Windows->Show view->Servers
4. Under “Servers”, right click, and select “new”, than select “Server”
5. In the pop-up window, select “Apache->Tomcat v8.0 Server”, click “next…”
6. Then another pop-up window will be displayed.
7. In the pop-up window, paste the root directory of your Tomcat 8, for example
“C:\Elec5619\apache-tomcat-8.0.53” in the “Tomcat installation directory” space, and click
Finish.
8. Then your “Servers” Section will be like this:
9. Right click the server, and select open. In the new window, in “Server Location” section, select “Use Tomcat installation”. In the “Deploy path”, please type “webapps”. Then save the settings by “Ctrl+s”.

10. By now, you have already set up a Tomcat 8 server on your STS.
11. In this step, we will test whether the server is able to run correctly.
1) Right click the server
2) Select “Start”
3) Open your web browser, type the link http://localhost:8080/
4) If your web page like following, that means you have already correctly configured a web
server on your machine. Congrats.

1.2 Create a basic SpringMVC project
Now, let’s create a basic Spring MVC project, and it will be used as the base of further tutorials in this document.
Steps to create the project (in STS):
File -> New -> Project -> Spring -> Spring Legacy Project (click next) -> Spring MVC Project Project Name: springapp
Top level package: au.usyd.elec5619

In the package explorer, you will get a project with the following structure.
Now we need to deploy the project into the Tomcat server:
1. Right click Tomcat server, then select “Add and Remove”

2. Add the project to the “Configured” section, then click finish
3. Then right click Tomcat server, then click “Start”
Now you have deployed your project to the Tomcat server, and you can access the pape from the URL:
http://localhost:8080/elec5619/
And the page will be shown like this:

You can check the detail procedures from this video
(https://www.youtube.com/watch?v=S5cbm6SDyvU), and the procedures in the video might be different because of the different version of STS.

Chapter 2: Developing and Configuring the Views and the Controller
2.1 Configure JSTL and add JSP header file
We will be creating a ‘header’ file that will be included in every JSP page that we’re going to write. We ensure the same definitions are included in all our JSPs simply by including the header file. We’re also going to put all JSPs in a directory named ‘views’ under the ‘WEB-INF’ directory. This will ensure that views can only be accessed via the controller since it will not be possible to access these pages directly via a URL. This strategy might not work in some application servers and if this is the case with the one you are using, move the ‘views’ directory up a level. You would then use ‘springapp/war/views’ as the directory instead of ‘springapp/war/WEB-INF/views’ in all the code examples that will follow.
2.1.1 Create the include.jsp file
First we create the header file for inclusion in all the JSPs we create.
In the file ‘springapp/src/main/webapp/WEB-INF/views/include.jsp’:
<%@ page session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
2.1.2 Create the index.jsp file
Now we can update ‘index.jsp’ to use this include file and since we are using JSTL, we can use the tag for redirecting to our front Controller. This means all requests for ‘index.jsp’ will go

through our application framework. Just delete the current contents of ‘index.jsp’ and replace it with the following:
In the file ‘springapp/src/main/webapp/WEB-INF/views/index.jsp’
<%@ include file="/WEB-INF/views/include.jsp" %>
<%-- Redirected because we can't set the welcome page to a virtual URL. --%>
2.1.3 Create the hello.jsp file
Now create another file called ‘hello.jsp’ inside the ‘views’ folder with the following content. In the file ‘springapp/src/main/webapp/WEB-INF/views/hello.jsp’
<%@ include file="/WEB-INF/views/include.jsp" %>
Hello :: Spring Application

Hello – Spring Application

Greetings, it is now



And after creating the ‘hello.jsp’ file the folder structure will be similar to the image below.

2.2 Create a controller for the view
So far, you’ve create all the JSP files, which we call the “views”, for this application. If you want to access those views through a browser, you need to provide other Java classes, which we call “controllers”.
Now create a new Java file called “HelloController” in “springapp/src/main/java/au.usyd.elec5619”, with the following content.
package au.usyd.elec5619;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller;
public class HelloController implements Controller {
protected final Log logger = LogFactory.getLog(getClass()); @Override

public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
String now = (new Date()).toString(); logger.info(“Returning hello view with ” + now);
return new ModelAndView(“hello”, “now”, now); }
}
And add a new line in “springapp/src/main/webapp/WEB-INF/spring/appServlet/servlet-
context.xml”.

Now if you run this application on a server, and go to the URL: http://localhost:8080/elec5619/hello.htm You will be able to see the “hello.jsp” page
2.3 Decouple the view from the controller
Now please open “springapp/src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml” and “springapp/src/main/java/au.usyd/elec5619/HelloController.java”.
In “servlet-context.xml”, please comment out the following lines (should be at around line 19 to 22):


Then run this application on server and go to http://localhost:8080/elec5619/hello.htm again and see what happens.
It’s a 404, which means your application cannot find the specified resource. And please have a look at the output in the Eclipse or STS console.

Now, please navigate to the “HelloController.java” tab opening in your IDE, and comment out the line, which should be the return statement:
return new ModelAndView(“hello”, “now”, now);
And copy and paste “return new ModelAndView(“WEB-INF/views/hello.jsp”, “now”, now);” as the return statement of the handleRequest() function.
Again, restart the server and go to http://localhost:8080/elec5619/hello.htm and see what happens.
The lines we commented out in “servlet-context.xml” are used for mapping to the views. Now, what we need to provide as the first parameter in the highlighted statement of the above image is the entire path to the view page, which is the “hello.jsp” page. And to simplify developers’ work and using logical name to map to different view pages, we need to use the “InternalResourceViewResolver” and specify the “prefix” and “suffix” for the logical name you provide.
Now you can leave your code as is (and you need to write the whole path to views again and again) or you can uncomment the 2 commented sections and remove the lines we just added.

Chapter 3: Developing the Business Logic
This is Part 3 of a step-by-step tutorial on how to develop a Spring application. In this section, we will adopt a pragmatic Test-Driven Development (TDD) approach for creating the domain objects and implementing the business logic for our inventory management system. This means we’ll “code a little, test a little, code some more then test some more”. In Part 1 we configured the environment and set up a basic application. In Part 2 we refined the application by decoupling the view from the controller.
Spring is about making simple things easy and the hard things possible. The fundamental construct that makes this possible is Spring’s use of Plain Old Java Objects (POJOs). POJOs are essentially plain old Java classes free from any contract usually enforced by a framework or component architecture through subclassing or the implementation of interfaces. POJOs are plain old objects that are free from such constraints, making object-oriented programming possible once again. When you are working with Spring, the domain objects and services you implement will be POJOs. In fact, almost everything you implement should be a POJO. If it’s not, you should be sure to ask yourself why that is. In this section, we will begin to see the simplicity and power of Spring.
3.0 Refine packages
So far, we are putting all our Java code directly in the “au.usyd.elec5619” package, which is ok for small project. However, it is not a good practice to do so. We need to put our “M”s, “V”s, and “C”s in different packages.
Now please create 3 sub-packages under the “au.usyd.elec5619” package, with the name “domain”, “web”, and “service”.
And now, you can drag and drop the 2 controllers into the “au.usyd.elec5619.web” package. And you will

see a pop-up window like:
Select “Update fully qualified names in non-java text files (forces preview)”, and click “Preview”. And you will see a second pop-up screen similar to the image below.
And click “OK”.
Then rerun your server and test if all necessary mappings have been correctly updated. (Everything should be working exactly as what you have been doing.)

3.1 Review the business case of the Inventory Management System
In our inventory management system, we have the concept of a product and a service for handling them. In particular, the business has requested the ability to increase prices across all products. Any decrease will be done on an individual product basis, but this feature is outside the scope of our application. The validation rules for price increase are:
● The maximum increase is limited to 50%.
● The minimum increase must be greater than 0%.
Find below a class diagram of our inventory management system.
3.2 Add some classes for business logic
Let’s now add some business logic in the form of a Product class and a service called ProductManager service that will manage all the products.
First we implement the Product class as a POJO with a default constructor (automatically provided if we don’t specify any constructors) and getters and setters for its properties ‘description’ and ‘price’. Let’s also make it Serializable, not necessary for our application, but could come in handy later on when we persist and store its state. The class is a domain object, so it belongs in the ‘domain’ package.
‘springapp/src/main/java/au.usyd.elec5619.domain/Product.java’:

Now we write the unit tests for our Product class. Some developers don’t bother writing tests for getters and setters or so-called ‘auto-generated’ code. It usually takes much longer to engage in the debate (as this paragraph demonstrates) on whether or not getters and setters need to be unit tested as they’re so ‘trivial’. We write them because: a) they are trivial to write; b) having the tests pays dividends in terms of the time saved for the one time out of a hundred you may be caught out by a dodgy getter or setter; and c) they improve test coverage. We create a Product stub and test each getter and setter as a pair in a single test. Usually, you will write one or more test methods per class method, with each test method testing a particular condition in a class method such as checking for a null value of an argument passed into the method.

In the file ‘springapp/src/test/java/au.usyd.elec5619.domain/ProductTest.java’
Next we create the ProductManager. This is the service responsible for handling products. It contains two methods: a business method increasePrice() that increases prices for all products and a getter method

getProducts() for retrieving all products. We have chosen to make it an interface instead of a concrete class for an number of reasons. First of all, it makes writing unit tests for Controllers easier (as we’ll see in the next chapter). Secondly, the use of interfaces means JDK proxying (a Java language feature) can be used to make the service transactional instead of CGLIB (a code generation library).
In the file ‘springapp/src/main/java/au.usyd.elec5619.service/ProductManager.java’
Let’s create the SimpleProductManager class that implements the ProductManager interface.
In the file ‘springapp/src/main/java/au.usyd.elec5619.service/SimpleProductManager.java’
Before we implement the methods in SimpleProductManager, we’re going to define some tests first. The

strictest definition of Test Driven Development (TDD) is to always write the tests first, then the code. A looser interpretation of it is more akin to Test Oriented Development (TOD), where we alternate between writing code and tests as part of the development process. The most important thing is for a codebase to have as complete a set of unit tests as possible, so how you achieve it becomes somewhat academic. Most TDD developers, however, do agree that the quality of tests is always higher when they are written at around the same time as the code that is being developed, so that’s the approach we’re going to take.
To write effective tests, you have to consider all the possible pre- and post-conditions of a method being tested as well as what happens within the method. Let’s start by testing a call to getProducts() returns null.
In the file ‘springapp/src/test/java/au.usyd.elec5619.service/SimpleProductManagerTest.java’
Rerun all the Maven tests target and the test should fail as getProducts() has yet to be implemented. It’s usually a good idea to mark unimplemented methods by getting them to throw an UnsupportedOperationException.
Next we implement a test for retrieving a list of stub products populated with test data. We know that we’ll need to populate the products list in the majority of our test methods in SimpleProductManagerTests, so we define the stub list in JUnit’s setUp(), a method that is invoked before each test method is called.
In the file ‘springapp/src/test/java/au.usyd.elec5619.service/SimpleProductManagerTest.java’

Rerun all the Maven tests target and our two tests should fail.
We go back to the ‘SimpleProductManager’ and implement the getter and setter methods for the products

property.
Rerun the Maven tests target and all our tests should pass.
We proceed by implementing the following tests for the increasePrice() method:
● The list of products is null and the method executes gracefully.
● The list of products is empty and the method executes gracefully.
● Set a price increase of 10% and check the increase is reflected in the prices of all the products in
the list.
In the file ‘springapp/src/test/java/au.usyd.elec5619.service/SimpleProductManagerTest.java’

We return to SimpleProductManager to implement increasePrice().

In the file ‘springapp/src/main/java/au.usyd.elec5619.service/SimpleProductManager.java’
Rerun the Maven tests target and all our tests should pass. *HURRAH* JUnit has a saying: “keep the bar green to keep the code clean.” For those of you running the tests in an IDE and are new to unit testing, we hope you’re feeling imbued with a sense of greater sense of confidence and certainty that the code is truly working as specified in the business rules specification and as you intend. We certainly do.
We’re now ready to move back into the web layer to put a list of products into our Controller model.

Chapter 4: Developing the Web Interface
This is Part 4 of a step-by-step account of how to develop a web application from scratch using the Spring Framework. In Part 1 we configured the environment and set up a basic application. In Part 2 we refined the application that we will build upon. Part 3 added all the business logic and unit tests. It’s now time to build the actual web interface for the application.
4.1 Add reference to business logic in the controller
First of all, let’s rename our HelloController to something more meaningful. How about InventoryController since we are building an inventory system. This is where an IDE with refactoring support is invaluable. We rename HelloController to InventoryController and the HelloControllerTests to InventoryControllerTests. Next, we modify the InventoryController to hold a reference to the ProductManager class. We also add code to have the controller pass some product information to the view. The getModelAndView() method now returns a Map with both the date and time and the products list obtained from the manager reference.
In the file ‘springapp/src/main/java/au.usyd.elec5619.web/InventoryController.java’

We will also need to create the InventoryControllerTest to supply a ProductManager and extract the value for ‘now’ from the model Map before the tests will pass again.

4.2 Modify the view to display business data and add support for message bundle
Using the JSTL tag, we add a section that displays product information. We have also replaced the title, heading and greeting text with a JSTL tag that pulls the text to display from a provided ‘message’ source – we will show this source in a later step.

In the file ‘springapp/src/main/webapp/WEB-INF/views/hello.jsp’

4.3 Add some test data to automatically populate some business objects
It’s time to add a SimpleProductManager to our configuration file and to pass that into the setter of the InventoryController. We are not going to add any code to load the business objects from a database just yet. Instead, we can stub a couple of Product instances using Spring’s bean and application context support. We will simply put the data we need as a couple of bean entries in ‘servlet-context.xml’. We will also add the ‘messageSource’ bean entry that will pull in the messages resource bundle (‘messages.properties’) that we will create in the next step. Also remember to rename the reference to HelloController to InventoryController since we renamed it.
In the file ‘springapp/src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml’
4.4 Add the message bundle

We create a ‘messages.properties’ file in the ‘springapp/src/main/webapp/WEB-INF/classes’ directory. This properties bundle so far has three entries matching the keys specified in the tags that we added to ‘hello.jsp’.
4.5 Adding a form
To provide an interface in the web application to expose the price increase functionality, we add a form that

will allow the user to enter a percentage value. This form uses a tag library named ‘spring-form.tld’ that is provided with the Spring Framework.
We also have to declare this taglib in a page directive in the jsp file, and then start using the tags we have thus imported. Add the JSP page ‘priceincrease.jsp’ to the ‘springapp/src/main/webapp/WEB- INF/views’ directory.

This next class is a very simple JavaBean class, and in our case there is a single property with a getter and setter. This is the object that the form will populate and that our business logic will extract the price increase percentage from.

The following validator class gets control after the user presses submit. The values entered in the form will be set on the command object by the framework. The validate(..) method is called and the command object (PriceIncrease) and a contextual object to hold any errors are passed in.

4.6 Adding a form controller
Now we need to add an entry in the ‘servlet-context.xml’ file to define the new form and controller. We define objects to inject into properties for commandClass and validator. We also specify two views, a formView that is used for the form and a successView that we will go to after successful form processing. The latter can be of two types. It can be a regular view reference that is forwarded to one of our JSP pages.

One disadvantage with this approach is, that if the user refreshes the page, the form data is submitted again, and you would end up with a double price increase. An alternative way is to use a redirect, where a response is sent back to the users browser instructing it to redirect to a new URL. The URL we use in this case can’t be one of our JSP pages, since they are hidden from direct access. It has to be a URL that is externally reachable. We have chosen to use ‘hello.htm’ as my redirect URL. This URL maps to the ‘hello.jsp’ page, so this should work nicely.

In the file ‘springapp/src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml’
Next, let’s take a look at the controller for this form. The onSubmit(..) method gets control and does some logging before it calls the increasePrice(..) method on the ProductManager object. It then returns a ModelAndView passing in a new instance of a RedirectView created using the URL for the success view.

We are also adding some messages to the ‘messages.properties’ resource file.

Compile and deploy all this and after reloading the application we can test it. This is what the form looks like with errors displayed.
Finally, we will add a link to the price increase page from the ‘hello.jsp’.

Chapter 5: Implementing Database Persistence
This is Part 5 of a step-by-step account of how to develop a web application from scratch using the Spring Framework. In Part 1 we configured the environment and set up a basic application. In Part 2 we refined the application that we will build upon. Part 3 added all the business logic and unit tests and Part 4 developed the web interface. It is now time to introduce database persistence. We saw in the earlier parts how we loaded some business objects using bean definitions in a configuration file. It is obvious that this would never work in real life – whenever we re-start the server we are back to the original prices. We need to add code to actually persist these changes to a database.
5.1 Using database (MySQL) in a web application
Almost all web applications need to have their data persisted in databases, and for your project you will need to store your own data somewhere as well. This Chapter gives you a short introduction of using Hibernate and MySQL.
Normally, data manipulation within a database consists of create, retrieve, update, and delete (CRUD in short). Now we need to move our Products from the bean definition to a database.
Firstly, you need to install MySQL database in your computer. Here we provide several videos to guide you install it.
Install MySQL on Mac: https://www.youtube.com/watch?v=Tq0TXcH6dAU Install MySQL on Windows: https://www.youtube.com/watch?v=O4xXzTIcnDE
This web page is a short tutorial to guide you how to do some operation in MySQL database:
https://dev.mysql.com/doc/refman/5.7/en/database-use.html
After installing the MySQL database server. You will need to to create a database called “springapp” in you MySQL. Above link will help you to create databases in MySQL.
5.2 Dependency and configuration
Let’s start from resolving the dependencies of using Hibernate and MySQL. Because you will use new features in Java, you need to tell Maven what it need to get for you. Below is all required jar files (dependency) you’ll need for this chapter, and you can just copy and paste these dependencies to your pom.xml file.
org.springframework spring-orm 3.1.0.RELEASE


org.hibernate hibernate-core 3.5.6-Final

org.hibernate hibernate-entitymanager 3.5.6-Final

org.hibernate hibernate-annotations 3.5.6-Final

mysql
mysql-connector-java
5.1.6

commons-dbcp commons-dbcp 1.4


org.hibernate hibernate-validator 4.3.1.Final

javax.validation validation-api 1.0.0.GA

In order to use a database, you need to have all necessary database configurations values available. The below database.properties file should be placed in the src/main/resources folder

Make sure that the “jdbc.username” and “jdbc.password” are the same as yours when you installing your MySQL server.
Also, you need to tell Spring how to connect to a database. You need to have a persistence-context.xml file to do this for you.

And you need to tell your application that there is another xml configuration file to load while starting the application. You just need to add one line (line 25 of the below screenshot) in your web.xml file, which is in src/main/webapp/WEB-INF folder.

In Chapter 4.3, we created 3 products in servlet-context.xml (which is in src/main/webapp/WEB- INF/spring/appServlet folder) using bean initialization. Now, since we are going to use database, we can remove the 3 products from our application.
But the component that actually connects to the persistence layer is a bean with the name “productManager”, which is a type of SimpleProductManager in this case. For simplicity, we can just comment out the bean definition of this “productManager” and create a new one that connects to the HSQLDB with Hibernate.

5.3 Annotation based web application development (Important)
So far (chapter 2 to 4), all the tutorial is done using xml configuration, which is verbose. A feature of Java called Annotation is able to accomplish the same task. For web development, typically there are 3 annotations that are used most often, which are @Entity, @Controller, and @Service. (Using XML, all you have are beans, but with Annotations, the “beans” are “categorized” into different classes based on their functionality)
The name of these annotations are derived from the roles of the corresponding components within the MVC design pattern.
Entity
@Entity announces the annotated class to be a domain entity, which is the M (model) in MVC. In our case, the Product class should be annotated with @Entity. As you can see in the below screenshot, there are other annotations within the Product class. Those annotations are used by Hibernate to map this Product class to a table called “Product” in the database.
Your task is to annotate Product class (which you have already got in the domain package) in the same way as the screenshot.

Controller
@Controller is used to define a controller, which is C in MVC. We need to create a new controller called ProductController to handle the CRUD functions of products.
In the au.usyd.elec5619.web package, create a new Java class with the name “ProductController”, and at the class level, annotate it with @Controller.
Now, what you have is a controller, and if you run your application (actually, it won’t run, because we have commented out the productManager bean. If you uncomment it, this application will run in the same way as before), Spring will know that this ProductController is a controller, and when requests come, the DispatcherServlet should dispatch some requests to this controller based on the given request URL. However, you haven’t given any URL mapping configuration information to this controller.

Now let’s add a method to this controller called “addProduct”, which should handle the add-a-product request send from a browser. But so far, Spring still doesn’t know how to map the request URL to this controller.
Now we add a new annotation @RequestMapping at both the class level and the method level. And based the annotation at line 9 and line 12, Spring will be able to map a request to http://localhost:8080/elec5619/product/add to ProductController.addProduct(). And this method simply return the logical name of the view file.
Now you need to create a new view file for the addProduct function called add.jsp.

This view file simply contains a form for creating a new Product. And this form will be submitted to http://localhost:8080/elec5619/product/add using POST method, instead of GET.
The addProduct() method we have now is used to handle GET request, which means we need to create another method to handle POST request to the same URL.

See the difference with the previous method? The new addProduct() method is specifically configured to handle POST request through the method=RequestMethod.POST setting. And this method simply redirect the user to hello.htm which contains all existing products in the database.
Service
@Service is used to define a service for your web application. A service is used to handle all processing of any model (or business logic), and a service is typically used inside a controller.
We need to create a new ProductManager subclass for the Product to handle the low level (closer to database) CRUD.
Inside the au.usyd.elec5619.service package, create a new class called DatabaseProductManager and it should implement the ProductManager interface. Wait a minute, there will be new method in the DatabaseProductManager, which handle the CRUD of a Product, do they go into the ProductManager interface? Yes.
We need to update the ProductManager interface first.
Then, we can create the new DatabaseProductManager class to implement the updated interface.

There will be errors in the SimpleProductManager class, because we haven’t implemented the new methods added to the ProductManager interface. You can just add them to the ProductManager class and leave them empty.

Since it is a service class, we annotate it with the @Service annotation, and now Spring knows that this DatabaseProductManager is a Service.

Now, we should introduce Hibernate to our code. Hibernate is like the superior of JDBC at a higher level, and in Hibernate, the Session is the most important entity. The session is all you have to access the database.
To get access to the “session” you need a SessionFactory, which you have already defined at the bottom of the persistence-context.xml file. The SessionFactory is a private instance variable of DatabaseProductManager and there is a setSessionFactory() function with the annotation @Autowired, which is able to inject an instance of SessionFactory to this DatabaseProductManager when this DatabaseProductManager is being created. This process is called “dependency injection”.
The @Transactional annotation at the class level is used to handle database transactions.

I’ve mentioned that a service is typically used in a controller (or other services), and now let’s update our ProductController.
What I did was inject an instance of the ProductManager into the controller and use this productManager to persist a new product in the database. (In this case, the ProductManager is actually an instance of DatabaseProductManager)
Now you can run your application and add new products.

5.3 Others
All CRUD requests should be handled in the ProductController, so below is the complete code.
For Product editing, you need to create a edit.jsp page.

The hello.jsp should also be updated to provide links to edit and delete products.