One of java learning is to build the spring framework step by step

preface

As a server-side developer, I always feel that I reject the framework. I always feel that any implementation logic is encapsulated in it. You only need to configure this and that. If there is a problem, you don't know how to troubleshoot it. Previously, even if you wrote a web program, you would rather use an embedded web server such as jetty to implement it and write your own servlet, I always feel that it is within my control from the main function, but this way is a little primitive. I also see that various open-source systems use spring to implement web services. Although the code can always be seen clearly, I still don't know how to build it step by step, so I took out a weekend to toss around, It turns out that this thing can crash an unfamiliar user. This article mainly introduces how I build a spring environment (in other words, I really can't tell spring from spring MVN), although it is a small skill in most web development.

The environment used in this article is a relatively new version of eclipse Luna + spring (according to the rule that I choose the version, I try not to use the latest version unless there are new functions, and then choose the one with a large number of users in the newer n versions. For example, the spring version selected in this article is 4.3.7. Release).

The following explains how to build such an environment step by step from the perspective of pure engineering. There is no principle. I guess that there is a principle. I haven't seen the source code.

Detailed steps

Step 1: create a maven project

This is a familiar process, but I generally don't recommend archetype, just create a simple project, The former always fails to create (creating archetype mode can make the IDE do more things). In fact, what is Maven project? In my opinion, it is just a java project with pom.xml, and then set the code path to Src / main / Java, so we just need the IDE to help us create a project with pom.xml, and we can write a dependency and build ourselves Parameters.

During configuration, in addition to filling in the correct group ID and artifact ID, the packaging is mainly selected as war, which can be run under Tomcat.

Step 2: modify project configuration

There are two configurations that need to be modified. Just pay attention to the appearance after modification:

1. Project facets: Although I don't know what to configure here, I have suffered from this again and again. Java to be configured here is more than 1.6 (preferably 1.7), and then select dynamic web module. The following interface appears below:

If it doesn't appear, you can check out the dynamic web module first, then save it, and then click Project facets again to select the dynamic web module. At this time, such an interface appears. Note that you'd better not select 3.0. You've encountered the incompatibility of 3.0 before, jdk1 Version 7 + 2.5 works normally.

Click "further configuration available..." to configure, modify the context directory to, and select generate web XML, save. As shown below:

At this point, you will see your project structure as shown in the figure below. There are three directories Java / resources / webapp under Src / main directory.

2. Configure the deployment assembly. The source and deploy path configured here means that the contents in the source directory will be copied to the Tomcat deployment directory / deploy path during project deployment. The to be configured here is shown in the figure below:

For example, the first one means that the source code under Src / main / Java directory in the project will be compiled and placed in the deployment directory / WEB-INF / classes directory, and the last one means that the Maven dependency of the project will be copied to the deployment directory / WEB-INF / lib directory. According to my observation, the deployment directory / WEB-INF / classes and deployment directory / WEB-INF / lib will be added to the classpath during the operation of Tomcat directory. Therefore, the configuration file and the compiled class file can be placed under classes and the dependent jar can be found when starting the Java program.

Step 3: Download spring dependencies

Spring has many jars, and the following dependencies are required for the most basic functions:

The versions used by different dependencies of spring should be consistent.

Step 4: write code

We write a simple controller that returns a "Hello ${username}" string.

Step 5: spring configuration file

Spring configuration files are generally called "ApplicationContext XML ", of course, this is not the default configuration name of spring, but it needs to be in the web XML specifies that here we only configure the spring configuration file. In fact, spring configuration mainly configures some beans. Here we don't need to create any beans for the time being, so we just need to add a scan path.

This configuration file is generally placed in the Src / main / resources directory. Previously, we have configured the settings of deployment copy. It will be copied to the WEB-INF / classes / directory during deployment. Here, only two items are configured. Context: annotation config tells spring to identify the annotation configuration, and the following scan indicates the package of the class to be scanned.

Step 6: configure web xml

web. XML enables us to automatically generate the configuration in the second step. It is the configuration that Tomcat needs to rely on when starting. Some servlets, filters, listeners, etc. can be configured. For the simple use of spring, generally only one servlet is configured, and all requests have this servlet for routing processing.

You can see that we only configure a dispatcher servlet, which handles all URL requests. It initializes the required configuration file and looks for ApplicationContext under classpath XML, which has just been introduced. During deployment, the files under resources will be copied to the WEB-INF / classes directory and added to the Java launched classpath.

Step 7: deploy Tomcat

First, you need to download a tomcat, Tomcat 7 X is a good choice. Because Tomcat is green (most Java implementations are green), you can decompress it directly and configure it in eclipse. Add a Tomcat instance in window - > server - > runtime environment in eclipse. Note that you need to select JDK and the version supported by the current JDK.

Then find servers in the lower taskbar. If not, you can select servers in window - > show view to add them. After adding them, you can create a new server here. Select the Tomcat instance just created, and then select one from the resources of avaliable to add it to the configured on the right (avaliable is generated according to whether there is web.xml in the project).

Step 8: configure Tomcat

Double click the newly created Tomcat server to enter the overview page. This page can configure the project to run the Tomcat instance. The main configurations include port number, deployment directory, etc. if the ports or files do not conflict, try not to modify them. One thing that needs to be modified is to check "publish module contexts to separate XML files" in server options, Although I don't know what this is for, the lessons of blood and tears tell me to choose this and save it directly.

Step 9: start Tomcat

Someone may want to ask why there is no plug-in configured with Tomcat on eclipse. Where can I start Tomcat! Can't it be without that cat's head? To be honest, configuring the cathead often encounters network problems and fails, so I don't try anymore. Instead, I can complete all the functions that the cathead can do by right clicking the Tomcat instance created in step 7. Why configure the plug-in? Right click start, and then pray that there will be no errors when starting. If there are errors, Google it. Basically, some people have stepped on the pit for spring problems.

Step 10: Test

After startup, there will be no error. Open the browser for input http://localhost:8080/SpringTest/test/hello?user=World , you can see the following output:

When the desired result appears, the mood can only be described as pleasure, but we specify that the user parameter needs to be carried. If there is no parameter in the URL, the following error occurs:

If you don't want this to happen, you can change the @ requestparam of the HelloWorld parameter to @ requestparam (value = "user", required = false, DefaultValue = "world"). Of course, this is only a very small example to illustrate the power of annotations. Spring also provides rich annotations to meet different requirements, which is simply programming with configuration and annotations.

Step 11: complex data structure

The above tests all return a string, but we usually involve complex data structures during development. We generally use JSON as a communication serialization tool. So how can we support JSON in spring? Before testing this, let's take a look at how complex data structures (such as map) are returned. We add a function in the controller:

The resource identified by this request is only capable of gene@R_419_1574 @ responses with characteristics not acceptable according to the request “accept” headers.”, This feeling is because accept only accepts text format by default, and the return value of this interface does not return a text object.

If you want to support JSON, you only need to configure message converters in spring. Each JSON library provides such converters. Let's take fastjson as an example. First, you need to configure it in POM Add fastjson dependency to XML. Then in ApplicationContext Add the following configuration to XML:

At this time, try the URL again and find that the map can be converted into JSON.

Step 11: Toss

Well, the above example is enough to complete a relatively simple web service. Of course, we don't have a front end, but it's just an HTTP service usually provided as a server. However, with spring, we can save a lot of code. Of course, providing a server interface through HTTP + JSON is more efficient than thrift and other RPC frameworks, But its advantage is that it is relatively simple and convenient to debug... I feel that a large number of front-end and server-side communication mostly use this way.

summary

After learning how to build the spring framework, mom doesn't have to worry about me writing web interfaces anymore. Of course, spring can also adapt to various components, such as mybatis connecting to the database, jedis connecting to redis, etc; There are also rich features that allow you to minimize unnecessary code through configuration and annotation. Recently, the better spring boot seems to be an artifact of web development. I'll have time to toss about this later.

Of course, this article only records the process of blood and tears, and how spring Xiaobai builds the spring development environment step by step..

The code in this article can be found in https://github.com/terry-chelsea/spring-demo.git Find

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>