Project Configuration

Introduction
  1. We will use Spring Tool Suit(STS) IDE based on eclipse
  2. Eclipse version retrofitted with spring tooling
  3. Download from http://spring.io/tools
  4. Has 3 parts
    1. Legal
    2. Pivotal TC server
      1. Tomcat server customized with different tools to support deployment of Spring and other pivotal products.
    3. STS
      1. Has the IDE
      2. We can start by clicking on Application launcher
      3. Select a workspace
      4. You will get a dashboard when tool opens up.
      5. Biggest benefit already has a pivotal server so no need to attach a separate server as in case of eclipse.
Configuration
  1. Disable dashboard
    1. Window=>preferences
    2. search for "dashboard"
    3. uncheck news and feed updates
  2. Disable updates
    1. Window=>preferences
    2. search for "updates"
    3. click "Automatic updates"
      1. uncheck automatically find new updates and notify me.
  3. Disable unnecessary Validators
    1. Window=>preferences
    2. Search "validation"
    3. Select Spring=>"validation"
    4. Disable web flow validator
  4. Export your Settings
    1. File=>Export=>General=>preferences
    2. Select export all and export to a file
    3. In future you can import your preferences at one go in case of fresh installation
  5. Select your web browser instead of internal web browser
    1. Window=>web browser=>Firefox/Chrome/Safari
    2. So STS will open application by default in your favorite browser.
  6. Close unnecessary views
    1. Outline view
    2. Spring Explorer
  7. Open project explorer view.
  8. Set package presentation to hierarchical.
Creating a Spring MVC project
  1. File=>New=>Spring Legacy Project
  2. Provide project Name
  3. Select Template
    1. A template is a preconfigured project.
    2. We will use a preconfigured spring MVC project so select the same
    3. Click Next
  4. Specify a top level package
    1. Will contain all of our classes.
    2. Enter com.springimplant.mvc
    3. Click Finish.
  5. STS starts building our project.
    1. The project may show some warnings initially but they will go away once it has finished building.
    2. Once the warnings have gone away then our project is fully built.
    3. If you encounter any issues during building project 
      1. Check that your maven is successfully setup.
      2. There are no proxy issues.
      3. Try building dependencies from console
        1. Open console CMD/Bash prompt.
        2. Go to the project folder.
        3. Execute
          1. mvn clean dependency:copy-dependencies package
      4. Once the warnings have gone away then our project is fully built.
    4. A maven project has been created
      1. Project has a pom.xml file.
        1. It has all the dependencies needed to run a spring MVC application.
        2. All jar files needed are on the classpath.
        3. We are using here Maven standard directory layout where
          1. Source code is present in ${basedir}/src/main/java
          2. Resources are present in ${basedir}/src/main/resources
          3. Tests are present in ${basedir}/src/test
          4. Complied byte code is present in ${basedir}/target
          5. Distributable JAR is present in ${basedir}/target/classes
          6. All the web files are stored in src/main/webapp directory.
            1. In WEB-INF directory we will find spring configuration files.
            2. These determine the behavior of spring mvc framework.
          7. To start application right click on application name
            1. Select run as 
            2. Select Run on server
            3. Click Finish.
Serving a Web Request
  1. Web.xml
    1. It has a servlet called as the dispatcher servlet.
      1. This points our server to the Spring.
    2. We modify in order to configure our Application server.
    3. We specify redirection to our Dispatcher Servlet
    4. We load Dispatcher Servlet on startup.
    5. Be sure to add Maven Dependencies to class path i.e. push them along Tomcat Server Dependencies so that they both can work along.
      1. We need to add these manually to our class path
     <?xml version="1.0" encoding="UTF-8"?>  
     <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"  
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
          <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->  
          <context-param>  
               <param-name>contextConfigLocation</param-name>  
               <param-value>/WEB-INF/spring/root-context.xml</param-value>  
          </context-param>  
          <!-- Creates the Spring Container shared by all Servlets and Filters -->  
          <listener>  
               <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
          </listener>  
          <!-- Processes application requests -->  
          <servlet>  
               <servlet-name>appServlet</servlet-name>  
               <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
               <init-param>  
                    <param-name>contextConfigLocation</param-name>  
                    <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>  
               </init-param>  
               <load-on-startup>1</load-on-startup>  
          </servlet>  
          <servlet-mapping>  
               <servlet-name>appServlet</servlet-name>  
               <url-pattern>/</url-pattern>  
          </servlet-mapping>  
     </web-app>  
  2. Dispatcher Servlet
    1. Dispatcher servlet serves as our front controller.
    2. Responsible for accepting requests and returning responses.
    3. Takes care of finding the controller based on url.
    4. Looks for a configuration file with name as /WEB-INF/{Name Of Dispatcher Servlet}-servlet.xml.
      1. The name of the dispatcher servlet is defined in web.xml
      2. This configuration of dispatcher servlet defines its behavior.
      3. This is also use to configure our Spring Application.
    5.  We can also define a file at our custom location, see this file is defined in init parameter in "web.xml" file.
      1. "<init-param>" tag.
    6. This file can be named to taste but servlet-context.xml is a standard.
    7. When Spring instantiates the dispatcher servlet it loads this configuration file.
    8. This also has a root-context.xml file.
    9. This is loaded by a context loader listener.
    10. When the application initializes we are going to load another context besides web-application context loaded by the dispatcher servlet.
 <?xml version="1.0" encoding="UTF-8"?>  
 <beans xmlns="http://www.springframework.org/schema/beans"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xmlns:context="http://www.springframework.org/schema/context"  
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">  
      <context:component-scan base-package="com.springimplant.complaint_manager"/>  
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
           <property name="prefix" value="/WEB-INF/views/"></property>  
           <property name="suffix" value=".jsp"></property>  
      </bean>  
 </beans>  
  1. root-context.xml
    1. The application context defined in root-context.xml file is going to define things like other spring beans that we need to perform our logic.
      1. Eg JPA repository stored in there.
      2. Security Configuration etc.
     <?xml version="1.0" encoding="UTF-8"?>  
     <beans xmlns="http://www.springframework.org/schema/beans"  
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
          xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">  
          <!-- Root Context: defines shared resources visible to all other web components -->  
     </beans>  
    
  2. servlet-context.xml
    1. Spring consults many other xml files when it loads Dispatcher servlet to determine its behavior.
    2. All these xml files are defined in this file.
    3. These xml files define how our Spring Application will be configured.
      1. For example we have configured our view resolver in below code.
      2. Also we have defined our base package where the spring should look for various components like entities,controllers etc.
 <?xml version="1.0" encoding="UTF-8"?>  
 <beans:beans xmlns="http://www.springframework.org/schema/mvc"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xmlns:beans="http://www.springframework.org/schema/beans"  
      xmlns:context="http://www.springframework.org/schema/context"  
      xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd  
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">  
      <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->  
      <!-- Enables the Spring MVC @Controller programming model -->  
      <annotation-driven />  
      <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->  
      <resources mapping="/resources/**" location="/resources/" />  
      <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->  
      <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
           <beans:property name="prefix" value="/WEB-INF/views/" />  
           <beans:property name="suffix" value=".jsp" />  
      </beans:bean>  
      <context:component-scan base-package="com.springimplant.mvc" />  
 </beans:beans>  

Request
  1. Once the dispatcher servlet has started up it waits to process request.
  2. When we hit our browser and we send a request to server.
  3. The dispatcher servlet looks at the url.
  4. It locates the controller that can handle the url.
    1. The controllers are mapped in servlet-context.xml
    2. A strategy is defined to map to them.
Home Controller
  1. Responsible for servicing all requests to our context root.
  2. The controller class is always annotated with a controller.
    1. @Controller
  3. A mapping is defined for requests for example a mapping is defined for root as 
    1. @RequestMapping(value="/",method=RequestMethod.GET)
  4. The @Controller annotation above a class signals the spring that this class is responsible for processing request.
  5. A Request Mapping annotation with ("/") signals processing request for a context-root.
  6. Going through the function name we see
    1. We are logging information.
    2. Then we have created a new Date class object.
    3. Then we have formatted date.
  7. The formatted date variable is added as attribute to our model as "servertime".
    1. Model is defined as an argument to our method.
    2. Model.addAttribute("servertime",formattedDate); is the syntax for the same.
  8. Model acts as a map so model stores data as name and value pairs.
  9. Model is passed to a view.
  10. The function returns a String "home".This is mapped to "home.jsp" file.
    1. This configuration is provided in "servlet-context.xml" file as follows.
      1. <beans : bean class="org.springframework.web.servlet.view.InternalResourceViewResolver>
      2. <beans:property name="prefix" value="/Web-INF/views" />
      3. <beans:property name="suffix" value=".jsp">
      4. </beans:bean>
    2. So it takes the string "name" "prefix"it with value "/web-INF/views" and suffix it with ".jsp".
    3. The string becomes "/Web-INF/views/home.jsp"
    4. This is the view we are going to display and we will have the file in location.
    5. The ".jsp" references to the variable attribute that we stored in our model.
    6. This jsp is rendered as our response to be displayed on browser.
Configuring Database
 jdbc.driverCLassName=com.mysql.jdbc.driver  
 jdbc.url=jdbc:mysql://localhost:3306/complaintsystem  
 jdbc.user=root  
 jdbc.pass=  
 hibernate.dialect=org.hibernate.dialect.MySQL5Dialect  
 hibernate.show_sql=true  
 hibernate.hdm2ddl.auto=update  

Configure Spring MVC
 <pre style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;background-image:URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh701XvsbM19FRwNNtPi5gZyi8hKkte01KuXDIveHJYXQBbAPPl0GIYsW8vdmUiLNHvUuywwF2IIUpNcTiihj6pqXrafmHh1Rq6qKa5fysCa4doyWiSMz1WCDRT-aVw2OLsckQ2DAKZbiHC/s320/codebg.gif);padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;"> package com.springimplant.complaint_manager;   
  import java.util.Properties;   
  import javax.sql.DataSource;   
  import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;   
  import org.hibernate.SessionFactory;   
  import org.springframework.beans.factory.annotation.Autowired;   
  import org.springframework.context.annotation.Bean;   
  import org.springframework.context.annotation.ComponentScan;   
  import org.springframework.context.annotation.Configuration;   
  import org.springframework.context.annotation.PropertySource;   
  import org.springframework.core.env.Environment;   
  import org.springframework.orm.hibernate5.HibernateTransactionManager;   
  import org.springframework.orm.hibernate5.LocalSessionFactoryBean;   
  import org.springframework.transaction.annotation.EnableTransactionManagement;   
  @Configuration   
  @EnableTransactionManagement   
  @PropertySource({"classpath:database-properties.properties"})   
  @ComponentScan({"com.springimplant.complaint_manager"})   
  public class PersistanceConfig {   
    @Autowired   
    private Environment env;   
    @Bean   
    public DataSource dataSource()   
    {   
       BasicDataSource dataSource=new BasicDataSource();   
       dataSource.setDriverClassName(env.getProperty("jdbc.driverCLassName"));   
       dataSource.setUrl(env.getProperty("jdbc.url"));   
       dataSource.setUsername(env.getProperty("jdbc.user"));   
       dataSource.setPassword(env.getProperty("jdbc.pass"));   
       return dataSource;   
    }   
    @Bean   
    @Autowired   
    public HibernateTransactionManager TransactionManager(SessionFactory sessionFactory)   
    {   
       HibernateTransactionManager transacManager=new HibernateTransactionManager();   
       transacManager.setSessionFactory(sessionFactory);   
       return transacManager;   
    }   
    @Bean   
    LocalSessionFactoryBean sessionFactory()   
    {   
       LocalSessionFactoryBean sessionFactory=new LocalSessionFactoryBean();   
       sessionFactory.setDataSource(dataSource());   
       sessionFactory.setPackagesToScan(new String[] {"com.springimplant.complaint_manager.entities"});   
       sessionFactory.setHibernateProperties(hibernateConfig());   
       return sessionFactory;   
    }   
    Properties hibernateConfig()   
    {   
       Properties configProp=new Properties();   
       configProp.setProperty("hibernate.hdm2ddl.auto",env.getProperty("hibernate.hdm2ddl.auto"));   
       configProp.setProperty("hibernate.dialect",env.getProperty("hibernate.dialect"));   
       configProp.setProperty("hibernate.show_sql",env.getProperty("hibernate.show_sql"));   
       return configProp;   
    }   
  }   
 </code></pre>  
  • Configuration File Annotations
    • @Configuration
      • Tells Spring MVC that this is a configuration file and needs to be read for configuration.
    • @EnableTransactionManagement
      • Tells Spring that we will be just enabling transaction management.
      • Spring manages transactions for each DB insert/update operation
    • @PropertySource({"classpath:dbpropertiesfile"})
      • classpath looks in java resources
      • tells Spring where to load properties file from
    • @ComponentScan({"basepackage"})
      • Package to scan for components
  • Configuration File Data Members
    • Envirnoment
      • refers to the properties file defined in PropertySource

sdfd

No comments:

Post a Comment

Spring Boot

What is circular/cyclic dependency in spring boot? When two services are interdependent on each other, that is to start one service, we requ...