Slide 1

Slide 1 text

Spring MVC 3.0 By Krishantha Dinesh (HDIT, PGDIT, MscIT, MBCS, MIEEE) [email protected] www.krishantha.com Java walkthrough by Krishantha Dinesh - www.krishantha.com

Slide 2

Slide 2 text

Prerequisites • Java.basicknowladge >(60/100); • Spring fundamentals • Mobilephone.soundmode=soundmode.completesilent && soundmode.completesilent != soundmode.vibrate Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 3

Slide 3 text

What are the similar frameworks • Struts used to be the standard, Struts 1. It was eventually very outdated. Struts 2 was a significant change all for the better than the original Struts but different enough that a lot of people has lost their loyalty for Struts, • Tapestry still is a very decent framework but is governed by one person and someone at the WIM or whatever project he was working on. Tapestry was one of the first heavily object-oriented or POJO-based web frameworks. • Wicket is a lightweight framework that sells itself on being easier to configure than some of the other frameworks that are out there. Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 4

Slide 4 text

• GWT Google Web Toolkit is a very rich user experience framework with a steeper learning curve than a lot of the other frameworks that are out there. • JSF Actually is the only true standard framework for the web out there is, J2EE based as well and it's a very rich user experience. It comes with libraries like ice faces and richfaces and other third-party components for integrating into JSF. • Spring MVC. Spring MVC is a very unobtrusive framework. It is lightweight in a sense that there's very little overhead in running it but it's a very capable, heavy duty framework. It pulls a lot of the best practices from all of these frameworks we just mentioned and combines it into Spring MVC. Plus, it just makes sense that Spring MVC integrates very nicely with Spring and all the other capabilities that Spring has available for us to use. Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 5

Slide 5 text

What is spring • Its not limited to specific group • It may be a RESTfull application , jsp , freemarker, velocity or etc • Web framework developed based on principles of spring • POJO based, unit testable, interface driven • Very light weight • Based on dispatcher servlet/front controller pattern • Build from short comings from struts 1 • Support for Themes, Locales , REST services and annotation based configuration Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 6

Slide 6 text

Architecture Java Servlets /JEE Spring MVC Customer App Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 7

Slide 7 text

Request Response life cycle Front Controller Controller Backend Request View Template Handled Req Create Model Delegate Request Delegate Rendering Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 8

Slide 8 text

Engineers talks • Dispatcher servlets – entry point for the servlet [front controller] • Controller – router , command pattern object that handle the request • Request mapping – URL and request type that method tied to • View resolver – to locate view • Servlet config – Configuration file per dispatcher servlet Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 9

Slide 9 text

Requirement [prerequisites] • Java 7 or 5 later • Maven 3.0 + • Spring STS or eclipse • Apache tomcat server Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 10

Slide 10 text

What we going to build • EventManager application with following features 1. Allow enter Events 2. Allow Enter Activities 3. Fetch all Event types 4. Manipulate Event type using jQuery Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 11

Slide 11 text

Download with maven • Only following 3 dependency needed • Spring-webmvc • Servlet-api • jstl Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 12

Slide 12 text

What we need Java 7

Slide 13

Slide 13 text

Demo • Open spring sts and close all existing projects • FileàNewàotheràMaven project and click next Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 14

Slide 14 text

Click Next Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 15

Slide 15 text

archetype • Select maven-archetype-webapp Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 16

Slide 16 text

Fill the required detail • Groupid – company • Artifactid – application name Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 17

Slide 17 text

Add required dependencies Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 18

Slide 18 text

Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 19

Slide 19 text

What's need to be configured Configure Web.xml Configure Servletconfig.xml Add Controller Add View Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 20

Slide 20 text

Where it going to host • We are going to use tomcat • Tomcat is just a web container. It does not have app server functionality • Download form http://tomcat.apache.org • For this training we are using 7.x Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 21

Slide 21 text

Setup server on IDE Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 22

Slide 22 text

Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 23

Slide 23 text

Standards • Put all view technology pages under WEB-INF Directory – Doing this we can hide filename from visitors – Control the direct navigation. Even user knows about file name thay cant access directly • Internal resource view resolver can resolve the view • addActivity.jsp will comes like – http://localhost:8080/EventManager/addActivity • Controller names with @Controller annotation • Name according to your business domain • Set path using @RequestMapping annotation Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 24

Slide 24 text

Change the web.xml for 2.5 standards • Default web.xml file use old style configuration. Delete first part and change it to schema based configurations Event Manager Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 25

Slide 25 text

Lets begin… • Now we going to first create the dispatcher servlet for the application. Open the web.xml file and edit as follows • Mentioning about the servlet configuration is optional however it is highly recommended to do it. • Because its tell where it should look for configuration file and how it named • After that define servlet mapping. It is nothing but route trafic • Name of the servlet mapping section should be exactly match with servlet section Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 26

Slide 26 text

Web.xml look like this Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 27

Slide 27 text

servletConfig.xml • This is namespace basis • For use you need to define the namespace • There are certain pre-defined namespaces comes with IDE Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 28

Slide 28 text

servletConfig.xml 2 • As we mentioned in web.xml file create the folder sturcture • Now add fileà new à spring bean configuration file to config directory • Since we use STS it will add xml header automatically • Click on namespace tab and add MVC and CONTEXT namespacesS Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 29

Slide 29 text

Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 30

Slide 30 text

Configure as annotation driven • Add following lines to config file • – To specify this project is annotation driven • – To specify where it should look for component Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 31

Slide 31 text

Create java code • First create folder structure • Right click on project and add new folder src/main/java • Right click on java folder and add to build path if it is not added Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 32

Slide 32 text

Add new controller class Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 33

Slide 33 text

Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 34

Slide 34 text

Convert POJO to controller • Add @Controller annotation • Add a method to return a greeting message • @RequestMapping annotation to bind a url to this method • Add a string to model render on view Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 35

Slide 35 text

Create JSP page • Create new directory under EventManager/src/main/webapp/WEB-INF for jsp as jsp • Fileà newà jsp • Make sure to same the file name what we returned from method • Edit the jsp to print the value comes for model [key] Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 36

Slide 36 text

Configure which jsp to pick [routing] • Need to add a bean to sevletConfig file • There are two ways to do it. We can use either way • Long way Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 37

Slide 37 text

Short way • Add namespace “P” by navigating to namespace tab • And now you can add bean like this • Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 38

Slide 38 text

Its time to RUN • Now all required configurations are made. • Restart tomcat server make sure no errors on startup • Enter following URL on browser • http://localhost:8080/EventManager/greeting.html • You will see the page Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 39

Slide 39 text

Anatomy • Web.xml has dispatcher servlet mapped to servletConfig.xml • Added internalResourceViewResolver for resolve jsp pages • Added java controller • Added @RequestMapping annotation to tight method with URL • Added a return jsp name. this return value should same as jsp page Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 40

Slide 40 text

Architecture Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 41

Slide 41 text

MVC Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 42

Slide 42 text

MVC in web Model View Controller Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 43

Slide 43 text

Tiered architecture • Main benefit is separation of concerns • Re usable layers • Maintenance Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 44

Slide 44 text

Spring MVC 3 component • Controller to route traffic • Service for business logic store also where start our tractions • Repository tier is almost like DAO Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 45

Slide 45 text

Controller • Annotated with @Controller • Suppose to handle incoming request and build the response • Business logic should NOT put here • Grab information from request/response and hand over to the business logic • Handle exception and routed in required way Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 46

Slide 46 text

Service • Annotated with @service • Service tier define action (verbs) to the system • Business logic should contained here • State management should handle here • Transaction should begins here • May have same method which repository has but in different focus Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 47

Slide 47 text

Repository • Annotated with @Repository • Define data (nouns) to the system • Focus to interaction with database and CRUD operations • One to one mapping with object – Customer à customerRepository – Company à companyRepository Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 48

Slide 48 text

Controllers Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 49

Slide 49 text

What is Controller • It is the center of the concept as well as part of the spring mvc framework • Decide what to do based on the action Controller Backend Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 50

Slide 50 text

Controller responsibilities • Transform user input in to model • Provide access to business logic • Handle exception and route those in correct way and tier • Determine view based on logic • Its is really simple class which has no implements , interfaces etc • Need @Controller annotation and @ReuestMapping. This tells spring which method is going to handle the request – Spring do have concrete classes you can extends and it maps url to class based on name. however it is old fashion and NOT depreciated yet. Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 51

Slide 51 text

Lets change the application in meaningful way • Add new method to controller and create new jsp file Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 52

Slide 52 text

Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 53

Slide 53 text

Working with parameter • @ModelAttribute is used to whenever wants to send data to controller or retriew data from controller • All these doing using simple POJO • Used with HTTP GET for get data back • Use HTTP POST when to send to controller • Can be validated with binding results Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 54

Slide 54 text

Customize jsp • Add following tag library • <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> • Add new form Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 55

Slide 55 text

Execute and read the exception • In simply what it said is it cannot find server side component to serve for value of the form Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 56

Slide 56 text

Fix the problem • Create new package as x.x.x.x.x.model • Create new class as Activity Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 57

Slide 57 text

Edit controller to attach the model Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 58

Slide 58 text

Edit the jsp file to bind the controller Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 59

Slide 59 text

It is working. • Just run the jsp page and enter value and submit • Go to IDE and see console window Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 60

Slide 60 text

Views Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 61

Slide 61 text

About view • View is the V part of mvc and also what we see • As a convention we place all jsp in jsps directory inside WEB-INF • It will help to prevent deep link and book marking as user must navigate through the our page navigation system means to secure our application • Should not carry any business logic here as this is dedicated for presentation part • We use internalResourceViewResolver to pick the correct view. It can find view by looking the string view return Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 62

Slide 62 text

View - advance • Controller and pass model to view resolver with the data for view if necessary. • View can render those data for presentations Controller View resolver model Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 63

Slide 63 text

View resolvers • There are many view resolvers ship with spring and you can have your own. It just implement ViewResolver interface – BeanNameViewResolver – ContentNegotiatingViewResolver – JasperReportViewResolver – TilesViewResolver – UrlBasedViewResolver – ResourceBundleViewResolver Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 64

Slide 64 text

Chaining • There are 2 types of chaining • Chaining helpful to navigation specially on redirections Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 65

Slide 65 text

Execute • Now try to browse the page and see what you can see • Why Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 66

Slide 66 text

• Because when forward chain requested it go out from container and comes back. Since we mentioned to process only *.html files in web.xml it gives error. • Fix the code like this Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 67

Slide 67 text

Chaining - redirect • Change forward to redirect and see how its work Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 68

Slide 68 text

? • Because when you use redirect it close the existing request and create new request • But you can see you cant test is as on first run it redirected to subActivity. • Make following change to over cum this. Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 69

Slide 69 text

Resolve static views • So far we know how we can resolve dynamic views • Reset project to the status where we was • Add mvc:resources to servletConfig.xml • Update web.xml to accept pdf • Create new folder and add files for it • Try to browse the file via URL • You can see its bypass standard controller Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 70

Slide 70 text

Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 71

Slide 71 text

Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 72

Slide 72 text

Tag library Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 73

Slide 73 text

What are the tags In spring • There are two type of tag libraries available in spring 1. Spring.tlg 1. Validating error 2. Output internationalize messages 3. Setting themes 2. Spring-form.tld 1. Processing form data 2. Came from HTML form tag Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 74

Slide 74 text

Message tag for get message from external files • Instead of hard code message in a application we can get captions from text files. • We can create property file and use tag libraries for read those file • Create property file in resource section of the project. Maven will automatically add it in to classpath • Add enter activity caption for that file Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 75

Slide 75 text

Change jsp file • Edit jsp file and add tag library and add sring tag over text Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 76

Slide 76 text

Create a bean for process • Open servletConfig.xml and add following bean Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 77

Slide 77 text

Interceptors • It is part of request life cycle and usually use to intercept the data which comes from jsp on the way to controller • It has ability to intercept data on the way to controller or way back from controller. [pre-handle and post-handle] • It has override methods to change values • we can use this for multi language application Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 78

Slide 78 text

Modify the page to support for multiple language Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 79

Slide 79 text

Create message file • Add new property file for the resource folder with the _si example messages_si.properties for japan • Translate your text and paste their • And create new bean now (see next page) • Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 80

Slide 80 text

Change locale Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 81

Slide 81 text

???? à change encoding Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 82

Slide 82 text

Extend the application • We are going to extend our application • Create other page to enter Events • R/C ànew àjsp [addEvent] Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 83

Slide 83 text

Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 84

Slide 84 text

Add Event object to model Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 85

Slide 85 text

Controller • This controller design in different way • We get Model object to in to send the data to jsp • Execute and see the result Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 86

Slide 86 text

Save data • Since we use new Event() at every time it kills the data. • Lets try to save the data to session!!!! • It is easy with spring mvc. Add @SessionAttribute(“

Slide 87

Slide 87 text

Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 88

Slide 88 text

Now run and see Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 89

Slide 89 text

Make sure its come from session • Change the jsp as follows and test Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 90

Slide 90 text

Validations Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 91

Slide 91 text

• Validations we do perform for any application development • Spring mvc has a capability to the validation through more systematic way • Validation are two types 1. Business logic validation 1. Validation should not bring to controller. Need to handle those in service tier 2. Restriction validation 1. Name not null , age >20 etc Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 92

Slide 92 text

Errors with tag • We have tag libraries to handle the errors • On that there are specific libraries to display errors • Those can change colors , fonts etc based on error • We can use validator interface and validationUtil helper class by theway this is old fashion • Now we use JSR-303 standards specification for validation. This is java standards • It use hibernate validator and It is annotation based Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 93

Slide 93 text

Lets validate to define minimum target • In our application there is not minimum target defined. Lets define it using JSR- 303 • Add following dependency and repository for pom file org.hibernate hibernate-validator 4.2.0.Final jboss-public-repository-group Jboss public Repository Group http://repository.jboss.org/nexus/content/groups/public Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 94

Slide 94 text

Add validation to Target Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 95

Slide 95 text

Controller to validate the validator • Now need to configure controller to say not to accept if not validated Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 96

Slide 96 text

No error messages L • We need to add meaning full massages to user to see where it went wrong • Change the jsp to post error Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 97

Slide 97 text

Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 98

Slide 98 text

Meaningful error Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 99

Slide 99 text

highlight Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 100

Slide 100 text

Error on same place Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 101

Slide 101 text

Store error message external file • Change the message.properties file and add new message • Remove message from @size validation in Event class Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 102

Slide 102 text

Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 103

Slide 103 text

Ajax Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 104

Slide 104 text

REST ??? • Spring MVC able to produce JSON services • More easy consumable across the application • Using deferent view resolver we can produce JSON • REST services mean what we can do with domain object and can be interact with services (action) • REST design almost like CRUD function replace POST,GET,PUT,DELETE respectively Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 105

Slide 105 text

ContentNegotiatingViewResolver • It use to handle multiple content type based on request • Accept XML,JSON,HTML headers • Can be combine with other view resolvers • Need to have additional jar • Add following dependency Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 106

Slide 106 text

In spring 3 pom file Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 107

Slide 107 text

Spring mvc 4 pom file Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 108

Slide 108 text

Add BIG bean in spring 3 Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 109

Slide 109 text

Big bean in spring 4 Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 110

Slide 110 text

Create model to json service Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 111

Slide 111 text

EventController in spring 3 Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 112

Slide 112 text

New Controller in spring 4 Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 113

Slide 113 text

Change web.xml and see Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 114

Slide 114 text

json output Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 115

Slide 115 text

Work with jQuery • jQuery is widely use UI technology • It is java script library • It is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript. Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 116

Slide 116 text

Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 117

Slide 117 text

Write jQuery function Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 118

Slide 118 text

Change Events.java Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 119

Slide 119 text

Best Practices • Where is service ? – Service layer is missing. Theoretically all business logics should reside service layer • Create service package • Add service class • Annotate with @service Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 120

Slide 120 text

Now move business logic to here • Remove business logic from EventController and move here Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 121

Slide 121 text

Code to interface • Now extract interface from service (R/C on Impl à refactor à extract interface • Then auto wire the controller Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 122

Slide 122 text

Finally J Spring MVC by Krishantha Dinesh - www.krishantha.com

Slide 123

Slide 123 text

Have Fun Life with SpRiNg J Spring MVC by Krishantha Dinesh - www.krishantha.com