Spring MVC – Multi Action 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

  • In case of MultiActionController we should not override handleRequest() and handleRequestInternals() methods. We should write custom methods with handleRequest signature. If you don’t want follow write same action name as method name then we should use MethodNameResolver.
CREATE TABLE `tutorial`.`emp` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `email` VARCHAR(45) NULL,
  `address` VARCHAR(45) NULL,
  PRIMARY KEY (`id`));
  • We can also use different method name in MultiActionController. MultiActionController have setMethodNameResolver() method, It will accept MethodNameResolver object. In MethodNameResolver (I) -> AbstractUrlMethodNameResolver (A) -> InternalPathMethodNameResolver (C) class we have setPrefix() and setSuffix() method.

Create Java Web Project

  • Open Eclipse
  • Go to File -> New -> Dynamic Web Project
  • Create MVC-Controller4 project
  • Right click on project -> Build Path -> Configure Build Path -> Libraries tab -> Add External JARs (Used 2.X jars)
    • commons-logging-X.X.jar
    • mysql-connector-java-X.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 -->
	<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings">
			<props>
				<prop key="/empsave.code">EmpController</prop>
				<prop key="/empupdate.code">EmpController</prop>
			</props>
		</property>
	</bean>

	<!-- controller -->
	<bean id="EmpController" class="com.codeFactory.controller.EmpController">
		<!-- uncomment below code when you want custom name.
		Your method name should be <prefix>action_name<suffix>.
		In our scenario it should be CodeFactoryempsaveCRUD and CodeFactoryempupdateCRUD -->
		
		<!-- <property name="methodNameResolver">
			<bean class="org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver">
				<property name="prefix" value="CodeFactory" />
				<property name="suffix" value="CRUD" />
			</bean>
		</property> -->
	</bean>

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

EmpController.java

package com.codeFactory.controller;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

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

	static Connection con;
	
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tutorial", "root", "root");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/* If we uncomment "methodNameResolver" code in xml file
	then method name must be based on prefix and suffix
	Ex. Method should be CodeFactoryempsaveCRUD intead of empsave */
	public ModelAndView empsave(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String address = request.getParameter("address");
		
		PreparedStatement ps = con.prepareStatement("INSERT INTO EMP (name, email, address) VALUES (?, ?, ?)");
		ps.setString(1, name);
		ps.setString(2, email);
		ps.setString(3, address);
		int i = ps.executeUpdate();
		
		ModelAndView modelAndView = null;
		if(i != 0) {
			modelAndView = new ModelAndView("success");
		} else {
			modelAndView = new ModelAndView("fail");
		}
		
		return modelAndView;
	}
	
	public ModelAndView empupdate(HttpServletRequest request, HttpServletResponse response) throws Exception {
		int id = Integer.parseInt(request.getParameter("id"));
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String address = request.getParameter("address");
		
		PreparedStatement ps = con.prepareStatement("UPDATE EMP SET name=?, email=?, address=? WHERE id=?");
		ps.setString(1, name);
		ps.setString(2, email);
		ps.setString(3, address);
		ps.setInt(4, id);
		int i = ps.executeUpdate();
		
		ModelAndView modelAndView = null;
		if(i != 0) {
			modelAndView = new ModelAndView("success");
		} else {
			modelAndView = new ModelAndView("fail");
		}
		return modelAndView;
	}
}

empsave.jsp

<h2>Employee Save</h2>
<form action="./empsave.code">
	<pre>
		Name: <input type="text" name="name">
		Email: <input type="text" name="email">
		Address: <input type="text" name="address">
		<input type="submit" value="Save">
	</pre>
</form>

empupdate.jsp

<h2>Employee Update</h2>
<form action="./empupdate.code">
	<pre>
		Id: <input type="text" name="id">
		Name: <input type="text" name="name">
		Email: <input type="text" name="email">
		Address: <input type="text" name="address">
		<input type="submit" value="Save">
	</pre>
</form>

success.jsp

<h3>Save or Update success.</h3>

fail.jsp

<h3>Save or Update fail.</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