Springmvc Getting Started

Source: Internet
Author: User

Lenotang's column old Xu Navigation

As a developer of the Java EE, we are basically developing Web-based application systems. In fact, workflow, state management, and validation are important functions that need to be addressed. The stateless nature of the HTTP protocol determines that these functions are not easy to implement. Spring's web framework is a way to help us solve these problems. With spring, we can have the Web framework automatically populate the model object with the requested parameters that are passed in, providing validation and error handling. You can also manage the state of objects that users create in a Web form. Before we get to know Springmvc, let's review the MVC.

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.

Let's look at the basic work flow 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.

How do you understand MVC? We give a realistic example, the earthquake was so terrible, the people all over the country one mind earthquake relief. Our beloved Premier Wen gave orders to the armed police commander to complete the arduous task of earthquake relief, so the armed police commander in accordance with the situation dispatched different types of special forces to different areas to go, and then the special forces to use a large and small tools to complete the task, and finally to the commander of a statistical chart, the commander was handed over to Wen Jiabao. Let's analyze that this symbol does not conform to the MVC design pattern. Here, Premier Wen is the client, the armed police commander is the front controller, the Commando is the back-end controller, the tool used by the Commando is the model, the final hand-handed statistical chart is the view.

Now everyone should be able to understand MVC's design ideas. Take our familiar struts framework, the front controller is Actionservlet, the back-end controller is the action. The mapping of the requested URL and the backend controller is <action-mappings on Struts-config.xml > Inside configuration, the model object is what we usually write dao/dto, the returned view type is usually JSP.

So, what about spring MVC? Let's say it by the first place. The first front-end controller to accept this request is called Dispatcherservlet, and the backend controller is called the controllers. Called Handmapping, which handles the request URL and back-end controller mappings, has several types, is 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. Just 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.

As we learn knowledge, we should pay attention to the use of analogy migration method. Some people say, I learned struts, but learn not to SPRINGMVC. This is not justified. Because the ideas are exactly the same. So, we just need to learn the different places they can be. OK, let's run one of the simplest examples to give you an intuitive understanding of the basic steps of building a SPRINGMVC. We should compare with struts while running.

(1) Build Dynamic Web Engineering, importing spring the jar package.

(2) Configure Dispatcherservlet

Dispatcherservlet is the core of SPRINGMVC, registering the following servlet registration information in Web. Xml. Be sure to remember: The servlet, like a companion, wants to get married and register first!

<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) writing a controller , do the core configuration file, and configure the URL and Controller the mapping

Package com.wepull.test;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import Org.springframework.web.servlet.ModelAndView;

import Org.springframework.web.servlet.mvc.Controller;

Public class Hellocontroller implements controller{

Public Modelandview HandleRequest (HttpServletRequest request,

HttpServletResponse response) throws Exception {

Request.setattribute ("Hello", "Welcome to spring!");

return New Modelandview ("Welcome");

}

}

We know that struts has a core configuration file in XML format, SPRINGMVC of course, 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, which does not need to be explicitly declared, but it is very clear after the declaration which mapping processor--<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--

<bean name= "/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 resolver to associate a controller with a JSP together.

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

<bean id= "Viewresolver"

class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >

<property name= "prefix" value= "/web-inf/jsp/"/>

<property name= "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. Because the view named welcome is in the Modelandview returned by Hellocontroller, Internalresourceviewresolver looks for the view at/web-inf/jsp/welcome.jsp.

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

/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 ">

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>

<title>hello world!</title>

<body>

${hello}

</body>

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

In contrast, we found that SPRINGMVC is similar to struts. There are only two mappings, and the SPRINGMVC is relatively flexible. What are the two places?

(1) Mapping of URLs and actions ( back-end controllers) .

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

Map a controller to a URL based on the name of the controller

--simpleurlhandlermapping

To map a controller to a URL with a collection of properties defined in the context configuration file

--commonspathmaphandlermapping

To map a controller to a URL by using metadata in the controller code

(2) Mapping of Logical view names and view objects.

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

Resolves a logical view name to a view bean in a dispatcherservlet application context

--resourcebundleviewresolver

Resolves a logical view name to a View object in a Resourcebundler

--xmlviewresolver

Parses the view bean from an XML file, which is separated from the Dispatcherservlet application context.

Well, today is an introduction to SPRINGMVC. It is recommended that struts and SPRINGMVC be compared to study, and that the effect will be better. Share with others and brainstorm. I hope we can all learn to be happy and work at your liking. See you next time.

Springmvc Getting Started

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.