Spring Mvc Example
We are going to create a spring mvc base example with maven in eclipce.
In this example we will print a message "Hello World" on screen and will handle same common errors like 404 (URL not found) or 500 (internal server error).
1. Click on File -> New -> other and select Maven Project
2. In next step select project location
4. In next step Specify Archetype parameters and click on finish. Now we have created
5. Now add project dependencies in pom.xml file.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com</groupId> <artifactId>example</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ROOT</name> <url>http://maven.apache.org</url> <properties> <spring.framework.version>3.2.0.RELEASE</spring.framework.version> <targetJdk>1.7</targetJdk> <sourceJdk>1.7</sourceJdk> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.framework.version}</version> <exclusions> <!-- Exclude Commons Logging in favor of SLF4j --> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.framework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.framework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.framework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.framework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.framework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.framework.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>example</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>${sourceJdk}</source> <target>${targetJdk}</target> </configuration> </plugin> </plugins> </build> </project>
6. Create spring controller HelloWorld.java in main/java/com/example folder
package com.example; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class HelloWorld { @RequestMapping(value = "/helloWorld", method = RequestMethod.GET) public ModelAndView helloWorld() { ModelAndView modelAndView = new ModelAndView("helloWorld"); modelAndView.addObject("message", "Hello World"); return modelAndView; } @RequestMapping(value = "/serverError", method = RequestMethod.GET) public int serverError() { Integer test = null; return test + 1; } }
The @Controller annotation indicates that a particular class serves the role of a controller.
There are several important things to point out here. First, the HelloWorld class is annotated
with @Controller so that it will be autoregistered as a bean by <mvc:annotation-driven />.
methods are also annotated with @RequestMapping, @RequestMapping indicates
that HTTP GET respond to requests for “/helloWorld” or "/serverError".
In our controller helloWorld() method return a ModelAndView object. The ModelAndView class is essentially a glorified Map that can
make adding objects that are to be displayed in (or on) a View adhere to a common naming convention.
ModelAndView stores values that we want to carry to the view. we added an value of key "message" and value “Hello World”.
We create a add a ModelAndView object with view name "helloWorld". Spring viewResolver will add prefix and suffix parameter with view name.
In final view name "helloWorld" will change to “/WEB-INF/jsp/helloWorld.jsp” and we will see "helloWorld.jsp" on screen.
7. Update web.xml in WEB-INF folder.
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SpringHelloWorldExample</display-name> <servlet> <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/app-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <error-page> <error-code>404</error-code> <location>/pageNotFound.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/error.jsp</location> </error-page> <welcome-file-list> <welcome-file>home.jsp</welcome-file> </welcome-file-list> </web-app>
Spring's web MVC framework is a request-driven framework, designed around a central servlet that
dispatches requests to controllers and offers other functionality facilitating the development of web applications.Spring's DispatcherServlet does that.
The DispatcherServlet is an actual Servlet and declared in the web.xml of your web application.
Requests that you want the DispatcherServlet to handle will have to be mapped using a URL mapping in the same web.xml file.
In our example we mapped the DispatcherServlet with URL "/". All request with URl "/" will be handled by DispatcherServlet.
We also mapped jsp error pages with some specific errors. Whenever a error occured in our example, specific error page will show on screen.
We also defined a welcome page "home.jsp" in web.xml. This page show on startup of our example.
8. Create app-config.xml (Configuration file) in WEB-INF folder.
<?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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- Scans the classpath of this application for @Components to deploy as beans --> <context:component-scan base-package="com.example" /> <!-- Configures the @Controller programming model --> <mvc:annotation-driven /> <!-- Resolves view names to protected .jsp resources within the /WEB-INF/jsp directory --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
The framework will look for a configuration file named [servlet-name]-servlet.xml on initialization of a DispatcherServlet.
We defined a configuration file name and position as a init-param with name “contextConfigLocation“ in web.xml
The configuration file will contain information about controller class, view resolvers etc.
To enable autodetection of such annotated controllers, you have to add component scanning to your configuration.
This is easily achieved by using the spring-context schema as shown in the following XML snippet:
<mvc:annotation-driven /> : To enable autodetection of such annotated controllers
<context:component-scan base-package="com.example" /> : Add component scanning path
We also registered an viewResolver of type “org.springframework.web.servlet.view.InternalResourceViewResolver“.
Spring will automatically configure it as a view resolver component and when any spring controller will return a view name
it will check for the view definition with the class “org.springframework.web.servlet.view.InternalResourceViewResolver“.
InternalResourceViewResolver class takes two special parameters prefix and suffix. The value of
these parameters are applied to the view name to get actual location of the view.
For example -
spring controller returns the view name as "helloWorld" and prefix is defined as “/WEB-INF/jsp/” and suffix
is defined as “.jsp” the InternalResourceViewResolver will return the jsp “/WEB-INF/jsp/helloWorld.jsp”
to the browser.
9. Create helloWorld.jsp (Spring View) in WEB-INF\jsp folder.
<html> <head> <title>Hello World Example</title> </head> <body> <h1>${message}</h1> </body> </html>
In "helloWorld.jsp" we just will show the message return by controller.
10. Create others jsp pages to show links and error messages.
<html>
<body>
<h1 style="color: red;">Some Error On server</h1>
</body>
</html>
<html>
<body>
<h1 style="color: red;">Page Not Found</h1>
</body>
</html>
Now our spring project with maven is completed. Final project will look like -
To run this project -
Open command prompt (CMD.exe).
Go to example(root) directory of project.
Execute maven command : mvn clean package This maven command will compile and build the project.
After successful buield a war file example.war will generate in target folder.
Deploy example.war file in tomcat.
Click on first link "say hello" ("/example/helloWorld"). You will see message "Hello World" on screen.
Click on second link "serverError 500" ("/example/serverError"). This will send a request on controller and a "Null Pointer Exception"
Click on third and final link "wrongUrl error 404" ("/example/wrongUrl"). This will send a request on controller, But will not found
any mapping with this url and you will be redirect to "page not found" page.
Related posts :-
Maven introduction
Spring Mvc Hello World Example With Annotation
Related posts :-
Maven introduction
Spring Mvc Hello World Example With Annotation
No comments:
Post a Comment