Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very beginning. In this post we will build a basic Spring MVC 5 Web Application with Bootstrap. we will see how to configure a Spring MVC application without using a web.xml. We will use Java-based configuration.
We will use a simple Maven web project. Maven will resolve and manage all the dependencies automatically. Below is the pom.xml file for our project. Notice here is the maven-war-plugin declaration. As we will be completely removing web.xml, we will need to configure this plugin in order to avoid maven failure to build war package.
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.onrugi</groupId>
<artifactId>Spring-MVC-Java-Configuration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<encoding>UTF-8</encoding>
<org.springframework.version>5.1.3.RELEASE</org.springframework.version>
</properties>
<dependencies>
<!--
Web application development utilities applicable to both Servlet and Portlet Environments
(depends on spring-core, spring-beans, spring-context)
Define this if you use Spring MVC, or wish to use Struts, JSF, or another web framework with Spring (org.springframework.web.*)
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>
@Controller annotation on class name declares this class as spring bean and The @RequestMapping annotation maps the URL's onto particular classes or methods.In this example, we populate the Model map- which is basically a map for the request attributes with a key called message and a simple string value.
package com.onrugi.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/")
public class AppController {
@RequestMapping(method = RequestMethod.GET)
public String index(ModelMap model){
model.addAttribute("message", "Spring MVC Java Configuration Example");
return "index";
}
}
@ComponentScan() - Scan starts from base package and registers all controllers, repositories, service, beans, etc.
@EnableWebMvc - Enable Spring MVC-specific annotations like @Controller
@Configuration - Treat as the configuration file for Spring MVC-enabled applications.the @Bean tag to register ViewResolver.
package com.onrugi.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
@ComponentScan({"com.onrugi"})
public class AppConfig implements WebMvcConfigurer{
@Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
/**
* Configure ResourceHandlers to serve static resources like CSS/ Javascript etc...
*/
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
}
}
DispatcherServlet, which acts as the FrontController of the Spring MVC application.
package com.onrugi.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { AppConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Create a new folder named views under WEB-INF and add in a Simple JSP page welcome.jsp (WEB-INF/views/index.jsp) to simply access the model value sent from controller.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<title>Welcome To sprring MVC</title>
<!-- Custom styles for this template -->
<link href="<c:url value='/assets/css/bootstrap.css' />" rel="stylesheet"></link>
<link href="<c:url value='/assets/css/starter-template.css'/>" rel="stylesheet"></link>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
<a class="navbar-brand" href="<c:url value='/ ' />">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="<c:url value='/' />">Home <span class="sr-only">(current)</span></a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
<button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<main role="main" class="container">
<div class="starter-template">
<h1>Spring MVC 5 + Bootstrap starter template</h1>
<p class="lead">${message}</p>
</div>
</main><!-- /.container -->
<script src="<c:url value='/assets/dist/jquery.js' />"> </script>
<script src="<c:url value='/assets/js/bootstrap.js' />"> </script>
</body>
</html>
URL: http://localhost:8080/Spring-MVC-Java-Configuration/
The source code is available on my GitHub repository.Download Source Code .
Welcome to Onrugi! Onrugi is an online Blog for IT, application developers, and web designers with its focus on sharing helpful resources, tutorials, instructions, exploring new techniques, and sharing useful tips. The team of Onrugi is dedicated to provide useful, inspiring and innovative content that is free of charge.
test onload="alert('you got hacked');