Create Spring MVC Project
On the Eclipse, create a Spring MVC project
Enter Project Information:
- Name: LearnSpringMVCWithRealApps
- Group: com.demo
- Artifact: LearnSpringMVCWithRealApps
- Description: Learn Spring MVC with Real Apps
- Package: com.demo
Select the technologies and libraries to be used:
- Web
Click Next button to show Site Information for project
Click Finish button to finish create Spring MVC project
Configure pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.demo</groupId>
<artifactId>LearnSpringMVCWithRealApps</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>LearnSpringMVCWithRealApps</name>
<description>Learn Spring MVC with Real Apps</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JSTL tag lib -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- Tomcat for JSP rendering -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Configure application.properties
spring.mvc.view.prefix = /WEB-INF/views/
spring.mvc.view.suffix = .jsp
spring.mvc.static-path-pattern=/resources/**
server.port=9596
Entities Class
Create new package, named com.demo.entities. In this package, create entities class as below:
Account Entity
Create new java class, named Account.java
package com.demo.entities;
public class Account {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Account(String username, String password) {
this.username = username;
this.password = password;
}
public Account() {
}
}
Models Class
Create new package, named com.demo.models. In this package, create AccountModel class as below:
package com.demo.models;
public class AccountModel {
public boolean login(String username, String password) {
return username.equalsIgnoreCase("abc") && password.equalsIgnoreCase("123");
}
}
Create Controllers
Create new package named com.demo.controllers. In this package, create controllers as below:
Account Controller
Create new java class, named AccountController.java
package com.demo.controllers;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.demo.entities.Account;
import com.demo.models.AccountModel;
@Controller
@RequestMapping(value = { "", "account" })
public class AccountController {
@RequestMapping(method = RequestMethod.GET)
public String index() {
return "redirect:/account/login";
}
@RequestMapping(value = "login", method = RequestMethod.GET)
public String login(ModelMap modelMap, HttpSession session, HttpServletRequest request) {
Account account = checkCookie(request);
if (account == null) {
modelMap.put("account", new Account());
return "account/index";
} else {
AccountModel accountModel = new AccountModel();
if (accountModel.login(account.getUsername(), account.getPassword())) {
session.setAttribute("username", account.getUsername());
return "account/welcome";
} else {
modelMap.put("error", "Account's Invalid");
return "account/index";
}
}
}
@RequestMapping(value = "login", method = RequestMethod.POST)
public String login(@ModelAttribute(value = "account") Account account, ModelMap modelMap, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
AccountModel accountModel = new AccountModel();
if (accountModel.login(account.getUsername(), account.getPassword())) {
session.setAttribute("username", account.getUsername());
if (request.getParameter("remember") != null) {
Cookie ckUsername = new Cookie("username", account.getUsername());
ckUsername.setMaxAge(3600);
response.addCookie(ckUsername);
Cookie ckPassword = new Cookie("password", account.getPassword());
ckPassword.setMaxAge(3600);
response.addCookie(ckPassword);
}
return "account/welcome";
} else {
modelMap.put("error", "Account's Invalid");
return "account/index";
}
}
@RequestMapping(value = "logout", method = RequestMethod.GET)
public String logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
// Remove session
session.removeAttribute("username");
// Remove cookie
for (Cookie cookie : request.getCookies()) {
if (cookie.getName().equalsIgnoreCase("username")) {
cookie.setMaxAge(0);
response.addCookie(cookie);
}
if (cookie.getName().equalsIgnoreCase("password")) {
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
return "redirect:/account/login";
}
public Account checkCookie(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
Account account = null;
String username = "", password = "";
for (Cookie cookie : cookies) {
if (cookie.getName().equalsIgnoreCase("username")) {
username = cookie.getValue();
}
if (cookie.getName().equalsIgnoreCase("password")) {
password = cookie.getValue();
}
}
if (!username.isEmpty() && !password.isEmpty()) {
account = new Account(username, password);
}
return account;
}
}
Create Views
Create new folders with path webapp\WEB-INF\views in src\main. In views folder, create views as below:
Index View
Create new folder named account. Create new jsp file named index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Remember Me with Spring MVC Framework</title>
</head>
<body>
<s:form method="post" modelAttribute="account" action="${pageContext.request.contextPath }/account/login">
<fieldset>
<legend>Login</legend>
${error }
<table cellpadding="2" cellspacing="2">
<tr>
<td>Username</td>
<td><s:input path="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><s:password path="password" /></td>
</tr>
<tr>
<td>Remember Me?</td>
<td><input type="checkbox" name="remember" value="true"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</fieldset>
</s:form>
</body>
</html>
Welcome View
In account folder, create new jsp file named welcome.jsp as below:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Remember Me with Spring MVC Framework</title>
</head>
<body>
Welcome ${sessionScope.username }
<br>
<a href="${pageContext.request.contextPath }/account/logout">Logout</a>
</body>
</html>
Structure of Spring MVC Project
Run Application
Select LearnSpringMVCWithRealAppsApplication.java file in com.demo package, right click and select Run As/Spring Boot App menu
Access index method in account controller with following url: http://localhost:9596/account
Output
Test with invalid account is username: acc2 and password: 123
Output
Test with valid account is username: abc and password: 123.
Output
Click logout link from welcome page to open login page again
Output