Introduction
Request
- We will use Spring Tool Suit(STS) IDE based on eclipse
- Eclipse version retrofitted with spring tooling
- Download from http://spring.io/tools
- Has 3 parts
- Legal
- Pivotal TC server
- Tomcat server customized with different tools to support deployment of Spring and other pivotal products.
- STS
- Has the IDE
- We can start by clicking on Application launcher
- Select a workspace
- You will get a dashboard when tool opens up.
- Biggest benefit already has a pivotal server so no need to attach a separate server as in case of eclipse.
- Disable dashboard
- Window=>preferences
- search for "dashboard"
- uncheck news and feed updates
- Disable updates
- Window=>preferences
- search for "updates"
- click "Automatic updates"
- uncheck automatically find new updates and notify me.
- Disable unnecessary Validators
- Window=>preferences
- Search "validation"
- Select Spring=>"validation"
- Disable web flow validator
- Export your Settings
- File=>Export=>General=>preferences
- Select export all and export to a file
- In future you can import your preferences at one go in case of fresh installation
- Select your web browser instead of internal web browser
- Window=>web browser=>Firefox/Chrome/Safari
- So STS will open application by default in your favorite browser.
- Close unnecessary views
- Outline view
- Spring Explorer
- Open project explorer view.
- Set package presentation to hierarchical.
Creating a Spring MVC project
- File=>New=>Spring Legacy Project
- Provide project Name
- Select Template
- A template is a preconfigured project.
- We will use a preconfigured spring MVC project so select the same
- Click Next
- Specify a top level package
- Will contain all of our classes.
- Enter com.springimplant.mvc
- Click Finish.
- STS starts building our project.
- The project may show some warnings initially but they will go away once it has finished building.
- Once the warnings have gone away then our project is fully built.
- If you encounter any issues during building project
- Check that your maven is successfully setup.
- There are no proxy issues.
- Try building dependencies from console
- Open console CMD/Bash prompt.
- Go to the project folder.
- Execute
mvn clean dependency:copy-dependencies package
- Once the warnings have gone away then our project is fully built.
- A maven project has been created
- Project has a pom.xml file.
- It has all the dependencies needed to run a spring MVC application.
- All jar files needed are on the classpath.
- We are using here Maven standard directory layout where
- Source code is present in ${basedir}/src/main/java
- Resources are present in ${basedir}/src/main/resources
- Tests are present in ${basedir}/src/test
- Complied byte code is present in ${basedir}/target
- Distributable JAR is present in ${basedir}/target/classes
- All the web files are stored in src/main/webapp directory.
- In WEB-INF directory we will find spring configuration files.
- These determine the behavior of spring mvc framework.
- To start application right click on application name
- Select run as
- Select Run on server
- Click Finish.
- Web.xml
- It has a servlet called as the dispatcher servlet.
- This points our server to the Spring.
- We modify in order to configure our Application server.
- We specify redirection to our Dispatcher Servlet
- We load Dispatcher Servlet on startup.
- Be sure to add Maven Dependencies to class path i.e. push them along Tomcat Server Dependencies so that they both can work along.
- We need to add these manually to our class path
- Dispatcher Servlet
- Dispatcher servlet serves as our front controller.
- Responsible for accepting requests and returning responses.
- Takes care of finding the controller based on url.
- Looks for a configuration file with name as /WEB-INF/{Name Of Dispatcher Servlet}-servlet.xml.
- The name of the dispatcher servlet is defined in web.xml
- This configuration of dispatcher servlet defines its behavior.
- This is also use to configure our Spring Application.
- We can also define a file at our custom location, see this file is defined in init parameter in "web.xml" file.
- "<init-param>" tag.
- This file can be named to taste but servlet-context.xml is a standard.
- When Spring instantiates the dispatcher servlet it loads this configuration file.
- This also has a root-context.xml file.
- This is loaded by a context loader listener.
- 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"?>
<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>
<?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>
- root-context.xml
- 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.
- Eg JPA repository stored in there.
- Security Configuration etc.
- servlet-context.xml
- Spring consults many other xml files when it loads Dispatcher servlet to determine its behavior.
- All these xml files are defined in this file.
- These xml files define how our Spring Application will be configured.
- For example we have configured our view resolver in below code.
- 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 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>
<?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
- Once the dispatcher servlet has started up it waits to process request.
- When we hit our browser and we send a request to server.
- The dispatcher servlet looks at the url.
- It locates the controller that can handle the url.
- The controllers are mapped in servlet-context.xml
- A strategy is defined to map to them.
- Responsible for servicing all requests to our context root.
- The controller class is always annotated with a controller.
- @Controller
- A mapping is defined for requests for example a mapping is defined for root as
- @RequestMapping(value="/",method=RequestMethod.GET)
- The @Controller annotation above a class signals the spring that this class is responsible for processing request.
- A Request Mapping annotation with ("/") signals processing request for a context-root.
- Going through the function name we see
- We are logging information.
- Then we have created a new Date class object.
- Then we have formatted date.
- The formatted date variable is added as attribute to our model as "servertime".
- Model is defined as an argument to our method.
- Model.addAttribute("servertime",formattedDate); is the syntax for the same.
- Model acts as a map so model stores data as name and value pairs.
- Model is passed to a view.
- The function returns a String "home".This is mapped to "home.jsp" file.
- This configuration is provided in "servlet-context.xml" file as follows.
- <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>
- So it takes the string "name" "prefix"it with value "/web-INF/views" and suffix it with ".jsp".
- The string becomes "/Web-INF/views/home.jsp"
- This is the view we are going to display and we will have the file in location.
- The ".jsp" references to the variable attribute that we stored in our model.
- This jsp is rendered as our response to be displayed on browser.
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