Building Web Development with Spring Framework
NARAYANAN PALANI ??????
Platform Engineering Lead | AWS & Google Cloud Certified Architect | Cloud Solutions Expert | Driving Innovation in Retail, Commercial & Investment Banking | CI/CD | DevOps | Cloud Transformation
Spring framework is powerful in building both backend and front end solutions. Web development in Spring helps targeting enterprise-level applications which are potentially built with scalability and robustness in mind.
This article elaborates simple steps in building a brand new website in fraction of few minutes time using Spring Framework.
Project Structure
Simple website built with an option to register for a demo of an application in this piece of code. Clone and use this sample project from Github at : https://github.com/narayananpalani/Demo/tree/main
MVC (Model View Controller)
The Spring Web model-view-controller (MVC) framework is designed around a?DispatcherServlet?that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for uploading files. The default handler is based on the?@Controller?and?@RequestMapping?annotations, offering a wide range of flexible handling methods. With the introduction of Spring 3.0, the?@Controller?mechanism also allows you to create RESTful Web sites and applications, through the?@PathVariable?annotation and other features.
WebApp
Two website views are built in JSP files to reflect two hyperlinks within the website.
About Page
This about page constructed with head and body of greetings message:
<!DOCTYPE html>
<html>
<head>
<title>About</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>
Demo Registration Page
This web page displays option to enter Name, Email ID, Phone to submit using registration button for the demo of software application:
<%@ page contentType="text/html; ISO-8859-1" language="java" %>
<%@ taglib prefix="form" uri="https://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<title>DemoRegistration</title>
</head>
<body>
<h1>Registration</h1>
<form:form modelAttribute="registration">
<table>
<tr>
<td>
Name:
</td>
<td>
<form:input path="name" />
</td>
</tr>
<tr>
<td>
Email ID:
</td>
<td>
<form:input path="emailid" />
</td>
</tr>
<tr>
<td>
Phone:
</td>
<td>
<form:input path="phone" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Registration for the Demo">
</td>
</tr>
</table>
</form:form>
</body>
</html>
Controllers
Spring MVC provides an annotation-based programming model where?@Controller?and?@RestController?components use annotations to express request mappings, request input, exception handling, and more. Annotated controllers have flexible method signatures and do not have to extend base classes nor implement specific interfaces
About Controller
package com.software.club.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Map;
@Controller
public class AboutController {
@GetMapping("about")
public String greeting(Map<String, Object> model) {
model.put("message", "This is a demo software of club");
return "about";
}
}
Demo Registration Controller
package com.software.club.controller;
import com.software.club.model.DemoRegistration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class DemoRegistrationController {
@GetMapping("demoregistration")
public String getRegistration(@ModelAttribute ("registration") DemoRegistration demoregistration) {
return "demoregistration";
}
@PostMapping("demoregistration")
public String addRegistration(@ModelAttribute ("registration") DemoRegistration demoregistration) {
System.out.println("Registration: " + demoregistration.getName());
return "demoregistration";
}
}
Redirect the Website post Submission of Entries:
@PostMapping("demoregistration")
public String addRegistration(@ModelAttribute ("registration") DemoRegistration demoregistration) {
System.out.println("Registration: " + demoregistration.getName());
return "redirect: demoregistration";
}
Model
Demo registration page's three input variables declared along with getters and setters:
package com.software.club.model;
public class DemoRegistration {
private String name;
private Integer phone;
private String emailId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public Integer getPhone() {
return phone;
}
public void setPhone(Integer phone) {
this.phone = phone;
}
}
Look at some more examples on constructing getters and setters:
Application
This main application constructed with @SpringBootApplication tag that helps in running this application from IntelliJ IDE.
Many Spring Boot developers like their apps to use auto-configuration, component scan and be able to define extra configuration on their "application class". A single?@SpringBootApplication?annotation can be used to enable those three features, that is:
The?@SpringBootApplication?annotation is equivalent to using?@Configuration,?@EnableAutoConfiguration, and?@ComponentScan?with their default attributes,
package com.software.club;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Application YAML helps linking asp files of respective pages via yaml file:
spring:
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
Index
This index file provides a reference between the links associated to about and registration pages.
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>Hello</h1>
<a href="about">About</a>
<a href="demoregistration">Demo Registration</a>
</body>
</html>
领英推荐
Language Extensions
The?LocaleChangeInterceptor?changes the language based on the fact if the request parameter is present or not. If this parameter is present it will get the?Locale?and use the?LocaleResolver.setLocale?method to change the language for the current user.
All the code that needs the?Locale?for translating messages use the LocaleResolver.resolveLocale?method to obtain it.
Localisation through latest Spring Config used in this repository to display page in English and Spanish:
package com.software.club;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import java.util.Locale;
@Configuration
public class DemoApplicationConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**")
.addResourceLocations("/WEB-INF/pdf/");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.US);
return slr;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");
return lci;
}
}
Extend Message files to source and reflect right localised content:
English:
#labels
name=Name
phone=Phone
#buttons
save.changes=Save Changes
Spanish:
#labels
name=Nombre
phone=Telefono
#buttons
save.changes=enviar registro
View
Input path provided for each text box to invoke right language based text to display on the website:
<%@ page contentType="text/html; ISO-8859-1" language="java" %>
<%@ taglib prefix="form" uri="https://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="https://www.springframework.org/tags" %>
<!DOCTYPE html>
<html>
<head>
<title>DemoRegistration</title>
</head>
<body>
<h1>Registration</h1>
<form:form modelAttribute="registration">
<table>
<tr>
<td>
<spring:message code="name" />:
</td>
<td>
<form:input path="name" />
</td>
</tr>
<tr>
<td>
Email ID:
</td>
<td>
<form:input path="emailid" />
</td>
</tr>
<tr>
<td>
<spring:message code="phone" />:
</td>
<td>
<form:input path="phone" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="<spring:message code="save.changes"/>" >
</td>
</tr>
</table>
</form:form>
</body>
</html>
Display
Once a website has been built using Spring Framework, it is possible to further extend features to control security, language and performance of the site based on the nature and complexity of user base.
Website Display while running in local:
About Page:
Registration Page
Language Support:
Page gets rendered in English when internal link has been launched.
Spanish:
The same website rendered in Spanish with the help of Spanish message files from the code repository.
This is a best example to reflect MVC model of developing website using Java within Spring Framework. Let us take a look at what makes it better when comparing to React.
Summary -React vs Spring: What are the differences?
React and Spring are both widely used frameworks in web development. Let's explore the key differences between them.
In summary, React is a front-end JavaScript library focused on building user interfaces, while Spring is a back-end Java framework targeting enterprise-level applications. React is suited for building single-page and mobile applications, providing a fast development experience, while Spring offers a comprehensive infrastructure for full-stack development with scalability and robustness.
How do you find this article on technical development of simple website using Spring Boot? Please leave your comments.
Keywords: #FinancialServices #FinTech #innovation #technology #digitalmarketing #management #creativity #future #socialmedia #socialnetworking #socialentrepreneurship #customerrelations
Disclaimer: Contents, posts and media used in this account of the author do not represent any organisation of any sort. Under no circumstances will the author be held responsible or liable in any way for any claims, loss, expenses or liabilities whatsoever.
Like this article? Subscribe to Engineering Leadership , Digital Accessibility and Digital Payments Hub to enjoy reading useful articles. Press SHARE and REPOST button to help sharing the content with your network.