Spring MVC design Pattern

Source: Internet
Author: User

The purpose of using MVC is to separate the implementation code for M and v so that the same program can use a different representation. For example, a batch of statistical data can be represented by histogram, pie chart. C exists to ensure the synchronization of M and V, and once M is changed, V should be updated synchronously.

MVC is a pattern of creating WEB applications using MVC (Model View Controller-View-Controller) design:
Model (models)
Represents the application core (such as a list of database records).
Is the part of the application that handles application data logic.
Typically, model objects are responsible for accessing data in the database.
View (views)
Display data (database records).
Is the part of the application that handles the display of data.
Typically views are created from model data.
Controller (Controllers)
Process input (writes to database records).
Is the part of the application that handles user interaction.
Typically the controller is responsible for reading data from the view, controlling user input, and sending data to the model

The MVC pattern also provides complete control over HTML, CSS, and JavaScript. MVC layering helps you manage complex applications because you can focus on one aspect at a time. For example, you can focus on view design without relying on business logic.  It also makes testing of applications easier. The MVC hierarchy also simplifies group development. Different developers can develop views, controller logic, and business logic at the same time.

ViewA view is an interface that the user sees and interacts with. For older Web applications, views are an interface of HTML elements, and in modern Web applications, HTML still plays an important role in the view, but new technologies are emerging, including Adobe Flash and like xhtml,xml/xsl, Some identity languages and Web services, such as WML. The benefit of MVC is that it can handle many different views of the application. There is really no real processing happening in the view, whether the data is stored online or an employee list, as a view, it is simply a way to output data and allow the user to manipulate it.
ModelModels represent enterprise data and business rules. Of the three parts of MVC, the model has the most processing tasks. For example, it may use a Component object such as EJBS and ColdFusion to process the database, the data returned by the model is neutral, that is, the model is independent of the data format, so that a model can provide data for multiple views, Because the code applied to the model can be reused by multiple views only once, it reduces the repetition of the code.
ControllerThe controller accepts the user's input and invokes the model and view to complete the user's needs, so when you click a hyperlink in a Web page and send an HTML form, the controller itself does not export anything and do any processing. It simply receives the request and decides which model component is called to process the request, and then determines which view to use to display the returned data.

MVC logically divides applications into model components , view Components , and controller components . The controller components can also be subdivided into: Front controller components and back-end controller components .

The basic workflow of MVC:  

    First, the client (usually the browser) makes a request. The first component to accept this request is typically a front-end controller. It gives different requests to different back-end controllers for processing, and in the back-end controller It can invoke the corresponding model object to handle the specific business logic, and finally return a specific view response to the client.

  The first front controller to accept this request is called Dispatcherservlet

  Back-end controllers called Controller

  called Handmapping that handles the request URL and back-end controller mappings (It has multiple types, is more flexible and is configured on an XML file)

  the model object that is responsible for business logic processing is usually the dao/dto component that we usually write (only its last return is more flexible, the Controller returns a Modelandview object to Dispatcherservlet, Modelandview can carry a view object, or it can carry the logical name of a View object.) If you are carrying the logical name of a View object, then Dispatcherservlet needs a viewresolver to find the view object used to render the response. Finally, Dispatcherservlet assigns the request to the view object specified by the Modelandview object. The View object is responsible for rendering the response returned to the customer. )

Run one of the simplest examples to give you an intuitive understanding of the basic steps of building a SPRINGMVC

(1) Create a Dynamic Web project and import the Spring jar package.
(2) Configuration Dispatcherservlet

Dispatcherservlet is the core of SPRINGMVC, registering the following Servlet registration information in Web. xml

<servlet>     <Servlet-name>Test</Servlet-name>   
<Servlet-class>Org.springframework.web.servlet.DispatcherServlet</Servlet-class>
   <Load-on-startup>1</Load-on-startup>
</servlet> <servlet-mapping> <Servlet-name>Test</Servlet-name>   <Url-pattern>*.do</Url-pattern> </servlet-mapping>

(3) Write the Controller, do the core configuration file, and configure the URL and controller mapping

 Packagecom.wepull.test;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.springframework.web.servlet.ModelAndView;ImportOrg.springframework.web.servlet.mvc.Controller; Public classHellocontrollerImplementscontroller{ PublicModelandview HandleRequest (httpservletrequest request, httpservletresponse response)throwsException {request.setattribute ("Hello", "Welcome to spring!" ); return NewModelandview ("Welcome" ); } } 

Create a new XML file under Web-inf: Test-servlet.xml. Note that the test here depends on the name of the servlet. When Dispatcherservlet is loaded, it will attempt to load the application context from this file.

<?XML version = "1.0" encoding = "UTF-8"?> <!DOCTYPE Beans Public "-//spring//dtd bean//en" "Http://www.springframework.org/dtd/spring-beans.dtd "> <Beans>     <!--The default mapping processor does not need to be explicitly declared, but it is very clear which mapping processor is used after the declaration -  
<BeanID= "Beannameurlmapping"class= "Org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">    </Bean>    <!--The name attribute here has two responsibilities, defining both the name of the Bean and the URL style that needs to be handled by the controller . -    <Beanname= "/hello.do"class= "Com.wepull.test.HelloController">    </Bean> </Beans>

It might be strange to set the Name property instead of the id attribute. This is because the URL contains the XML ID attribute illegal characters-especially the slash (/);

(4) Configure a view parser to combine the controller with the JSP.

Add the parser's configuration fragment to the test-servlet.xml above

<BeanID= "Viewresolver"class= "Org.springframework.web.servlet.view.InternalResourceViewResolver">        < Propertyname= "prefix"value= "/web-inf/jsp/" />        < Propertyname= "suffix"value= ". jsp" /> </Bean> 

Internalresourceviewresolver the name of the view returned by Modelandview with the prefix of the prefix property configuration, plus the suffix of the suffix property configuration at the end. If the view named Welcome is in the Modelandview returned by Hellocontroller, Internalresourceviewresolver will find the view at/web-inf/jsp/welcome.jsp /c3>.

(5) Write the JSP file that is presented to the user.

/web-inf/jsp/welcome.jsp

<%@ Page ContentType= "text/html; Charset=utf-8" %> <%@ Page iselignored= "false" %> <%@ taglib Prefix= "C"URI= "Http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "> <HTMLxmlns= "http://www.w3.org/1999/xhtml" >   <Head>   <Metahttp-equiv= "Content-type"content= "text/html; Charset=utf-8 " />   <title>Hello world!</title>   </Head>   <Body>   <H2>${hello}</H2>   </Body> </HTML> 

When you are done, start the server and enter http://locahost:8080/projectName/hello.do on the browser address bar to access it.

The mapping relationship in MVC handlermapping

There is a concept of a mapping processor (handlermapping) in Springmvc. It is actually a processor-mapped Bean used to assign a controller to a URL. Spring provides three useful implementations of handlermapping:

beannameurlhandlermapping        According to the controller's name simpleurlhandlermapping        commonspathmaphandlermapping        To map a controller to a URL by using metadata in the controller code  

the attempted parser in MVC Viewresolver

There is also the concept of a View parser (Viewresolver) in Springmvc. It determines how the logical view name of the Modelandview object resolves to a view Bean used to render the result to the user. There are four viewresolver implementations of Spring:

Internalresourceviewresolver        Resolves a logical view name into a View object rendered with a template file (such as a JSP and Velocity template)  beannameviewresolver The        logical view name into a Dispatcherservlet View Bean Resourcebundleviewresolver in the application context          resolves the logical view name to a View object  in a Resourcebundler Xmlviewresolver        

Spring MVC design Pattern

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.