Spring MVC and Spring summary

Source: Internet
Author: User

1. Why use spring?

1). Easy to decouple and simplify development

With the IOC container provided by spring, dependencies between objects can be controlled by spring, avoiding excessive program coupling caused by hard coding.

2). Support for AOP programming

The AOP functionality provided by spring facilitates aspect-oriented programming, such as performance monitoring, transaction management, logging, and so on.

3). Declarative Transaction Support

4). Easy integration of a variety of excellent frameworks

5). Reduce the difficulty of using Java EE APIs

such as jdbc,javamail, remote invocation, etc. provides a simple package

2. What is the IOC and why use the IOC?

IOC full name Iversion of controller, inversion of control.

The idea is that you don't have to create an object, you just need to describe how it was created. you do not assemble your components and services directly in the code, but the configuration file describes which components require which services, and then a container (the IOC container) is responsible for assembling them.

It can guide us to design a loosely coupled, better program.

3. What is AOP and why use AOP?

AOP Full Name: aspect-oriented programming, face-slicing programming.

AOP, aspect-oriented programming, is to extract reusable functionality, and then weave these common functions into the application at the right time, such as transaction management , permissions control , logging , performance statistics, and so on.

AOP does not help us solve any new problems, it just provides a better way to solve existing problems with less effort, making the system more robust and more maintainable.

4. What is Spring's transaction management?

A transaction is a uniform commit or rollback operation for a series of database operations (such as inserting multiple data), and if the insert succeeds, it succeeds, and if there is an exception in the middle, all actions before the rollback. This prevents dirty data from occurring and prevents problems with database data.

In development, transaction management is generally done to avoid this situation.

Spring's declarative transactions typically refer to the configuration of a transaction in a configuration file, including a number of declarative properties, which are used by spring proxies to help you do the proxy, without the need to write additional code, as long as it is declared in the spring configuration file ; usually used in the operation of the database;

A programmatic transaction is a hard-coded way of doing transactions , which requires writing code, the logic in the transaction can be customized, it can be a database, or it can be another operation.

Spring also has its own transaction management mechanism, typically managed using Transactionmananger, which can be done through spring injection.

5. The spring framework supports the following five types of bean scopes:

Singleton: Default value, the bean has only one instance in each spring IOC container.

Prototype: the definition of a bean can have multiple instances.

Request: Each HTTP request creates a bean that is only valid in the case of a web-based spring ApplicationContext.

Session: In an HTTP session, a bean definition corresponds to an instance. This scope is valid only in the case of a web-based spring ApplicationContext.

Global-session: In a global HTTP session, a bean definition corresponds to an instance. This scope is valid only in the case of a web-based spring ApplicationContext.

6. What is the Spring MVC framework?

Spring is equipped with a full-featured MVC framework for building Web applications. Spring makes it easy to integrate with other MVC frameworks, such as the struts,spring MVC framework, which cleanly isolates business objects and control logic with control inversion. It also allows binding of request parameters and business objects in a declarative manner.

Spring MVC is an MVC-based web framework. Spring MVC is a module of the spring Framework, and SPRINGMVC and spring do not need to be consolidated through an intermediate integration layer.

7. How to enable annotations:

<context:annotation-config/>

if using <context:component-scan base-package= "Com.tgb.web.controller.annotation" > </context: Component-scan> the above content can be omitted

8. Spring MVC Request Flow:

First step: Initiating a request to the front-end controller (Dispatcherservlet)

Step Two: Front controller request handlermapping Find handler can be found based on XML configuration, annotations

Step Three: Processor mapper handlermapping back to the front-end controller Handler

Fourth step: The front controller calls the processor adapter to execute the handler

Fifth Step: Processor adapter to perform handler

Sixth step: Handler execution completes to the adapter return Modelandview

Seventh Step: The processor adapter returns Modelandview to the front-end controller. Modelandview is an underlying object of the SPRINGMVC framework, including model and view

Eighth step: The front controller requests the view parser to parse the view and parse it into a real view (JSP) based on the logical view name.

Nineth Step: View Resolver to Front controller return view

Tenth step: Front controller for view rendering . View rendering fills the model data (in the Modelandview object) into the request field

11th Step: Front controller responds to user results

9. Configuration of Web. xml

10. Processor Mapper and adapter for annotations

After spring3.1, use the org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping annotation mapper.

Use the Org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter annotation adapter after spring3.1.

using Mvc:annotation-driven instead of the top annotation mapper and annotation adapter configuration

Spring and MyBatis integration process

First step: Integrate the DAO layer

MyBatis and spring are integrated to manage the Mapper interface through spring.

Use Mapper's scanner to automatically scan the Mapper interface for registration in spring.

Step Two: Integrate service tiers

Manage service interfaces through spring.

Configure the service interface in the spring configuration file by using the configuration method.

Implement transaction control.

Step Three: Integrate SPRINGMVC

Since SPRINGMVC is a spring module, no consolidation is required.

The main configurations are:

1). mybatis configuration file sqlmapconfig.xml configuration alias Auto -Scan (entity Class)

2). Mapper Scanner (interface, database access interface)

3). database Connection Pool Configuration

4). Declarative transaction Configuration

5). Enable annotation scanning: <context:component-scan base-package= "Cn.itcast.ssm.controller" ></context:component-scan>

6). Configure the note Mapper and adapter: <mvc:annotation-driven></mvc:annotation-driven>

7). View parser: <bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >

8). Configuration control class: Dispatcherservlet Front Controller

9). Configure Spring Profile Load class: Classloadlistener

The front controller loads the processing mapper, adapter, view resolver, and other components from the top file, and uses the default loaded dispatcherserlvet.properties if it is not configured in Springmvc.xml.

13. View parser configuration prefix and suffix:

Sqlmapconfig.xml,mybatis your own configuration file.

15. Configure the data source:

16. Transaction control (Applicationcontext-transaction.xml), using the Spring declarative transaction control method in Applicationcontext-transaction.xml.

17. Load Spring Configuration

18. Static resource access is not blocked:

<resources mapping= "/resources/**" location= "/resources/"/>

<resources mapping= "/images/**" location= "/images/"/>

<resources mapping= "/js/**" location= "/js/"/>

The role of @RequestMapping

1). URL mapping

2). Narrowing Request Mapping

3). Restricting HTTP request methods

The return value of the Controller method

20.1 back to Modelandview

At the end of the method, define the Modelandview and set the model and view separately.

20.2 return String

If the Controller method returns a string,

1). Represents the return logical view name. True view (jsp path) = prefix + logical view name + suffix

2). REDIRECT redirect: Return string format: "Redirect:queryItem.action"

3). Forward page Forwarding: return string format: "Forward:queryItem.action"

20.3 return void

You can define the request and response on the controller method parameters, using request or response to specify the response result:

1). Use the request to turn to the page as follows: Request.getrequestdispatcher ("page path"). Forward (request, response);

2). Can also be redirected via Response page: response.sendredirect ("url")

3). You can also specify the response result via response, such as the response JSON data as follows:

Response.setcharacterencoding ("Utf-8");

Response.setcontenttype ("Application/json;charset=utf-8");

Response.getwriter (). Write ("JSON string");

21. Parameter binding:

21.1 Types supported by default

You can use these objects directly by defining objects of the type below on the controller method parameters. During parameter binding, if the type below is encountered, it is bound directly.

1). HttpServletRequest: Obtaining request information through the Requester object

2). HttpServletResponse: Handling response information through response

3). HttpSession: Gets the object stored in the session by the Session object

4). Model/modelmap:model is an interface, MODELMAP is an interface implementation. Function: Populates the model data with the request domain.

21.2 Simple Types

Binds the parameters of a simple type by @requestparam.

If you do not use @requestparam, you require the request to pass in the parameter name consistent with the Controller method's formal parameter name before binding succeeds.

If you use @requestparam, you do not have to restrict the request to pass in parameter names consistent with the Controller method's formal parameter names.

The Required property specifies whether the parameter must be passed in, and if it is set to true, there are no incoming parameters and an error is given.

21.3 Pojo Bindings

The name of input in the page is identical to the property names in the controller's Pojo parameter, binding the data in the page to Pojo. (usename,age; no user.username,user.age required)

21.4 Custom parameter bindings implement date type binding

For a Pojo object in a controller parameter, a custom parameter binding is required if there is a date type in the attribute. The request date data string is converted to a date type, the type of date to convert is consistent with the type of the date attribute in Pojo.

Spring MVC vs. Struts2

1). STRUTS2 is class-level interception, a class corresponds to a request context, SPRINGMVC is a method-level intercept, a method corresponds to a request context, and the method corresponds to a URL, so the schema itself SPRINGMVC Easy to implement restful URLs

2). From the above reasons, Springmvc method is basically independent of the request response data, requests for data through parameters, processing results through the MODELMAP to the framework, the method does not share variables, and Struts2 make a mess, although the method

is also independent, but all of its action variables are shared, which does not affect the program's operation, but gives us trouble coding the program, creating an action every time a request is made, and an action object corresponding to a request context.

3). Since the Struts2 needs to be encapsulated for each request, the variables of the servlet life cycle, such as request,session, are encapsulated into a single map, supplied for each action, and thread-safe, so in principle, is more memory-intensive.

4). SPRINGMVC integrates Ajax, it is very convenient to use, only one annotation @responsebody can be implemented, and then directly return the response text, and STRUTS2 interceptors integrated Ajax, in action in general must install plug-ins or their own

It is also relatively inconvenient to use it when writing code is integrated.

5). Springmvc-oriented method development (closer to service interface development), STRUTS2 class-oriented development.

6). SPRINGMVC can be developed in a single case, STRUTS2 can only be developed in many cases.

23. Garbled Handling

1). Post garbled

Add post garbled filter:characterencodingfilter in Web. XML

2). There are two garbled methods for GET request Chinese parameter:

A. Modifying the Tomcat configuration file add encoding is consistent with the engineering code as follows:

<connector uriencoding= "Utf-8" connectiontimeout= "20000" port= "8080" protocol= "http/1.1" redirectport= "8443"/ >

B. Re-encode the parameters:

String userName = new String (Request.getparamter ("UserName"). GetBytes ("Iso8859-1"), "Utf-8")

Iso8859-1 is the tomcat default encoding, and the Tomcat encoded content needs to be encoded by utf-8

24. Collection type Binding

1). Array bindings:

Controller method parameters using: (integer[] itemId)

Page Unified use: ItemId as Name

2). List binding:

The Pojo property is named: Itemslist

Page: Itemslist[index]. Property name

3). Map bindings:

The Pojo property is named: map<string, object> iteminfo = new hashmap<string, object> ();

Page: <td> name: <inputtype="text"name="iteminfo[' name ']"/>

Spring Checksum

1). In the project, most of the front-end checks are usually used, such as the JS check in the page. For higher security requirements, it is recommended to validate on the service side.

2). SPRINGMVC uses Hibernate's check frame validation (no relationship with hibernate).

Check the idea: the page submits the request parameter, requests to the Controller method, uses the validation to verify. If the checksum error occurs, the error message is displayed to the page.

26. Data echo

1). @ModelAttribute can also upload the return value of the method to the page: add annotations to the method @modelattribute

2). Use the model in the simplest way, without @modelattribute:model.addattribute ("id", id);

3). SPRINGMVC defaults to echo pojo data. Pojo data is passed into the controller method, Springmvc automatically puts Pojo data into the request domain, key equals Pojo type (lowercase first letter)

4). public string Testparam (PrintWriter out, @RequestParam ("username") string username) {//out Direct output

27. Exception Handling

SPRINGMVC provides a global exception handler (a system with only one exception handler) for uniform exception handling.

The system encounters an exception, is thrown manually in the program, DAO throws to the service, the service to the Controller, the controller throws to the front-end controllers, and the front controller calls the global exception handler.

28. Uploading Images

1). When submitting enctype= "Multipart/form-data" data in a page form, you need to SPRINGMVC parse the data for the multipart type.

2). Configure the multipart type resolver in Springmvc.xml.

3). Method used: Multipartfile Attach (Single file upload) or multipartfile[] Attachs (multiple file uploads)

JSON processing

1). Load the JSON transform JAR package: Springmvc using Jackson's package for JSON conversion (@requestBody and @responsebody using the package below for JSON transfer)

2). Configure the JSON converter. Add Messageconverters to the note adapter Requestmappinghandleradapter. If you use <mvc:annotation-driven/>, you will automatically join.

3). Ajax

4). Controller (responsebody, Requestbody)

5). Note that Ajax contenttype if not set to the JSON type, the passed argument is of type Key/value. When set above, the JSON type is passed.

See: http://www.cnblogs.com/Jtianlin/p/5224885.html

30. Interceptors:

1). Define the interceptor to implement the Handlerinterceptor interface. Three methods are available in an interface.

A. Prehandle: Before entering the handler method, it is used for identity authentication, identity authorization, such as authentication, if the authentication by means that the current user does not log in, need this method to intercept no longer execution down

B. Posthandle: After entering the handler method, go back to Modelandview before execution , the scenario starts from Modelandview: Upload common model data (such as menu navigation) here to the view, You can also specify a view here uniformly

C. aftercompletion: Execution handler complete execution of this method, application scenario: Unified exception handling, unified log processing

2). Interceptor Configuration:

A. For handlermapping configuration (not recommended): The SPRINGMVC Interceptor is set for handlermapping, and if blocking is configured in a handlermapping, the Handlermapping Mapping the successful handler

The interceptor is eventually used. (generally not recommended)

B. A global-like interceptor: SPRINGMVC is configured like a global interceptor, and the SPRINGMVC framework injects a similar global interceptor into each handlermapping

How to enable annotations:

<context:annotation-config/>

if using <context:component-scan base-package= "Com.tgb.web.controller.annotation" > </context: Component-scan> the above content can be omitted

using Mvc:annotation-driven instead of annotation mapper and annotation adapter configuration

Spring MVC and Spring summary

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.