Introduction to Spring MVC

Source: Internet
Author: User

Introduction to 1.Spring MVC

The Spring MVC Framework has an MVC framework that separates data, business, and presentation well by implementing the Model-view-controller pattern. From this perspective, Spring MVC is very similar to struts and Struts2. Spring MVC is designed around Dispatcherservlet, and Dispatcherservlet is responsible for distributing requests to specific handler. Process requests and go to corresponding views with configurable handler mappings, view resolution, locale, and theme resolution. The overall flow of Spring MVC request processing

A controller class is defined in spring3.x and must be marked with a @controller annotation. When the controller class receives a request, it looks for an appropriate processing method within itself to process the request. Use the @requestmapping annotation to map the method to a number of requests so that the method processes those requests. This method is like a method in a general class, and the method name parameter list and return value are not very restrictive like Struts2 frameworks. The method parameter list is specific and the return value is specific, which is not detailed here first. The purpose of this blog is to briefly describe how to quickly get started with the Spring MVC framework.

When a controller chooses a method that is appropriate for processing a request, the incoming request is passed in (depending on the type of the method parameter, it may be passed in with a different type), and the logic in the method is called for processing (or it can be called service to really handle). The method logic may also add or remove data from the parameter. When the processing method finishes processing, it is delegated to a view that handles the return value of the method. The return value of the handler does not represent the concrete implementation of the view, it can be just a string type, represents the view name, or even void (when spring MVC can find the default view based on the method name or the controller name). There's no need to worry that the return value is just the view name, and the view doesn't get the data you want to display. Because the method parameters are also available for the view. For example, if the processing method takes a map parameter, then the map can be obtained for the view as well.

The returned view name is returned to dispatcherservlet, which resolves the view name to a specific view implementation based on a view parser. The view parser here is a bean that implements the viewresolver excuse, and its task is to return a concrete implementation of the view (HTML, JSP, PDF, and so on).

2.Spring MVC version of HelloWorld

Next we use spring MVC to develop a most simple Web application. First create a dynamic Web Project. For convenience, we put all the jar packages in the Spring dist directory under the Web-inf/lib directory. I'm using the spring3.1.x version here. You will also need to add the commons-logging package.

Next, configure Dispatcherservlet in the Web. xml file to add the following fragment to the Web. xml file:

?
1234567891011 <servlet>    <servlet-name>hello</servlet-name>    <servlet-class>        org.springframework.web.servlet.DispatcherServlet    </servlet-class>    <load-on-startup>1</load-on-startup></servlet><servlet-mapping>    <servlet-name>hello</servlet-name>    <url-pattern>/</url-pattern></servlet-mapping>

Here we name Dispatcherservlet as Hello and let it load at the start of a Web project. Next we need to create a hello-servlet.xml spring configuration file under the Web-inf directory. The default file name recommended on the spring Official document is [Servlet-name]-servlet.xml file, where servlet-name is called Hello, so this file is called Hello-servlet.xml. In this file, you can define a variety of beans that spring MVC needs to use. It should be explained that the beans defined in the spring configuration file throughout the Web project can be inherited in this configuration file, which in turn is not true. Above, we will give all the requests to dispatcherservlet.

Now we define a controller class Hellocontroller:

?
12345678910111213141516 package springmvc.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;@Controllerpublic class HelloController {        @RequestMapping(value="/hello",method=RequestMethod.GET)    public String sayHello(Model model) {        model.addAttribute("msg", "Hello, World!");        return "hello";    }}

First, the @controller annotation indicates that the class is a controller, and then, in this case, the SayHello method handles only the get type of/hello request by @requestmapping annotations for the method SayHello which requests are processed.

The SayHello method receives a parameter of type Org.springframework.ui.Model MODEL,SPRINGMVC automatically encapsulates the request parameter into the model, and we can simply interpret the model as a map. We take the value of the person from the model in the method and print it, and then add an attribute msg to the model with a value of "hello,world! ", and then return the view name hello.

Next we need to configure a view resolver in the Spring MVC configuration file, and we'll look at the contents of Hello-servlet.xml:

?
12345678910111213141516171819202122 <?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:p="http://www.springframework.org/schema/p"    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">    <!-- 默认的注解映射的支持 -->    <mvc:annotation-driven />    <!--启用自动扫描  -->    <context:component-scan base-package="springmvc.controller" />    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/WEB-INF/jsp/" />        <property name="suffix" value=".jsp" />    </bean></beans>

There's nothing to say, but notice that the MVC namespace is added, followed by spring automatic scanning, and the default annotation mapping support is set. The key here is to explain the bean in the configuration file. Its type is the most commonly used view resolver in spring MVC, and of course there are many other types, as this blog focuses on a simple introduction to spring MVC, so it is not highlighted, and subsequent posts will be added. The prefix property refers to the view prefix, suffix is the view suffix, which is configured in. JSP, we return in the controller's method SayHello is Hello, and then combined with the configuration here, the corresponding complete view is:/web-inf/jsp/hello.jsp. Next we complete this view, we simply take out the information we put msg:

?
123456789101112 <%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!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=UTF-8"><title>hello.jsp</title></head><body>    ${msg}</body></html>

Next we deploy the app, we visit Http://localhost:8080/springmvc/hello, the contents of the view are displayed, and the contents of the MSG are removed:

Just a simple spring MVC web App is ok.

Introduction to Spring MVC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.