Spring MVC – Java and Spring Examples http://localhost/wordpress Wed, 26 Jun 2019 15:04:13 +0000 fr-FR hourly 1 https://wordpress.org/?v=5.0.4 Example Spring 4 MVC – Changing Theme http://localhost/wordpress/2019/03/19/example-spring-4-mvc-changing-theme/ Tue, 19 Mar 2019 17:41:29 +0000 http://localhost/wordpress/?p=550 This example presents the basic concept of using in Spring the changing theme.

The technologies used are :

    – Spring 4.3.18
    – JDK 1.80
    – 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.changingtheme.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 welcomeController {

    @RequestMapping(value = "/welcome")
    public ModelAndView user() {
        return new ModelAndView("welcome");
    }
}
style=css/white.css
style=css/yellow.css
body {
    background-color: white;
    color: black;
}
body {
    background-color: yellow;
    color: green;
}
<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>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.mvc</url-pattern>
	</servlet-mapping>

</web-app>
<?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-4.0.xsd 
       					   http://www.springframework.org/schema/context
       					   http://www.springframework.org/schema/context/spring-context-4.0.xsd
       					   http://www.springframework.org/schema/mvc 
       					   http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<context:component-scan
		base-package="javaspringexamples.spring.changingtheme" />
	<context:annotation-config />
	<mvc:annotation-driven />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<bean id="themeSource"
		class="org.springframework.ui.context.support.ResourceBundleThemeSource" />

	<bean id="themeResolver"
		class="org.springframework.web.servlet.theme.SessionThemeResolver">
		<property name="defaultThemeName" value="yellow" />
	</bean>

	<mvc:interceptors>
		<bean id="themeChangeInterceptor"
			class="org.springframework.web.servlet.theme.ThemeChangeInterceptor">
			<property name="paramName" value="theme" />
		</bean>
	</mvc:interceptors>

</beans>
<%
	response.sendRedirect("welcome.mvc");
%>
<%@ page contentType="text/html;charset=ISO-8859-9"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<head>
<title>JavaSpringExamples.io - Spring MVC Changing Theme</title>
<link rel="stylesheet" href="<spring:theme code="style"/>"
	type="text/css" />
</head>
<body>
	Theme :
	<a href="?theme=white">White theme</a> -
	<a href="?theme=yellow">Yellow theme</a>
	<br />
	<h1>JavaSpringExamples.io - Changing theme</h1>
</body>
</html>

Get the sources of the example from the following GitHub url

Or Download a .zip file

]]>
Example Spring 4 MVC – Internationalization http://localhost/wordpress/2019/03/19/example-spring-4-mvc-internationalisation/ Tue, 19 Mar 2019 17:30:52 +0000 http://localhost/wordpress/?p=548 This example presents the basic concept of using in Spring the internationalization.

The technologies used are :

    – Spring 4.3.18
    – JDK 1.80
    – 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.internationalisation.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 WelcomeController {

	@RequestMapping(value = "/welcome")
	public ModelAndView user() {
			return new ModelAndView("welcome");
	}
}
welcome=Welcome to JavaSpringExamples.io
welcome=Bienvenue à JavaSpringExamples.io
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	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>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.mvc</url-pattern>
	</servlet-mapping>
</web-app>
<?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-4.0.xsd 
       					   http://www.springframework.org/schema/context
       					   http://www.springframework.org/schema/context/spring-context-4.0.xsd
       					   http://www.springframework.org/schema/mvc 
       					   http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<context:component-scan
		base-package="javaspringexamples.spring.internationalisation" />
	<context:annotation-config />
	<mvc:annotation-driven />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<bean id="localeResolver"
		class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
		<property name="defaultLocale" value="en_US" />
	</bean>

	<bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basename" value="classpath:messages" />
	</bean>

	<mvc:interceptors>
		<bean id="localeChangeInterceptor"
			class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
			<property name="paramName" value="lang" />
		</bean>
	</mvc:interceptors>

</beans>
<%
	response.sendRedirect("welcome.mvc");
%>
<%@ page contentType="text/html; charset=ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<head>
<title>Spring MVC Internationalization</title>
</head>

<body>
	Language :
	<a href="?lang=en_US">English</a> -
	<a href="?lang=fr_FR">Français</a>
	<h2>
		<spring:message code="welcome" />
	</h2>
	Locale: ${pageContext.response.locale}
</body>
</html>

Get the sources of the example from the following GitHub url

Or Download a .zip file

]]>
Example Spring 4 MVC – Exception Handling http://localhost/wordpress/2019/03/19/example-spring-4-mvc-exception-handling/ Tue, 19 Mar 2019 16:17:18 +0000 http://localhost/wordpress/?p=537 This example presents the basic concept of using in Spring the exception handling.

The technologies used are :

    – Spring 4.3.18
    – JDK 1.80
    – 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.exceptionhandling.domain;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class Country {

	private String name;
	private String isoCode;

	public Country() {
	}

	public Country(String name, String isoCode) {
		this.name = name;
		this.isoCode = isoCode;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getIsoCode() {
		return isoCode;
	}

	public void setIsoCode(String isoCode) {
		this.isoCode = isoCode;
	}
}
package javaspringexamples.spring.exceptionhandling.exception;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class CountryNotFoundException extends Exception {

	public CountryNotFoundException(String name) {
		super("Country not found with name: " + name);
	}
}
package javaspringexamples.spring.exceptionhandling.handler;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
@ControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(Exception.class)
	public ModelAndView handleException() {
		return new ModelAndView("errorGlobal");
	}
}
package javaspringexamples.spring.exceptionhandling.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javaspringexamples.spring.exceptionhandling.domain.Country;
import javaspringexamples.spring.exceptionhandling.exception.CountryNotFoundException;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
@Controller
public class CountryController {

	private Map<String, Country> countries = new HashMap<String, Country>();

	@PostConstruct
	public void setup() {
		countries.put("morocco", new Country("Morocco", "MA"));
		countries.put("france", new Country("France", "FR"));
		countries.put("united states of america", new Country("United states of America", "US"));
		countries.put("error", new Country("Error", "Err"));
	}

	@RequestMapping(value = "/form")
	public ModelAndView country() {
		return new ModelAndView("form", "country", new Country());
	}

	@RequestMapping(value = "/result")
	public ModelAndView process(String name) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		if ("error".equalsIgnoreCase(name)) {
			throw new Exception();
		}

		Country country = countries.get(name.toLowerCase());
		if (country == null) {
			throw new CountryNotFoundException(name);
		}
		modelAndView.addObject("country", country);
		modelAndView.setViewName("result");
		return modelAndView;
	}

	@ExceptionHandler(CountryNotFoundException.class)
	public ModelAndView handleException(CountryNotFoundException e) {
		ModelAndView modelAndView = new ModelAndView("errorCountry");
		modelAndView.addObject("errorMessage", e.getMessage());
		return modelAndView;
	}
}
<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>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.mvc</url-pattern>
	</servlet-mapping>

</web-app>
<?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-4.0.xsd 
       					   http://www.springframework.org/schema/context
       					   http://www.springframework.org/schema/context/spring-context-4.0.xsd
       					   http://www.springframework.org/schema/mvc 
       					   http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<context:component-scan
		base-package="javaspringexamples.spring.exceptionhandling" />
	<context:annotation-config />
	<mvc:annotation-driven />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>
<%
	response.sendRedirect("form.mvc");
%>
<%@ page contentType="text/html; charset=ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc"%>
<html>
<head>
<title>JavaSpringExamples Exception Handling</title>
</head>
<body>

	<h2>Search Country</h2>
	<mvc:form modelAttribute="country" action="result.mvc">
		<table>
			<tr>
				<td><mvc:label path="name">Country Name</mvc:label></td>
				<td><mvc:input path="name" /></td>
			</tr>
			<tr>
				<td colspan="2"><input type="submit" value="Search" /></td>
			</tr>
		</table>
	</mvc:form>
</body>
</html>
<%@ page contentType="text/html; charset=ISO-8859-1"%>
<html>
<head>
<title>Country Not Found</title>
</head>
<body>
	<h2>${errorMessage}</h2>
</body>
</html>
<html>
<head>
<title>Error!</title>
</head>
<body>
	<h2>Error occurred!</h2>
</body>
</html>
<%@ page contentType="text/html; charset=ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc"%>
<html>
<head>
<title>JavaSpringExamples Exception Handling</title>
</head>
<body>
	<h2>Search Country</h2>
	<table>
		<tr>
			<td>Country Name :</td>
			<td>${country.name}</td>
		</tr>
		<tr>
			<td>ISO Code :</td>
			<td>${country.isoCode}</td>
		</tr>
	</table>
</body>
</html>

Get the sources of the example from the following GitHub url

Or Download a .zip file

]]>
Example Spring 4 MVC – Form http://localhost/wordpress/2019/03/19/529/ Tue, 19 Mar 2019 15:59:32 +0000 http://localhost/wordpress/?p=529 This example presents the basic concept of using forms in Spring MVC.

The technologies used are :

    – Spring 4.3.18
    – JDK 1.80
    – 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.mvcform.domain;

import java.time.LocalDate;

import javax.validation.constraints.Size;

import org.springframework.format.annotation.DateTimeFormat;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class User {

	@Size(min = 3, max = 14)
	private String name;
	@Size(min = 3, max = 14)
	private String lastname;
	private String password;
	private String detail;
	@DateTimeFormat(pattern = "yyyy-MM-dd")
	private LocalDate birthDate;
	private Gender gender;
	private String country;
	private boolean nonSmoking;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getLastname() {
		return lastname;
	}

	public void setLastname(String lastname) {
		this.lastname = lastname;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getDetail() {
		return detail;
	}

	public void setDetail(String detail) {
		this.detail = detail;
	}

	public LocalDate getBirthDate() {
		return birthDate;
	}

	public void setBirthDate(LocalDate birthDate) {
		this.birthDate = birthDate;
	}

	public Gender getGender() {
		return gender;
	}

	public void setGender(Gender gender) {
		this.gender = gender;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public boolean isNonSmoking() {
		return nonSmoking;
	}

	public void setNonSmoking(boolean nonSmoking) {
		this.nonSmoking = nonSmoking;
	}
}
package javaspringexamples.spring.mvcform.domain;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public enum Gender {
	MALE,
	FEMALE;
}
package javaspringexamples.spring.mvcform.controller;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javaspringexamples.spring.mvcform.domain.Gender;
import javaspringexamples.spring.mvcform.domain.User;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
@Controller
public class UserController {

	private static final String[] countries = { "Morocco", "United States", "France" };

	@RequestMapping(value = "/form")
	public ModelAndView user() {
		ModelAndView modelAndView = new ModelAndView("userForm", "user", new User());
		modelAndView.addObject("genders", Gender.values());
		modelAndView.addObject("countries", countries);

		return modelAndView;
	}

	@RequestMapping(value = "/result")
	public ModelAndView processUser(@Valid User user, BindingResult result) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("user", user);

		if (result.hasErrors()) {
			modelAndView.addObject("genders", Gender.values());
			modelAndView.addObject("countries", countries);
			modelAndView.setViewName("userForm");
		} else {
			modelAndView.setViewName("userResult");
		}

		return modelAndView;
	}
}
Size.user.name=Error format: at least 3, max 14.
Size.user.lastname=Error format: at least 3, max 14.
Pattern.user.password=Error format: at least 4 letters, max 15.
<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>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.mvc</url-pattern>
	</servlet-mapping>

</web-app>
<?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-4.0.xsd 
       					   http://www.springframework.org/schema/context
       					   http://www.springframework.org/schema/context/spring-context-4.0.xsd
       					   http://www.springframework.org/schema/mvc 
       					   http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<context:component-scan
		base-package="javaspringexamples.spring.mvcform" />
	<context:annotation-config />
	<mvc:annotation-driven />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>
<% response.sendRedirect("form.mvc"); %>
<%@ page contentType="text/html; charset=ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc"%>
<html>
<head>
<title>JavaSpringExamples Spring MVC Form</title>
</head>
<body>

	<h2>Form</h2>
	<mvc:form modelAttribute="user" action="result.mvc">
		<table>
			<tr>
				<td><mvc:label path="name">Name</mvc:label></td>
				<td><mvc:input path="name" /></td>
				<td><mvc:errors path="name" /></td>
			</tr>
			<tr>
				<td><mvc:label path="lastname">Last Name</mvc:label></td>
				<td><mvc:input path="lastname" /></td>
				<td><mvc:errors path="lastname" /></td>
			</tr>
			<tr>
				<td><mvc:label path="password">Password</mvc:label></td>
				<td><mvc:password path="password" /></td>
				<td><mvc:errors path="password" /></td>
			</tr>
			<tr>
				<td><mvc:label path="detail">Detail</mvc:label></td>
				<td><mvc:textarea path="detail" /></td>
			</tr>
			<tr>
				<td><mvc:label path="birthDate">Birth Date</mvc:label></td>
				<td><mvc:input path="birthDate" /></td>
			</tr>
			<tr>
				<td><mvc:label path="gender">Gender</mvc:label></td>
				<td><mvc:radiobuttons path="gender" items="${genders}" /></td>
			</tr>
			<tr>
				<td><mvc:label path="country">Country</mvc:label></td>
				<td><mvc:select path="country" items="${countries}" /></td>
			</tr>
			<tr>
				<td><mvc:label path="nonSmoking">Non Smoking</mvc:label></td>
				<td><mvc:checkbox path="nonSmoking" /></td>
			</tr>
			<tr>
				<td colspan="2"><input type="submit" value="Submit" /></td>
			</tr>
		</table>
	</mvc:form>
</body>
</html>
<%@ page contentType="text/html; charset=ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc"%>
<html>
<head>
<title>JavaSpringExamples Spring MVC Form</title>
</head>
<body>
	<h2>Result</h2>
	<table>
		<tr>
			<td>Name</td>
			<td>${user.name}</td>
		</tr>
		<tr>
			<td>Last name</td>
			<td>${user.lastname}</td>
		</tr>
		<tr>
			<td>Password</td>
			<td>${user.password}</td>
		</tr>
		<tr>
			<td>Detail</td>
			<td>${user.detail}</td>
		</tr>
		<tr>
			<td>Birth Date</td>
			<td>${user.birthDate}</td>
		</tr>
		<tr>
			<td>Gender</td>
			<td>${user.gender}</td>
		</tr>
		<tr>
			<td>Country</td>
			<td>${user.country}</td>
		</tr>
		<tr>
			<td>Non-Smoking</td>
			<td>${user.nonSmoking}</td>
		</tr>
	</table>
</body>
</html>

Get the sources of the example from the following GitHub url

Or Download a .zip file

]]>
Example Spring 4 MVC – Bean Validation http://localhost/wordpress/2019/03/19/example-spring-4-mvc-bean-validation/ Tue, 19 Mar 2019 15:46:06 +0000 http://localhost/wordpress/?p=525 This example presents the basic concept of using in Spring MVC bean validation.

The technologies used are :

    – Spring 4.3.18
    – JDK 1.80
    – 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.beanvalidation.domain;

import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class User {

	@Size(min = 3, max = 20)
	String username;

	@Pattern(regexp = "^[a-zA-Z]\\w{3,14}$")
	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;
	}
}
Pattern.user.password=Error format: at least 4 letters, max 15.
Size.user.username=Error format: at least 3, max 20.
package javaspringexamples.spring.beanvalidation.controller;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javaspringexamples.spring.beanvalidation.domain.User;

import javax.validation.Valid;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */

@Controller
public class UserController {

	@RequestMapping(value = "/form")
	public ModelAndView initiateUser() {
		return new ModelAndView("userForm", "user", new User());
	}

	@RequestMapping(value = "/result", method = RequestMethod.POST)
	public ModelAndView processUser(@Valid User user, BindingResult result) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("usr", user);

		if (result.hasErrors()) {
			modelAndView.setViewName("userForm");
		} else {
			modelAndView.setViewName("userResult");
		}

		return modelAndView;
	}
}
<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>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.mvc</url-pattern>
	</servlet-mapping>

</web-app>
<?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-4.0.xsd 
       					   http://www.springframework.org/schema/context
       					   http://www.springframework.org/schema/context/spring-context-4.0.xsd
       					   http://www.springframework.org/schema/mvc 
       					   http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<context:component-scan
		base-package="javaspringexamples.spring.beanvalidation.controller" />
	<context:annotation-config />
	<mvc:annotation-driven validator="validator" />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basename" value="classpath:errorMessages" />
	</bean>

	<bean id="validator"
		class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
		<property name="validationMessageSource" ref="messageSource" />
	</bean>
</beans>
<%
	response.sendRedirect("form.mvc");
%>
<%@ page contentType="text/html; charset=ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc"%>
<html>
<head>
<title>JavaSpringExamples Spring MVC Form</title>
<style type="text/css">
.formFieldError {
	background-color: #FFC;
}
</style>
</head>
<body>

	<h2>Form</h2>
	<mvc:form modelAttribute="user" action="result.mvc">
		<table>
			<tr>
				<td><mvc:label path="username">Login</mvc:label></td>
				<td><mvc:input path="username" cssErrorClass="formFieldError" /></td>
				<td><mvc:errors path="username" /></td>
			</tr>
			<tr>
				<td><mvc:label path="password">Password</mvc:label></td>
				<td><mvc:password path="password"
						cssErrorClass="formFieldError" /></td>
				<td><mvc:errors path="password" /></td>
			</tr>
			<tr>
				<td colspan="3"><input type="submit" value="Submit" /></td>
			</tr>
		</table>
	</mvc:form>
</body>
</html>
<%@ page contentType="text/html; charset=ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc"%>
<html>
<head>
<title>JavaSpringExamples Spring MVC Form</title>
</head>
<body>
	<h2>Result Form</h2>
	<table>
		<tr>
			<td>login :</td>
			<td>${usr.username}</td>
		</tr>
		<tr>
			<td>Password :</td>
			<td>${usr.password}</td>
		</tr>
	</table>
</body>
</html>

Get the sources of the example from the following GitHub url

Or Download a .zip file

]]>
Example Spring 4 MVC – Hello Word XML Config http://localhost/wordpress/2019/03/19/example-spring-4-mvc-hello-word-xml-config/ Tue, 19 Mar 2019 15:32:31 +0000 http://localhost/wordpress/?p=522 This example presents the basic concept of using in Spring MVC the XML based configuration.

The technologies used are :

    – Spring 4.3.18
    – JDK 1.80
    – 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.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>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/springmvc-servlet.xml</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>
<?xml version="1.0" encoding="UTF-8"?>
<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       					   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
       					   http://www.springframework.org/schema/context
       					   http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 
    <context:component-scan base-package="javaspringexamples.spring.springmvcHelloWord" />
    <context:annotation-config />
 
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>
<% 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

Or Download a .zip file

]]>
Example Spring 4 MVC – Hello Word Annotation Config http://localhost/wordpress/2019/03/19/example-spring-4-mvc-hello-word-annotation-config/ Tue, 19 Mar 2019 11:30:21 +0000 http://localhost/wordpress/?p=501 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

Or Download a .zip file

]]>