Annotation based Spring web https://github.com /Innominds-jee /spring-web-training.git
Index  Spring Java based configuration  Traditional Java web application  Servlet 3.0 based structure  Customizing web app with Spring Adapters  Securing your web pages  Creating simple REST API  Exception handling
Traditional Web application -myApp |static/ *.css, *.js |-WEB-INF |classes/ *.class |lib/*.jar |-web.xml
Configuring web.xml prior to servlet 3.0 <web-app id="WebApp_ID" version="2.4”> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
How Servlet 3.0 container works (tomcat 7 +)  In a Servlet 3.0 environment, the container looks for any classes in the class path that implement the javax.servlet.ServletContainerInitializer interface; if any are found, they’re used to configure the servlet container.  Spring supplies an implementation of that interface called SpringServletContainerInitializer that, in turn, seeks out any classes that implement WebApplicationInitializer and delegates to them for configuration.  Spring 3.2 introduced a convenient base implementation of WebApplicationInitializer called AbstractAnnotationConfigDispatcherServletInitializer
 AbstractAnnotationConfigDispatcherServletInitializer creates both a DispatcherServlet and a ContextLoaderListener.  The @Configuration classes returned from getServletConfigClasses() will define beans for DispatcherServlet’s application context.  equals to dispatcher-servlet.xml  The @Configuration class’s returned getRootConfigClasses() will be used to configure the application context created by ContextLoaderListener  equals to applicationContext.xml  getServletMappings() will provde URL Mappings for dispatcherServlet. equals to <url-pattern>/</url-pattern>
Adapters Spring comes with different adapters to custom spring web application rendering It allows us to customize …..  View Resolvers  CORS filters  Exception resolvers  Static Resource configuration  Message converters  Locale configuration  Enabling security to the web URLs or methods  And more….
Customizing web Web customization can achieved by writing a class and annotate with @EnableWebMvc And Extend this class with WebMvcConfigurerAdapter With this annotation container will look for a class in the class path which implements WebMvcConfigurer or extends WebMvcConfigurerAdapter to load the customized settings for web application.
CORS Mapping  Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the resource originated @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/cors/**"); }
Resource Handlers  resource handlers for serving static resources such as images, CSS files and others through Spring MVC including setting cache headers optimized for efficient loading in a web browser. Resources can be served out of locations under web application root, from the class path, and others. @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**"). addResourceLocations("classpath:/static/"); }
Writing simple REST service Writing REST Service is simple with below steps…  Annotate your controller with @RestController This is equals to @Controller +@ResponseBody  Make sure appropriate message converters available in the class path. Spring will automatically creates message converters for you.  Return required DTO Objects from the class methods
Enabling Spring Security  Write a class and annotate with @EnableWebSecurity and extend that class with WebSecurityConfigurerAdapter This annotation looks for a instance of class WebSecurityConfigurer to read the security settings  Override configure(HttpSecurity http) method http.authorizeRequests().anyRequest().authenticated().and().for mLogin().and().httpBasic();  Configure Security filter proxy in the WEBXMLConfig file  Add authenticationProvider or inMemoryManager by overriding configure(AuthenticationManagerBuilder auth) method.
Customizing spring security Following interfaces from spring security framework need to implement to customize spring security framework 1. UserDetails: contains username ,password and other account enable disable locking kind of properties. 2. GrantedAuthority: contains roles based we can grant access to the resources 3. UserDetailService: loads the user based on username and returns UserDetails object. 4. AuthenticationProvider: contains authenticate method to do check username and password against DB. If credentials are valid it has to return object of type UsernamePasswordAuthenticationToken which takes valid username , password, authorities
Exception handing Web exception can be handled by overriding method below method in WebMvcConfigurerAdapter @Override public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { super.configureHandlerExceptionResolvers(exceptionResolvers); exceptionResolvers.add(new CustomExceptionResolver()); }
Writing custom exception resolver public class CustomExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { final ModelAndView mv = new ModelAndView("exception"); mv.addObject("name", ex.getClass().getSimpleName()); mv.addObject("message", ex.getMessage()); mv.addObject("errorCode", response.getStatus()); return mv; } }
RESTful service exception handling  If you want exception message as JSON then write a class which extends ResponseEntityExceptionHandler and annotate that class with @ControllerAdvice.  Override methods available in above handler class @ControllerAdvice public class RESTExceptionHandler extends ResponseEntityExceptionHandler{ }

Spring WebApplication development

  • 1.
  • 2.
    Index  Spring Javabased configuration  Traditional Java web application  Servlet 3.0 based structure  Customizing web app with Spring Adapters  Securing your web pages  Creating simple REST API  Exception handling
  • 3.
    Traditional Web application -myApp |static/*.css, *.js |-WEB-INF |classes/ *.class |lib/*.jar |-web.xml
  • 4.
    Configuring web.xml priorto servlet 3.0 <web-app id="WebApp_ID" version="2.4”> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
  • 5.
    How Servlet 3.0container works (tomcat 7 +)  In a Servlet 3.0 environment, the container looks for any classes in the class path that implement the javax.servlet.ServletContainerInitializer interface; if any are found, they’re used to configure the servlet container.  Spring supplies an implementation of that interface called SpringServletContainerInitializer that, in turn, seeks out any classes that implement WebApplicationInitializer and delegates to them for configuration.  Spring 3.2 introduced a convenient base implementation of WebApplicationInitializer called AbstractAnnotationConfigDispatcherServletInitializer
  • 6.
     AbstractAnnotationConfigDispatcherServletInitializer creates botha DispatcherServlet and a ContextLoaderListener.  The @Configuration classes returned from getServletConfigClasses() will define beans for DispatcherServlet’s application context.  equals to dispatcher-servlet.xml  The @Configuration class’s returned getRootConfigClasses() will be used to configure the application context created by ContextLoaderListener  equals to applicationContext.xml  getServletMappings() will provde URL Mappings for dispatcherServlet. equals to <url-pattern>/</url-pattern>
  • 7.
    Adapters Spring comes withdifferent adapters to custom spring web application rendering It allows us to customize …..  View Resolvers  CORS filters  Exception resolvers  Static Resource configuration  Message converters  Locale configuration  Enabling security to the web URLs or methods  And more….
  • 8.
    Customizing web Web customizationcan achieved by writing a class and annotate with @EnableWebMvc And Extend this class with WebMvcConfigurerAdapter With this annotation container will look for a class in the class path which implements WebMvcConfigurer or extends WebMvcConfigurerAdapter to load the customized settings for web application.
  • 9.
    CORS Mapping  Cross-originresource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the resource originated @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/cors/**"); }
  • 10.
    Resource Handlers  resourcehandlers for serving static resources such as images, CSS files and others through Spring MVC including setting cache headers optimized for efficient loading in a web browser. Resources can be served out of locations under web application root, from the class path, and others. @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**"). addResourceLocations("classpath:/static/"); }
  • 11.
    Writing simple RESTservice Writing REST Service is simple with below steps…  Annotate your controller with @RestController This is equals to @Controller +@ResponseBody  Make sure appropriate message converters available in the class path. Spring will automatically creates message converters for you.  Return required DTO Objects from the class methods
  • 12.
    Enabling Spring Security Write a class and annotate with @EnableWebSecurity and extend that class with WebSecurityConfigurerAdapter This annotation looks for a instance of class WebSecurityConfigurer to read the security settings  Override configure(HttpSecurity http) method http.authorizeRequests().anyRequest().authenticated().and().for mLogin().and().httpBasic();  Configure Security filter proxy in the WEBXMLConfig file  Add authenticationProvider or inMemoryManager by overriding configure(AuthenticationManagerBuilder auth) method.
  • 13.
    Customizing spring security Followinginterfaces from spring security framework need to implement to customize spring security framework 1. UserDetails: contains username ,password and other account enable disable locking kind of properties. 2. GrantedAuthority: contains roles based we can grant access to the resources 3. UserDetailService: loads the user based on username and returns UserDetails object. 4. AuthenticationProvider: contains authenticate method to do check username and password against DB. If credentials are valid it has to return object of type UsernamePasswordAuthenticationToken which takes valid username , password, authorities
  • 14.
    Exception handing Web exceptioncan be handled by overriding method below method in WebMvcConfigurerAdapter @Override public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { super.configureHandlerExceptionResolvers(exceptionResolvers); exceptionResolvers.add(new CustomExceptionResolver()); }
  • 15.
    Writing custom exceptionresolver public class CustomExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { final ModelAndView mv = new ModelAndView("exception"); mv.addObject("name", ex.getClass().getSimpleName()); mv.addObject("message", ex.getMessage()); mv.addObject("errorCode", response.getStatus()); return mv; } }
  • 16.
    RESTful service exceptionhandling  If you want exception message as JSON then write a class which extends ResponseEntityExceptionHandler and annotate that class with @ControllerAdvice.  Override methods available in above handler class @ControllerAdvice public class RESTExceptionHandler extends ResponseEntityExceptionHandler{ }