420 likes | 847 Views
Spring Framework. Anti Orgla, Nortal AS. 08.04.2014. Web appication framework ? . How do you handle your requests ? How do you access your database ? How do you manage your session ? Code reuse ? Maybe it’s already been done ?. Web application f ramework.
E N D
SpringFramework Anti Orgla, Nortal AS 08.04.2014
Webappicationframework? • Howdoyouhandleyourrequests? • Howdoyouaccessyourdatabase? • Howdoyou manage yoursession? • Codereuse? • Maybeit’salreadybeendone?
Web application framework • Typically frameworks provide libraries: • Database Access • Sessionmanagement • Requestmanagement • Transactionmanagement • UI Templates • Cache, Security, Ajax, WebServices, etc…
Howtoget a String from DB? public static String getName(Connectioncon, int id){ Statement stmt = null; String query = "selectnamefrom user_infowhere id = ?"; try { stmt = con.createStatement(); stmt.setInt(1, id); ResultSetrs = stmt.executeQuery(query); if(rs.next()) { returnrs.getString("name"); }else{ return null; } } catch (SQLException e ) { //handletheexception } finally { if (stmt != null) { stmt.close(); } } }
Easierway? public static String getName(int id){ return jdbcTemplate.queryForObject("select namefrom user_info where id = ?",String.class, id); }
Spring Framework • One of themostpopular • Open source application framework • Veryflexible • Availablesince 2002 (v4.0 dets.2013) • Did I sayitisveryflexible?
SpringFramework • Inversion of Control • DependencyInjection • staticvs runtime • abstractions vs implementations
Dependency injection publicinterfaceUserDao { UsergetByUserName(Stringname); } @Repository publicclassJdbcUserDaoimplementsUserDao { publicUsergetByUserName(Stringname) { // load userfrom DB } } @Resource privateUserDaouserDao; Universal abstraction
Dependency injection publicinterfaceUserDao { UsergetByUserName(Stringname); } @Repository publicclassJdbcUserDaoimplementsUserDao { publicUsergetByUserName(Stringname) { // load userfrom DB } } @Resource privateUserDaouserDao; One possible implementation. Spring will create and register it
Dependency injection publicinterfaceUserDao { UsergetByUserName(Stringname); } @Repository publicclassJdbcUserDaoimplementsUserDao { publicUsergetByUserName(Stringname) { // load userfrom DB } } @Resource privateUserDaouserDao; Injectionis made asanabstraction
IoC in Spring • Spring handles the infrastructure • (bean creation, dependency lookup and injection) • Developerfocuses on application specific logic • Youcandescribehowyourapplicationiscoupled, notcoupleityourself!
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>
MVC – Whatwasthat? http://java.sun.com/blueprints/patterns/MVC-detailed.html
Model-View-Controller • Controller: executesbusinesslogic, dataactionsetc. Forms a modelobject and passes ittoviewforrendering • Model: objectforpassingdatabetweencontroller and view • View: takesmodeldatafromthecontroller and presentsittothe end user
Model-View-Controller • Separation of differentlayers • An application might have more than one user interface • Different developersmay be responsible for different aspects of the application.
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
Let’swritesome MVC! Code demo..
Built-in conversion • There are some standard built-in converters. @RequestMapping("/foo") public String foo( @RequestParam("param1")intintParam, @RequestParam("param2")long longParam) { ...
Type conversion • You can also define your own PropertyEditors • PropertyEditorSupportimplementsPropertyEditor
Custom types publicclassDateRange { privateDatestart; privateDateend; publicDateRange(Date start, Date end) { this.start = start; this.end = end; } publicintgetDayDifference() { // calculate } }
Custom type editor publicclassDateRangeEditorextendsPropertyEditorSupport { privateDateFormatdateFormat = newSimpleDateFormat("dd.MM.yyyy"); publicvoidsetAsText(String text) throwsIllegalArgumentException { String[] parts = text.split("-"); Date start = dateFormat.parse(parts[0]); Date end = dateFormat.parse(parts[1]); setValue(newDateRange(start, end)); } public String getAsText() { DateRangedateRange = (DateRange) getValue(); returndateFormat.format(dateRange.getStart()) + "-" + dateFormat.format(dateRange.getEnd()); } } String to custom type Custom type to String
Register and use @Controller publicclassMyController { @InitBinder publicvoidinitBinder(WebDataBinderbinder) { binder.registerCustomEditor(DateRange.class, newDateRangeEditor()); } @RequestMapping(value="/dateRange") public String dateRange(@RequestParam("range") DateRange range) { ... } }
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.
Codeexamples.. Code demo..
Sources of wisdom • Spring has great documentation: http://www.springsource.org/spring-framework#documentation • Java BluePrints - Model-View-Controllerhttp://www.oracle.com/technetwork/java/mvc-detailed-136062.html • Model-View-Controllerhttp://www.oracle.com/technetwork/java/mvc-140477.html • Inversion of controlhttp://en.wikipedia.org/wiki/Inversion_of_control