1:36 pm - Saturday March 25, 2017

Spring MVC with CookieThemeResolver Tutorial + Example

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

BACK

Spring MVC with CookieThemeResolver Tutorial + Example

app-config.xml


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

	<bean id="themeSource" class="org.springframework.ui.context.support.ResourceBundleThemeSource">
		<property name="basenamePrefix" value="theme-" />
	</bean>

	<!-- Theme Change Interceptor and Resolver definition -->
	<bean id="themeChangeInterceptor" class="org.springframework.web.servlet.theme.ThemeChangeInterceptor">
		<property name="paramName" value="theme" />
	</bean>

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

	<bean id="urlHandler" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
		<property name="interceptors">
			<list>
				<ref bean="themeChangeInterceptor" />
			</list>
		</property>
	</bean>

	<bean id="registrationValidator" class="com.raistudies.validator.RegistrationValidator"/>

	<bean name="/registration.htm" class="com.raistudies.controllers.RegistrationController">
		<property name="formView" value="registration"/>
		<property name="successView" value="success"/>
		<property name="validator" ref="registrationValidator"/>
	</bean>

	<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"/>
		<property name="suffix" value=".jsp"/>
	</bean>

</beans>

RegistrationController.java


package com.raistudies.controllers;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.raistudies.domain.RegistrationBean;

public class RegistrationController extends SimpleFormController{

	public RegistrationController(){
		setCommandClass(RegistrationBean.class);
		setCommandName("Registration");
	}

	@Override
	protected ModelAndView onSubmit(Object command, BindException errors)
			throws Exception {
		ModelAndView mv = new ModelAndView();
		if(errors.hasErrors()){
			mv.setViewName(getFormView());
		}else{
			mv.addObject("Registration", command);
			mv.setViewName(getSuccessView());
		}
		return mv;
	}

}

RegistrationBean.java


package com.raistudies.domain;

public class RegistrationBean {
	private String name = null;
	private String username = null;
	private String email = null;
	private String phone = null;
	private String password = null;
	private String rePassword = null;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getRePassword() {
		return rePassword;
	}
	public void setRePassword(String rePassword) {
		this.rePassword = rePassword;
	}
}

RegistrationValidator.java


package com.raistudies.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.raistudies.domain.RegistrationBean;

public class RegistrationValidator implements Validator {

	public boolean supports(Class<?> c) {
		return RegistrationBean.class.isAssignableFrom(c);
	}

	public void validate(Object command, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "field.name.empty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "field.username.empty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "field.email.empty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "field.phone.empty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "field.password.empty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "rePassword", "field.rePassword.empty");
		RegistrationBean regBean = (RegistrationBean)command;
		if(!regBean.getPassword().equals(regBean.getRePassword()))
			errors.rejectValue("rePassword","password.notmatch");
		if(regBean.getPhone().trim().length() != 10)
			errors.rejectValue("phone","field.phone.length");
		if(!isNumber(regBean.getPhone().trim()))
			errors.rejectValue("phone", "field.phone.NAN");
	}

	private boolean isNumber(String str){
	    for (int i = 0; i < str.length(); i++) {

	        //If we find a non-digit character we return false.
	        if (!Character.isDigit(str.charAt(i)))
	        return false;
	        }

	        return true;
	}
}

registration.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page session="true" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<title>Form Validation with Spring 3 MVC and theme resolver</title>
		<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
		<link rel="stylesheet" href="<spring:theme code="style"/>" type="text/css" />
	</head>
	<body>
		<table>
			<tbody>
				<tr><td>Change Theme:</td><td><form name="themeChangeForm" method="get">
					<select name="theme" onchange="submitform()">
						<option selected="selected">--</option>
						<option value="default">Default</option>
						<option value="blue">Blue</option>
						<option value="black">Black</option>
					</select>
				</form></td></tr>
			</tbody>
		</table>
		<script type="text/javascript">
			function submitform()
			{
  				document.themeChangeForm.submit();
			}
		</script>
		<h1>Registration Form</h1><br />

		<form:form commandName="Registration">
		<table>
			<tr><td colspan="2"><form:errors path="*" cssStyle="color : red;"/></td></tr>
			<tr><td>Name : </td><td><form:input path="name" /></td></tr>
			<tr><td>Username : </td><td><form:input path="username" /></td></tr>
			<tr><td>Email : </td><td><form:input path="email" /></td></tr>
			<tr><td>Phone : </td><td><form:input path="phone" /></td></tr>
			<tr><td>Password : </td><td><form:password path="password" /></td></tr>
			<tr><td>Retype Password : </td><td><form:password path="rePassword" /></td></tr>

		</form:form>
	</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	<title>Registration Confirmation Page</title>
	<link rel="stylesheet" href="<spring:theme code="css"/>" type="text/css" />
</head>
<body>
	<h1>Registration has been completed with following details :</h1> <br>
	Name : ${Registration.name}.<br>
	Username : ${Registration.username}. <br>
	Email : ${Registration.email}.<br>
	Phone : ${Registration.phone}.<br>
	Password : ${Registration.password}.
</body>
</html>

index.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<jsp:forward page="/registration.htm"></jsp:forward>

messages.properties


password.notmatch= Password and Retype Password does not match.

field.name.empty=Name field is mandatory.
field.username.empty=Username field is mandatory.
field.email.empty=Email field is mandatory.
field.phone.empty=Phone field is mandatory.
field.password.empty=Password should not be empty.
field.rePassword.empty=Retype Password should not be empty.

field.phone.length=Phone number is not valid. Should be of length 10.
field.phone.NAN=Phone number should be a number.

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>HelloWorldExampleWithSpring3MVCInEclipse</display-name>
<servlet>
<servlet-name>Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Servlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Output Screenshots

                Download Theme Resolver     +   Spring_mvc_jar

Filed in: Z-A Spring Codes

Comments are closed.