Spring configuration notes in javaEE and javaeespring Configuration

Source: Internet
Author: User

Spring configuration notes in javaEE and javaeespring Configuration

0 JavaEE project directory

0.1 WebContent

The main directory of the project. You can name it yourself when creating a project in eclipse. The content of this folder will be published to tomcat's webapps during deployment.

In this directory, you can create a JS/CSS/JSP folder and index. jsp as the front-end content accessed by the user. Servlet and springMVC will forward the front-end requests to the background java through the so-called forwarder.

0.1.1 WEB-INF

(0) The WEB-INF folder is not accessible through a URL

(1) lib: put a third-party jar package

(2) classes: the compiled files will be put here during release.

(3) web. xml: deployment descriptor of a Web application. when a project is started, the web Container first reads this configuration for a series of configurations.

 0.2 src

Source file path, which generally stores java source files. In eclipse, you can right-click "-Property-Java Build Path" to change the Path. For example, add some folder paths with configuration files, such as resource/spring. xml.

0.3 build/classes

You can also right-click "-Property-Java Build Path" in eclipse to change the Path. These files will be moved to WebContent/WEB-INF/classes at release.

0.4 General Project Structure

 

1 web. xml

1.1 Loading Order

The loading sequence of web. xml is:Context-param-> listener-> filter-> servlet. The actual Program Calling sequence between the same types is called according to the corresponding mapping Sequence.

1.2 context-param

<! -- Used to set the context parameter contextConfigLocation and specify the location of spring-related files --> <context-param> <param-name> contextConfigLocation </param-name> <param-value> classpath: spring. xml </param-value> </context-param> <! -- The parameter set here can be obtained using getServletContext (). getInitParameter ("contextConfigLocation") in servlet -->

1.3 listener

<! -- Enable the spring Function --> <listener-class> org. springframework. web. context. ContextLoaderListener </listener-class> </listener>

<! -- Prevent memory overflow listener --> <listener-class> org. springframework. web. util. IntrospectorCleanupListener </listener-class> </listener>

ContextLoaderListener is based on the Web context-level listener: when the server is started,

(1) create a context object

(2) read the contextConfigLocation parameter, load the Spring file, create the Bean, and put it into the context object.

(3) Place the context object in the ServletContext (that is, the global variable of Java Web ).

1.4 filter

<! -- Configure the character set filter --> <filter-name> encodingFilter </filter-name> <filter-class> org. springframework. web. filter. characterEncodingFilter </filter-class> <init-param> <param-name> encoding </param-name> <param-value> UTF-8 </param-value> </init- param> </filter> <! -- Encoding mapping of the configuration item --> <filter-mapping> <filter-name> encodingFilter </filter-name> <url-pattern>/* </url-pattern> </filter -mapping>

 1.5 servlet

<! -- Configure spring mvc --> <servlet-name> springMvc </servlet-name> <servlet-class> org. springframework. web. servlet. dispatcherServlet </servlet-class> <init-param> <param-name> contextConfigLocation </param-name> <param-value>/WEB-INF/spring-mvc.xml </param-value> </init-param> <load-on-startup> 1 </load-on-startup> </servlet> <! -- Configure spring mvc mapping --> <servlet-mapping> <servlet-name> springMvc </servlet-name> <url-pattern>/</url-pattern> </servlet- mapping>

The load-on-startup element specifies the order in which the servlet is loaded when the web application starts. Its value must be an integer. If its value is a negative integer or the element does not exist, the container will load the servlet when the servlet is called. If the value is a positive integer or zero, the container loads and initializes the servlet during configuration. The container must first load the servlet if the value is small.

 

2 DispatcherServlet and ContextLoaderListner

 DispatcherServletIt is mainly used for duty scheduling and is mainly used for controlling the process. Its main responsibilities are as follows:

1. File Upload parsing. If the request type is multipartMultipartResolverParse uploaded files;

2. map requests to the processor through HandlerMapping, as shown in figureBeanNameUrlHandlerMappingMap the URL to the Bean name.

3. HandlerAdapter supports multiple types of processors (processors in HandlerExecutionChain );

4. Use ViewResolver to parse the logical view name to a specific view. For example:InternalResourceViewResolverMap the logical view name to the jsp view.

5. localized parsing and rendering of specific views;

6. If an exception occurs during execution, HandlerExceptionResolver will be handed over for parsing.

DispatchServletCreates the Spring application context and loads the configuration file. DispatchServlet loads beans containing Web components, such as controllers, view parsers, and processor ing. You can manually specify the location of the configuration file. WhileContextLoaderListnerLoad other beans in the application, usually the middle layer and data layer components that drive the application backend. Load according to the context parameter contextConfigLocation.

 

For more information about WebContextLoaderListener and DispatcherServlet, see.

 

3. spring theoretical knowledge

3.1 spring Core

The core of the Spring framework is the Spring container. The container is responsible for managing the lifecycle of components in the application. It creates these components and ensures that their dependencies are satisfied. Spring comes with multiple container implementations, which can be categorized into two different types.

Bean factory: the simplest container that provides basic DI support, defined by the org. springframework. beans. factory. beanFactory interface.

Application context: it is built based on BeanFactory and provides services at the application framework level, which is defined by the org. springframework. context. ApplicationContext interface. Spring comes with multiple types of application context. AnnotationConfigWebApplication: loads Spring Web context from one or more java-based configuration classes. XmlWebApplicationContext: loads context definitions from one or more XML configuration files under a Web application. After the application context is ready, you can call the getBean method of the context to obtain the bean from the container.

Spring is committed to simplifying enterprise-level java development and promoting loose code coupling. The key to success lies in DI and AOP. DI facilitates the decoupling between application objects, while AOP can implement the decoupling between cross-cutting concerns and the objects they affect.

DI is a way to assemble application objects. With this method, objects do not need to know where dependencies come from or how dependencies are implemented. AOP helps applications collect logic that is scattered everywhere, that is, the aspect. Features distributed in multiple places in an application are called cross-cutting concerns, such as logs, security, cache, and transaction management. In general, these cross-cutting concerns are conceptually separated from the business logic of the application. separating them is exactly the problem to be solved by AOP.

The Bean types are as follows.

Singleton: creates only one bean instance for the entire application.
Prototype: A new instance is created each time it is injected or obtained through the Spring application context.
Session: Creates a bean instance for each Session in a Web application.
Request: In a Web application, create a bean instance for each Request.

 

 3.2 Web Spring

Spring is usually used to develop Web applications. SpringMVC is implemented based on the MVC model and helps you build Web applications that are as flexible and loosely coupled as the Spring framework.

Three-tier architecture: UIL, BLL, DCL (User Interface Layer, Business Logic Layer, Data Control Layer ). This is different from MVC.

In most Java-based Web frameworks, all requests are sent through a front-end controller. In Spring MVC, DispatchServlet is the front-end controller. DispatchServlet queries the processor ing to send requests to different controllers. The Controller completes logical processing (delegated to the service) and transmits data information in the form of a model.

Build Spring MVC

1: Configure DispatchServlet and ContextLoaderListener. (It can be configured in web. xml or java)

2: Enable SpringMVC (XML or annotation can be used): Enable SpringMVC, enable component scanning, configure the JSP view parser, and configure static resource processing.

3: Write the Controller @ RequestMapping: annotation Url ing Url, process the Request, and pass the model to the view. The model data will be placed in the Request as the Request attribute.

4: Spring MVC advanced technology: one of them is File Upload. Data in multipart format splits a form into multiple parts, each of which corresponds to an input field, A part of binary data is allowed. DispatchServlet does not implement the multipart data parsing function. It delegates the parsing task to the implementation of the MultipartResolver interface. Spring has two built-in implementation classes, one of which is CommonsMultipartResolver. Spring provides the MultipartFile interface for processing multipart data. In form, enctype = "multipart/form-data" tells the browser to submit the form in the form of multipart data.

 

3.3 backend Spring

Spring's Data Access philosophy: One of Spring's goals is to allow us to follow the "programming for interfaces" in the OO principle during development ". Spring also supports data access. To avoid coupling between applications and specific data access policies, a well-written DAO should expose functions in the form of interfaces. In addition, the choice of persistence mode is independent of DAO.

Data Access templated: Spring's template class processes a fixed part of data access, controls transactions, manages resources, and handles exceptions. You only need to care about your data access logic.

Configure the Data source: the data source defined by the JDBC driver, the data source of the connection pool, and so on.

Using JDBC in Spring: you do not need to know the query languages of other frameworks. It is built on SQL. Using JDBC can better optimize the performance of data access, allow you to use all the features of the database; JDBC allows us to process data at a lower level.

Integrate Hibernate (ORM tool) in Spring)
1: The org. Hibernate. Session interface provides basic data access functions, such as saving, updating, deleting, and loading objects from the database.
2: The standard way to get the Session object is to use the SessionFactory interface implementation class, which is mainly responsible for opening, closing, and managing the Session.
3: we need to use a session factory bean in Spring to obtain the Hibernate SessionFactory.
4: After configuring the Session factory bean in the Spring application context, you can create your own DAO. You usually need to configure data sources, database connection properties, and scan packages.

 

3.4 Spring Integration

Message conversion converts the data produced by the Controller to the expressions serving the client. Spring comes with a variety of converters to meet common requirements for converting objects into expressions. (Convert data based on request header information)

Add the @ ResponseBody annotation to the Controller method. It tells DispatchServlet to consider the request header information and finds the message converter that can provide the desired expression form for the client.

Similarly, @ RequestBody can also tell Spring to find a message converter and convert the resource expression from the client to an object.

 

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.