Spring MVC – Base Command Controller | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

This image has an empty alt attribute; its file name is image-1.png

Spring Tutorial Index Page: Link

  • Command Controllers are used for validations, for execute interceptors, for applying I18N.
  • The ControllerClassNameHandlerMapping class is the convention-based handler mapping class, which maps the URL request(s) to the name of the controllers mentioned in the configuration.
  • For example, using below configuration, If URI
    • /empSave.code or /emp{any letter}.code is requested, DispatcherServlet will forward the request to the EmpController.
    • /emp.code is requested, DispatcherServlet will forward the request to the EmpController.
    • /Emp.code is requested where E is capital cased, DispatcherServlet will not find any controller and the server will throw 404 status error.

Create Java Web Project

  • Open Eclipse
  • Go to File -> New -> Dynamic Web Project
  • Create MVC-Controller5 project
  • Right click on project -> Build Path -> Configure Build Path -> Libraries tab -> Add External JARs (Used 2.X jars)
    • commons-logging-X.X.jar
    • spring-beans-X.X.X.jar
    • spring-context-X.X.X.jar
    • spring-core-X.X.X.jar
    • spring-web-X.X.X.jar
    • spring-webmvc-X.X.X.jar
  • Also, add these jars in WEB-INF/lib folder for runtime.
  • * You can find dtd information from spring-beans-X.X.X.jar -> org -> springframework -> beans -> factory -> xml -> spring-beans.dtd (line no 36 & 37)

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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">
	
	<display-name>MVC-Controller4</display-name>
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	
	<!-- default -->
	<servlet>
		<servlet-name>helloWorld</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>helloWorld</servlet-name>
		<url-pattern>*.code</url-pattern>
	</servlet-mapping>

</web-app>

helloWorld-servlet.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
	"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

	<!-- handler mapping -->
	<!-- first we have to request /emp.code because here we use ControllerClassNameHandlerMapping
	and it will code EmpController -->
	<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />

	<!-- controller -->
	<bean class="com.codeFactory.controller.EmpController"></bean>

	<!-- view resolver -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

EmpBean.java

package com.codeFactory.controller;

/**
 * @author code.factory
 *
 */
public class EmpBean {

	private String name;
	private String email;

	public String getName() {
		return name;
	}

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

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}

EmpController.java

package com.codeFactory.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

/**
 * @author code.factory
 *
 */
public class EmpController extends SimpleFormController {

	public EmpController() {
		setCommandName("form");
		setCommandClass(EmpBean.class);
		setValidator(new EmpValidator());
		setFormView("index");
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
			BindException errors) throws Exception {
		EmpBean empBean = (EmpBean) command;
		System.out.println(empBean.getName());
		System.out.println(empBean.getEmail());
		return new ModelAndView("success");
	}
}

EmpValidator.java

package com.codeFactory.controller;

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

/**
 * @author code.factory
 *
 */
public class EmpValidator implements Validator {

	@Override
	public boolean supports(Class arg0) {
		return true;
	}

	@Override
	public void validate(Object form, Errors errors) {
		EmpBean empBean = (EmpBean) form;
		if(empBean.getName().equals("")) {
			errors.reject("name", "Name is required.");
		}
		if(empBean.getEmail().equals("")) {
			errors.reject("email", "Email is required.");
		}
	}
}

index.jsp

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sform" %>

<h2>Employee page</h2>
<sform:form commandName="form">
<pre>
<sform:errors />
Name: <sform:input path="name" />
Email: <sform:input path="email" />
<input type="submit" value="Save" />
</pre>
</sform:form>

success.jsp

<h3>Success page.</h3>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s