This example presents the basic concept of using in Spring MVC the annotation based configuration.
The technologies used are :
-
– Spring 4.3.18
– JDK 1.8
– Maven 3.3.9
You can convert this example to an Eclipse IDE project by going to folder where is the pom.xml is, and use the command :
mvn eclipse:eclipse
Inspired from « Beginning Spring » Mert Caliskan, Kenan Sevindik, Rod Johnson (Foreword by), Jürgen Höller (Foreword by).
package javaspringexamples.spring.springmvcHelloWord.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
/**
*
* @author mounir.sahrani@gmail.com
*
*/
@Configuration
@ComponentScan(basePackages = { "javaspringexamples.spring.springmvcHelloWord" })
public class AppConfig {
@Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
package javaspringexamples.spring.springmvcHelloWord.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author mounir.sahrani@gmail.com
*
*/
@Controller
public class HelloController {
@RequestMapping(value = "/hello")
public ModelAndView sayHello() {
ModelAndView mv = new ModelAndView();
mv.addObject("message", "Hello JavaSpringExamples Word!");
mv.setViewName("helloWord");
return mv;
}
}
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
javaspringexamples.spring.springmvcHelloWord.config.AppConfig
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.mvc</url-pattern>
</servlet-mapping>
</web-app>
<% response.sendRedirect("hello.mvc"); %>
<html>
<body>
${message}
</body>
</html>
The output is : Hello JavaSpringExamples Word!
Get the sources of the example from the following GitHub url
