Spring MVC Margus Hanni, Nortal AS 07.04.2015.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
Advertisements

Web Development with Karsten Schulz Terp-Nielsen Master Principal Sales Consultant Oracle Denmark.
Apache Struts Technology
INTRODUCTION TO ASP.NET MVC AND EXAMPLE WALKTHROUGH RAJAT ARYA EFECS - OIM DAWG – 4/21/2009 ASP.NET MVC.
 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
Spring, Hibernate and Web Services 13 th September 2014.
Margus Hanni, Nortal AS Spring MVC Viited varasematele materjalidele… 2012 – TÜ - Spring MVC – Roman Tekhov.
28/1/2001 Seminar in Databases in the Internet Environment Introduction to J ava S erver P ages technology by Naomi Chen.
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
Apache Struts Technology A MVC Framework for Java Web Applications.
Chapter 10 Servlets and Java Server Pages. A servlet is a Java class designed to be run in the context of a special servlet container An instance of the.
Struts 2.0 an Overview ( )
UNIT-V The MVC architecture and Struts Framework.
Lecture 2 - Struts ENTERPRISE JAVA. 2 Contents  Servlet Deployment  Servlet Filters  Model View Controllers  Struts  Dependency Injection.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
Netbeans – jsp.zip Introduction to JSP Netbeans – jsp.zip.
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
Spring Overview, Application demo -Midhila Paineni 09/23/2011 Spring Overview, Application demo9/8/20151.
Separation of Concerns Technion – Institute of Technology Author: Gal Lalouche - Technion 2015 © 1.
Design Patterns Phil Smith 28 th November Design Patterns There are many ways to produce content via Servlets and JSPs Understanding the good, the.
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
JSP Architecture Outline  Model 1 Architecture  Model 2 Architecture.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
Chapter 8 Script-free pages. Problem with scripting in JSP When you use scripting (declaration, scriplet, expressions) in your JSP, you actually put Java.
Anti Orgla, Nortal AS Spring Framework
1 Dr Alexiei Dingli Web Science Stream Introducing Rails.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
JSF Introduction Copyright © Liferay, Inc. All Rights Reserved. No material may be reproduced electronically or in print without written permission.
® IBM Software Group © 2007 IBM Corporation JSP Expression Language
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Lecturer: Prof. Piero Fraternali, Teaching Assistant: Alessandro Bozzon, Advanced Web Technologies: Struts–
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
Fall CIS 764 Database Systems Design L8. Web ….
SE-2840 Dr. Mark L. Hornick 1 Java Server Pages. HTML/JSPs are intended to be used as the views in an MVC- based web application Model – represents an.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Forms with Spring MVC Handling Form.
JSF Framework Java Server Faces Presented by Songkran Totiya (6/10/2014)
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
Introduction to Spring Web Flow Andrew Petro Software Developer Unicon, Inc. Jasig 2011 Westminster, CO 23 May 2011 © Copyright Unicon, Inc., Some.
CSC 2720 Building Web Applications Frameworks for Building Web Applications.
CS-4220 Dr. Mark L. Hornick 1 Java Server Pages. HTML/JSPs are intended to be used as the views in an MVC- based web application Model – represents an.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Views Rendering custom views.
Chapter 11 Invoking Java Code with JSP Scripting Elements.
INTEGRATION OF BACKBONE.JS WITH SPRING 3.1. Agenda New Features and Enhancements in Spring 3.1 What is Backbone.js and why I should use it Spring 3.1.
JSP Pages. What and Why of JSP? JSP = Java code imbedded in HTML or XML –Static portion of the page is HTML –Dynamic portion is Java Easy way to develop.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Essentials Getting started.
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
Preface IIntroduction Objectives I-2 Course Overview I-3 1Oracle Application Development Framework Objectives 1-2 J2EE Platform 1-3 Benefits of the J2EE.
RESTful Web Services What is RESTful?
MVC WITH CODEIGNITER Presented By Bhanu Priya.
1 Copyright © 2004, Oracle. All rights reserved. Oracle Application Development Framework.
Implementation Struts Framework for well-architectured web applications Model-View-Controller design pattern.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Overview of the Spring Framework Introducing.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Java Server Pages. 2 Servlets The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
APACHE STRUTS ASHISH SINGH TOMAR ast2124. OUTLINE Introduction The Model-View-Controller Design Pattern Struts’ implementation of the MVC Pattern Additional.
Singleton Academy, Pune. Course syllabus Singleton Academy Pune – Course Syllabus1.
By Jonathan Smith. Road Map Introduction Company Information Project Overview Java Web Design and Development Summary Relation to IUP Acknowledgments.
Apache Struts Technology A MVC Framework for Java Web Applications.
CS520 Web Programming Spring – Web MVC Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Spring – Web MVC Chengyu Sun California State University, Los Angeles.
J2EE Platform Overview (Application Architecture)
J2EE Lecture 7: Spring – Spring MVC
CS5220 Advanced Topics in Web Programming Spring – Web MVC
The Model Layer What is Model?
CS5220 Advanced Topics in Web Programming Spring – Web MVC
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Spring MVC Margus Hanni, Nortal AS 07.04.2015

Millest räägime Framework Spring Spring MVC IoC - Inversion of Control AngularJS

What is a Web Framework? A web framework is a software framework designed to simplify your web development life. Frameworks exist to save you from having to re-invent the wheel and help alleviate some of the overhead when you’re building a new site.

What is a Web Framework? Typically frameworks provide libraries for accessing a database, managing sessions and cookies, creating templates to display your HTML and in general, promote the reuse of code.

Spring Framework Open source application framework. Inversion of Control container (IoC). Lots of utility API-s.

Should I bother? Spring framework is still extremely popular in Java (web) applications. If you’re going to build web applications in Java then chances are that you will meet Spring.

Inversion of control (IoC) Inversion of control is used to increase modularity of the program and make it extensible.

IoC in Spring 1 @Service 2 public class UserService { 3 4 @Autowired 5 6 7 8 9 10 11 12 13 14 @Service public class UserService { @Autowired private UserDao userDao; public User getByUserName(String name) { User user = userDao.getByUserName(name); // additional actions return user; }

IoC in Spring Declare bean, Spring will create it 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Declare bean, Spring will create it @Service public class UserService { @Autowired private UserDao userDao; public User getByUserName(String name) { User user = userDao.getByUserName(name); // additional actions return user; } Declare dependencies, Spring will inject them Küsimus: Rida 5, kust tuleb implementatsioon?

Dependency injection Your code depends on abstractions, Spring handles actual implementations. You can switch implementations easily.

Dependency injection 1 public interface UserDao { 2 3 4 5 6 7 8 9 10 11 12 13 14 public interface UserDao { User getByUserName(String name); } @Repository public class JdbcUserDao implements UserDao { public User getByUserName(String name) { // load user from DB @Autowired private UserDao userDao; Küsimus: Miks kasutada liidest?

Dependency injection Universal abstraction 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public interface UserDao { User getByUserName(String name); } @Repository public class JdbcUserDao implements UserDao { public User getByUserName(String name) { // load user from DB @Autowired private UserDao userDao; Universal abstraction One possible implementation. Spring will create and register it Spring can inject as an abstraction type

How to get a String from DB? Küsimus: Kas sellisel kujul on mõistlik pärida?

How to get a String from DB?

IoC in Spring Spring handles the infrastructure bean creation, dependency lookup and injection Developer focuses on application specific logic

XML based configuration Bean can also be defined and injected in XML. <bean id="userDao" class="example.JdbcUserDao" /> <bean id="userService" class="example.UserService"> <property name="userDao" ref="userDao" /> </bean>

What is MVC? http://java.sun.com/blueprints/patterns/MVC-detailed.html

Model-View-Controller Model - Model represents an object or JAVA POJO carrying data View - View represents the visualization of the data that model contains Controller - Controller acts on both model and view: It controls the data flow into model object Executes business logic, data actions etc. It keeps view and model separate Küsimus: Miks selline kihilisus hea on?

Model-View-Controller Separation of different layers An application might have more than one user interface Different developers may be responsible for different aspects of the application

Spring MVC Spring based web framework. Request-driven. Designed around a central Servlet. Implements the Model-View-Controller design pattern. Very flexible (we’ll see how exactly).

Spring MVC IoC again – framework handles the infrastructure, you focus on application specific things.

Architecture - DispatcherServlet http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html

DispatcherServlet Is completely integrated with the Spring IoC container and as such allows to use every other feature that Spring has.

Controller 1 @Controller 2 public class HelloController { 3 4 5 6 7 8 9 10 11 12 13 14 @Controller public class HelloController { @Resource private UserService userService; @RequestMapping("/hello") public String hello(Model model) { User user = userService.getByUserName("Cartman"); model.addAttribute("user", user); return "hello"; } Küsimus: Mis on päringuvastuseks?

Controller Declare controller Inject Spring resources 1 2 3 4 5 6 7 8 9 10 11 12 13 14 @Controller public class HelloController { @Autowired private UserService userService; @RequestMapping("/hello") public String hello(Model model) { User user = userService.getByUserName("Cartman"); model.addAttribute("user", user); return "hello"; } Inject Spring resources What requests to serve? Method for handling requests

Controller Logical view name 1 @Controller 2 3 4 5 6 7 8 9 10 11 12 13 14 @Controller public class HelloController { @Resource private UserService userService; @RequestMapping("/hello") public String hello(Model model) { User user = userService.getByUserName("Cartman"); model.addAttribute("user", user); return "hello"; } Logical view name

Model Set of attributes that Controller collects and passes to the View.

Model Spring’s Model object… @RequestMapping(value="/hello") public String hello(Model model) { User user = userService.getByUserName(“cartman"); model.addAttribute("user", user); ...

Model Or plain java.util.Map @RequestMapping(value="/hello") public String hello(Map<String, Object> model) { User user = userService.getByUserName("cartman"); model.put("user", user); ...

Model Or plain java.util.Map @RequestMapping(value="/hello") public String hello(Map<String, Object> model) { User user = userService.getByUserName("cartman"); model.put("user", user); ...

View Any representation of output, invoked after the Controller, uses data from the Model to render itself.

View technologies Usually Java Server Pages that generate HTML. Out-of-the-box there are also PDF, XML, JSON, Excel and other views. You can create your own.

View Controller is totally decoupled from actual view technology. @RequestMapping("/hello") public String hello() { ... return "hello"; } Just a logical view name to be invoked

JSP view "hello” /WEB-INF/jsp/hello.jsp <bean class="org.springframework...InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> "hello” /WEB-INF/jsp/hello.jsp

JSP view (hello.jsp) Model attributes are accessible as EL (Expression Language) variables in JSP. JSP: <p>Hello, ${user.fullName}!</p> HTML: <p>Hello, Eric Cartman!</p>

JSON view JSON view transforms the whole model to JSON format. <bean class="org.springframework...ContentNegotiatingViewResolver"> <property name="defaultViews"> <list> <bean class="org.springframework...MappingJacksonJsonView" /> </list> </property> </bean>

JSON view {"user":{"fullName":"Eric Cartman"}} Outputs the Model as JSON document. {"user":{"fullName":"Eric Cartman"}}

Request mapping @RequestMapping("/hello") @RequestMapping(value="/hello", method=RequestMethod.GET) @RequestMapping(value="/hello", params= {"param1", "param2"}) @RequestMapping(value="/hello", consumes="application/json", produces="application/json")

Path variables http://[SERVER]/hello/cartman @RequestMapping(value="/hello/{username}") public String hello( @PathVariable String username, Model model) { ... http://[SERVER]/hello/cartman

Request parameters http://[SERVER]/hello?username=cartman @RequestMapping(value="/hello") public String hello( @RequestParam("username") String username, Model model) { ... http://[SERVER]/hello?username=cartman

Type conversion HttpServletRequest parameters, headers, paths etc are all Strings. Spring MVC allows you to convert to and from Strings automatically.

Built-in conversion There are some standard built-in converters. @RequestMapping("/foo") public String foo( @RequestParam("param1") int intParam, @RequestParam("param2") long longParam) { ...

Type conversion You can also define your own PropertyEditors PropertyEditorSupport implements PropertyEditor

Custom types 1 public class DateRange { 2 3 private Date start; 4 5 6 7 8 9 10 11 12 13 14 public class DateRange { private Date start; private Date end; public DateRange(Date start, Date end) { this.start = start; this.end = end; } public int getDayDifference() { // calculate

Custom type editor String to custom type Custom type to String 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public class DateRangeEditor extends PropertyEditorSupport { private DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy"); public void setAsText(String text) throws IllegalArgumentException { String[] parts = text.split("-"); Date start = dateFormat.parse(parts[0]); Date end = dateFormat.parse(parts[1]); setValue(new DateRange(start, end)); } public String getAsText() { DateRange dateRange = (DateRange) getValue(); return dateFormat.format(dateRange.getStart()) + "-" + dateFormat.format(dateRange.getEnd()); String to custom type Custom type to String

Register and use 1 @Controller 2 public class MyController { 3 4 5 6 7 8 9 10 11 12 13 14 @Controller public class MyController { @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(DateRange.class, new DateRangeEditor()); } @RequestMapping(value="/dateRange") public String dateRange(@RequestParam("range") DateRange range) { ...

Method parameters It all about IoC and Convention Over Configuration. Your code simply declares what it needs from the environment, Spring makes it happen. The order is not important, the type is.

Method parameters Model/Map – model @RequestParam/@PathVariable annotated HttpServletRequest, HttpServletResponse, HttpSession – it is all based on Servlet API!

Method parameters java.io.Writer / java.io.OutputStream – if you want to generate response directly in controller …

Method parameters For example @RequestMapping(value="/hello") public String hello(Model model, Writer writer, HttpServletRequest request, HttpSession session) { ... 1 2 3 4 5

Return values Same principle – you return what Spring awaits from you.

Return value examples String – logical view name. void … If you write the response in controller If you use default/content negotiating views (like JSON earlier) …

Non-intrusive Very important feature of a framework is non-intrusiveness. Spring MVC normally lets you do stuff according to MVC pattern. But it doesn’t prevent you from violating MVC if you really want to.

No view examples @RequestMapping(value="/noView") @ResponseBody public String noView() { return "Too simple for a view"; } public void noView(Writer writer) { writer.write("Too simple for a view"); Küsimus: Miks siin ei rakendu view loogika?

Form First you need to give Spring a new command object @RequestMapping(value="/addUser") public String add(Model model) { model.addAttribute("user", new User()); return "add"; }

Command object public class User { private String fullName; private int age; // getters/setters ...

Form JSP <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <form:form commandName="user"> <form:input path="fullName" /> ... <form:input path="age" /> <input type="submit" value="Add" /> </form:form>

Form Spring will bind the data to our command object @RequestMapping(value="/addUser", method=RequestMethod.POST) public String save(User user) { // save user return "home"; }

Validation JSR-303 defines constraint annotations: public class User { @NotNull @Size(max=20) private String fullName; @Min(10) private int age; ...

Validation Check for validation errors. 1 2 3 4 5 6 7 8 9 10 11 12 @RequestMapping(value="/addUser", method=RequestMethod.POST) public String save(@Valid User user, BindingResult result, Model model) { if (result.hasErrors()) { model.addAttribute("user", user); return "add"; } // save user return "home"; Check for validation errors. Render the same view in case of errors

Validation Show validation errors <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <form:form commandName="user"> <form:input path="fullName" /> <form:errors path="fullName" /> ... <form:input path="age" /> <form:errors path="age" /> <input type="submit" value="Add" /> </form:form> Show validation errors

Validation It is of course possible to define your own constraints and validators.

AngularJS ja Spring MVC Mis kaob ning asendatakse? Mis rolli mängib Spring MVC? Kuhu nihkub arendus? FE  BE

RESTful REST - Representational State Transfer RESTful systems is a software architecture style consisting of guidelines and best practices for creating scalable web services RESTful systems communicate over the Hypertext Transfer Protocol with HTTP verbs (GET, POST, PUT, DELETE, etc.)

Mis muutub Kontroller nihkub REST teenused Stateless http://blog.jhades.org/developing-a-modern-java-8-web-app-with-spring-mvc-and-angularjs/

Mida tuleb arvestada Autentimine Autoriseerimine Kontrollid Küsimus: Kuidas lahendada autentimine? Kuidas lahendada autoriseerimine? Kes mida näeb! Miks kontrollid on eraldi välja toodud?

Spring MVC + AngularJS või JSP „Üks eelistab ema, teine aga tütart!“ Konventsioonid Tagasiühilduvus … Mõttemaailma muutus Tehnoloogiate ja vahendite rohkus Single-page application Erinevad kihid Data Transfer Object (DTO)

Sources of wisdom Spring has great documentation: http://www.springsource.org/spring-framework#documentation Java BluePrints - Model-View-Controller http://www.oracle.com/technetwork/java/mvc-detailed-136062.html Model-View-Controller http://www.oracle.com/technetwork/java/mvc-140477.html Inversion of control http://en.wikipedia.org/wiki/Inversion_of_control Design Patterns - MVC Pattern http://www.tutorialspoint.com/design_pattern/mvc_pattern.htm Web App Architecture - the Spring MVC - AngularJs stack http://blog.jhades.org/developing-a-modern-java-8-web-app-with-spring-mvc-and-angularjs/