Decoupling view from the controller – HP Integrity NonStop H-Series User Manual

Page 116

Advertising
background image

Decoupling View from the Controller

So far, the controller is specifying full path of the view, thereby creating unnecessary dependency
between the controller and the view. Ideally, the view must be mapped using a logical name, so
that the view can be switched without changing the controller.

To decouple the view from the controller, complete the following steps:

1.

Modify the

EmpInfo-servlet.xml

file in the

EmpInfo/WebContent/WEB-INF

directory

to add the following bean to declare a new

ViewResolver

entry.

NOTE:

By default, XML files open in the XML Editor. The XML Editor has two views:

Design and Source view. Select the Source view.

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

After modification, the

EmpInfo-servlet.xml

file appears as:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean name="/insert.htm"
class="com.hp.empinfo.web.EmployeeController"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix"
value="/WEB-INF/jsp/"></property>
<property name="suffix"
value=".jsp"></property>
</bean>
</beans>

2.

Modify the

EmployeeController

class

EmpInfo/com/hp/empinfo/web/

EmployeeController.java

to decouple the controller from view using

ViewResolver

, as shown below:

Before modification:

return new ModelAndView("WEB-INF/jsp/insert.jsp", "now", now);

After modification:

return new ModelAndView("insert", "now", now);

After modification, the

EmployeeController.java

file appears as:

package com.hp.empinfo.web;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.util.Date;

public class EmployeeController extends SimpleFormController {

protected final Log logger = LogFactory.getLog(getClass());

116

Getting Started with Spring

Advertising
This manual is related to the following products: