How to do it...

Let us build a simple web application using the Spring MVC concept:

  1. Open web.xml and register the main servlet handler of our Spring MVC application, which is org.springframework.web.servlet.DispatcherServlet.
<servlet> 
  <servlet-name>ch02</servlet-name> 
  <servlet-class> 
    org.springframework.web.servlet.DispatcherServlet 
  </servlet-class> 
  <load-on-startup>1</load-on-startup> 
</servlet> 
<servlet-mapping> 
  <servlet-name>ch02</servlet-name> 
  <url-pattern>*.html</url-pattern> 
</servlet-mapping> 
Be cautious with the <url-pattern> in web.xml because it is where DispatcherServlet picks the correct format for its request URLs. The pattern *.html means the main servlet will recognize all URL paths with a view extension of .html.
  1. In the previous recipes, the XML bean definition file was created on the Classpath level. It is an option to import this file or just move the file to WEB-INF and name it ch02-servlet.xml. Additional modules such as Spring Web, Spring WebMvc, Spring Tx, and Spring AOP must be included with their dependencies:
<?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.xsd 
http://www.springframework.org/schema/context    
  http://www.springframework.org/schema/context 
/spring-context.xsd 
   http://www.springframework.org/schema/mvc 
     http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 
     
</beans>
  1. This ch02-servlet.xml file will be the first servlet-specific context or root context definition of the DispatchServlet. This servlet needs this context to instantiate WebApplicationContext, which is Spring's root ApplicationContext, which manages controllers, view resolvers, resource bundle message configurators, and other MVC-specific requirements. To successfully create WebApplicationContext, the DispatcherServlet must first specify the location of the XML file through its contextConfigLocation parameter:
<servlet> 
  <servlet-name>ch02</servlet-name> 
  <servlet-class> 
    org.springframework.web.servlet.DispatcherServlet 
  </servlet-class> 
  <init-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>/WEB-INF/ch02-servlet.xml</param-value> 
  </init-param> 
</servlet> 
<servlet-mapping> 
  <servlet-name>ch02</servlet-name> 
  <url-pattern>*.html</url-pattern> 
</servlet-mapping> 
If the XML is named using the pattern <servlet-name>-servlet.xml, there is no need to configure contextConfigLocation, thus, Step 1 is enough.
  1. Save all files. Deploy the project using the Maven goals presented in Chapter 1, Getting Started with Spring. Observe if there are any container errors. If none, let us proceed with building the view layer of the application using the WebApplicationContext. First, inject the two most popular view resolvers of the MVC application, namely the org.springframework.web.servlet.view.InternalResourceViewResolver and org.springframework.web.servlet.view.ResourceBundleViewResolver. Open the ch02-servlet.xml and add the following details:
<bean id="viewResolverA" class="org.springframework.web.servlet 
.view.InternalResourceViewResolver"> 
        <property name="prefix" value="/WEB-INF/jsp/"/> 
        <property name="suffix" value=".jsp"/> 
        <property name="order" value="1"/> 
</bean> 
    
<bean id="viewResolverB" class="org.springframework.web.servlet 
.view.ResourceBundleViewResolver"> 
      <property name="basename" value="config.views"/> 
      <property name="order" value="0"/> 
</bean> 
  1. In order for InternalResourceViewResolver to work, create its lookup WEB_INFjsp directory, which is the static location of all its JSP pages.
  2. For ResourceBundleViewResolver to function, create its view.properties inside the srcmain esourcesconfig directory. All view names are required to be declared here and each must have two specific configuration details, which are the <view-name>.(class) and <view-name>.url. The <view-name>.(class) refers to the view type (for example, JSP, Tiles, JSON) of the rendition page while the <view-name>.url contains the context root path of the physical view page. Leave the file empty.
  3. The views, models, and transactions will be nothing without the @Controller. Create the first controller, MainController, inside the package org.packt.starter.ioc.controller. The class must contain a set of handler methods that directly deals with the request and response of the client. Each method has URL mapping through the method-level @RequestMapping annotation. Let us create a handler that outputs page-generated content (in the String type) on the page using @ResponseBody:
@Controller 
public class MainController { 
    
      @ResponseBody 
      @RequestMapping("/main.html") 
      public String pageGenerate(){ 
       
      String content = "<html>" 
            + "" + "<head><title>Ch02 MVC Web</title></head>" 
            + "" + "<body>This is Spring MVC Web!</body>" 
            + "" + "</html>" 
            + ""; 
      return content; 
} 
} 
  1. In order for the DispatcherServlet to recognize all the MVC components and annotations of the project, add the following important lines in the root context ch02-servlet.xml:
<context:component-scan base-package="org.packt.starter.ioc"/> 
<mvc:annotation-driven />
  1. The chosen root or core directory of the Classpath is org.packt.starter.ioc where all other sub-directories contain the MVC layers and components such as the controllers, services, repository, and model classes. Save all the files. Deploy the project. If there are no errors, open any browser and run https://localhost:8443/ch02/main.html. The output must be similar to the following:
  2. Let us add more handlers by adding the following methods to our MainController:
@RequestMapping("/intro.html") 
public String introPage(){ 
      return "intro"; 
} 
    
@RequestMapping("/welcome.html") 
public String welcomePage(){ 
      return "welcome"; 
} 
  1. The welcomePage() request handler requires a view name welcome from InternalResourceViewResolver. Add a JSP file named welcome.jsp in the WEB-INFjsp directory:
<%@ page language="java" contentType="text/html; 
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 
<!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>Insert title here</title> 
</head> 
<body> 
       <h1>Welcome!</h1> 
    <em>-- from InternalResourceViewResolver</em> 
</body> 
</html>
  1. The other handler, introPage(), calls a view name intro from ResourceBundleViewResolver. Add a JSP file named intro_page.jsp in the WEB-INFpage directory. The page must contain the following content:
<%@ page language="java" contentType="text/html; 
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 
<!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>Insert title here</title> 
</head> 
<body> 
   <h1>Introduction to Spring MVC Web</h1> 
   <em>-- from ResourceBundleViewResolver</em> 
</body> 
</html> 
  1. To recognize the logical view names, open views.properties and add the following details of the view name intro:
intro.(class)=org.springframework.web.servlet.view.JstlView 
intro.url=/page/intro_page.jsp 
  1. Save all the files. Deploy the project and check the Maven console to see whether there are errors. If there are none, open any browser and run https://localhost:8443/ch02/welcome.html and expect a result like this:

  1. Run https://localhost:8443/ch02/intro.html seperately and expect the following result:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.17.137