Java Development The road of Tears: Building the Spring Framework step by step

Source: Internet
Author: User
Tags tomcat server

Objective

As a service-side development feeling has been quite rejection of the framework of this thing, always feel what the implementation of logic to help you encapsulated in the inside, you only need to configure this configuration that, out of the problem and do not know how to troubleshoot, even if the writing Web program would prefer to use jetty such an embedded Web server implementation, I write the servlet, always feel from the main function is within the scope of their own control, but this is a bit primitive, but also see a variety of open source systems using spring to implement Web services, although the code is always able to see, but still do not know how to build a step-by-step, So take a weekend toss toss, do not know, originally this thing can put an unfamiliar user to crash, this article mainly introduce me how to build a spring environment (words also really can't divide spring and SPRINGMVN), although in most web development it seems that this is tricks.

The environment used in this article is a newer version of Eclipse Luna+spring (according to the rules of my choice version, unless there is a new version of the new feature to use, otherwise try not to use the latest version, and then choose a newer n version of the more people use, For example, the spring version selected in this article is 4.3.7.RELEASE).

The following from a purely engineering point of view to explain how to build such an environment, no principle, there is a principle I am purely guessing, did not read the source.

Detailed steps

First step: Create a MAVEN project

This is a familiar process, but generally I do not recommend the choice of archetype, just create a simple project can be, the former always create a failure (create archetype mode can let the IDE do more things). In fact, what is the MAVEN project, in my opinion is a Java project with Pom.xml, and then set the path of the code to src/main/java similar to the structure, So we just need to use the IDE to help us create a project with Pom.xml, and we'll write a dependency and build parameter ourselves.

In addition to filling in the correct group ID and artifact ID, the packaging is chosen as the war, which can be run under Tomcat.

Step Two: Modify the project configuration

Here you need to modify the configuration has two, only need to pay attention to the changes after the appearance of it:

1, Project Facets: Although do not know what to configure here, but again and again eat this loss, here to configure is the Java select more than 1.6 (best 1.7 bar), and then select the dynamic Web Module, below the following interface appears:
If not, then you can tick off the Dynamic Web module, then save it, then click again in Project Facets, select Dynamic Web module, this is the interface that appears, Note It is best not to choose 3.0, before encountering 3.0 incompatibility issues, jdk1.7 + 2.5 version is OK to run.

Click "Further configuration avaliable ..." To configure, change the context directory to, and select Generate Web. XML, save. Such as:

At this point you will see your engineering structure, such as the Src/main directory where the Java/resources/webapp three directories appear.

2. Configure deployment Assembly, where the source and deploy Path are configured, indicating that the contents of the source directory will be copied to the Tomcat deployment directory/deploy path when the project is deployed. Here it needs to be configured as shown in:
For example, the first indicates that the source code under the Src/main/java directory in the project is compiled and placed into the deployment directory/web-inf/classes directory, and the last one indicates that the project's MAVEN dependencies are copied to the deployment directory/web-inf/lib directory. As far as I can see, in fact the Tomcat directory is running with the deployment deployment directory/web-inf/classes, the deployment directory/web-inf/lib joined to Classpath, so the configuration file and the compiled class file are placed under classes. The dependent jar is placed in the Lib directory and can be found when the Java program is started.

Step three: Download spring dependencies

Spring's jar is more, and the basic function needs several dependency as follows:

Fourth Step: Writing code

We write a simple controller, and the controller returns a "Hello ${username}" string.

Fifth step: Spring configuration file

Spring configuration file is generally called "applicationcontext.xml", of course, this is not the spring default configuration name, Still need to specify in Web. XML, here we only configure the spring configuration file, in fact, the spring configuration is mainly for some bean configuration, here we do not need to create any beans, we just need to simply add a scan path to it.

<beans xmlns= "Http://www.springframework.org/schema/beans"

Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"

xmlns:context= "Http://www.springframework.org/schema/context"

Xmlns:mvc= "Http://www.springframework.org/schema/mvc"

Xsi:schemalocation= "Http://www.springframework.org/schema/beans

Http://www.springframework.org/schema/beans/spring-beans.xsd

Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd ">

< Context:annotation-config/>

This configuration file is usually placed in the Src/main/resources directory, we have configured the deployment copy of the settings, he will be copied to the web-inf/classes/directory at the time of deployment, there are only two things configured in the context: Annotation-config is the package that tells spring to identify the annotation configuration, followed by a scan that represents the class to be scanned. Sixth step: Configure Web.xmlweb.xml to enable us to automatically generate the second step of configuration, it is the configuration that Tomcat needs to rely on when booting, can configure some servlet, filter, listener, etc., for the simple use of spring, Typically only one servlet is configured, and all requests have this servlet for routing. dispatcherservlet Org.springfra Mework.web.servlet.DispatcherServlet contextconfiglocation classpath:applicationContext.xml 1!--load-on-startup--> dispatcherservlet /!--url-pattern--> You can see that we only configured a dispatcherservlet, which handles all URL requests, It initializes the required configuration files will be classpath down to find Applicationcontext.xml, just described, in the deployment of resources under the files will be copied to web-inf/ Classes directory and join to Java-initiated classpath. Seventh step: Deploying Tomcat first needs to download a Tomcat,tomcat 7.x is a good choice, because Tomcat is green (most Java implementations are green), can be extracted directly, and then configured in Eclipse. Add a Tomcat instance to window->server->runtime environment in eclipse, note that you need to select the JDK and need to select the version supported by the current JDK. Then find servers in the lower taskbar, if there is no way to Window->show view to select Servers Add, then add to create a new server here. Select the Tomcat instance that you just created, and then choose one from avaliable resources to join to the right configured (avaliable is generated based on whether the project has web. xml). Eighth step: Configure Tomcat to double-click the newly created Tomcat Server, go to the overview page, this page can be configured to run the Tomcat instance, the main configuration includes port number, deployment directory and so on, if the port or file does not conflict, try not to modify, One of the things that needs to be modified is the "Publish module contexts to separate XML files" Check in the server options, although I don't know what this is, but the lesson of blood and tears tells me to choose this and save it directly. Nineth Step: Launch Tomcat here may be someone to ask why there is no Tomcat plugin configured on Eclipse Ah, where do I go to start tomcat! Isn't that cat's head going to die? To tell the truth, the configuration of the cat head often encounter network problems fail, so no longer try, and directly by right-clicking the seventh step created by the Tomcat instance can complete all the functions of the cat head can be done, why also configure the plug-in? Right-start, and then pray to start without any errors, error on Google, basically spring problems have been trampled on the pit. Tenth step: After the test boot is complete, there is usually no error, open the browser input HTTP://LOCALHOst:8080/springtest/test/hello?user=world, you can now see the following output:! [] (http://i2.51cto.com/images/blog/201808/04/901c622732b765360b907ac1119750c2.jpg?x-oss-process=image/ watermark,size_16,text_qduxq1rp5y2a5a6i,color_ffffff,t_100,g_se,x_10,y_10,shadow_90,type_zmfuz3pozw5nagvpdgk=) Java development of the Road of Tears: Step by step to build the spring framework we want to the results, at this time the mood can only be described with pleasure, but we specify the need to carry the user parameter, if the URL without parameters, the following error occurs:! [] (http://i2.51cto.com/images/blog/201808/04/57b24556b785dc467517d24f6c90ae2f.png?x-oss-process=image/ watermark,size_16,text_qduxq1rp5y2a5a6i,color_ffffff,t_100,g_se,x_10,y_10,shadow_90,type_zmfuz3pozw5nagvpdgk=) Java Development The road of Tears: Build a spring framework step by step if you do not want this to happen, you can helloworld this parameter @requestparam modify it to @requestparam (value= "user", required= False, defaultvalue= "World"), of course, this is just a very small example to illustrate the power of annotations, and spring provides a rich set of annotations to implement different requirements, simply programmed with configuration and annotations. 11th Step: The test on the complex data structure is to return a string, but when we generally develop complex data structures, we generally use JSON as a serialization tool for communication, so how do you support JSON in spring? Before testing this, take a look at how complex data structures (such as map) are now returned. We add a function to the controller: @RequestMapping (value = "Hellomap", method = Requestmethod.get) @ResponseBodypublic Map Hellomap (@RequestParam (value= "User", Required=false, defaultvalue= "World") String userName) {Map ret = new HashMap (); Ret.put ("Hello", userName); return ret;} And then test in the browser, the following error appears: "The resource identified by this request are only capable of generating responses with characteristics Not acceptable according to the request "accept" headers. "This is because accept defaults to the text format only, and the return value of this interface does not return a text object. If you want to support JSON, in fact, you only need to configure message-converters in spring, each JSON library provides such converter, we have Fastjson as an example, First, you need to add Fastjson dependencies in Pom.xml. Then add the following configuration in the Applicationcontext.xml: text/html; Charset=utf-8 Application/json; Charset=utf-8 At this point, retry the URL discovery to return to the map converted to JSON look. [] (http://i2.51cto.com/images/blog/201808/04/3d3fa1ee3a157fcfec9a3f97f2c0e5ac.png?x-oss-process=image/ watermark,size_16,text_qduxq1rp5y2a5a6i,color_ffffff,t_100,g_se,x_10,y_10,shadow_90,type_zmfuz3pozw5nagvpdgk=) 11th Step: Toss Well, the above example is enough to complete a relatively simple Web service, of course, we do not have a front end, but is usually served as the service side of the HTTP service, but with spring we can save a lot of code, of course, by http+ JSON provides service-side interface than thrift and other RPC framework to some, the efficiency may be lower, but its advantages are relatively simple ah, debugging more convenient ah ... It feels like a lot of front-end and server-side communications are mostly used in this way. Summed up the spring framework of the building, mom no longer worry about me to write the Web interface, of course, spring can also adapt to a variety of components, such as the usual use of MyBatis connection database, Jedis connection Redis, etc. There are also plenty of features that allow you to minimize unnecessary code through configuration and annotations. Recently the better spring boot seems to be a web development artifact. There is time to toss it later. Of course, this article only records the history of Blood and tears, spring small white is how to build a spring development environment, the Great God Light spray.

Java Development The road of Tears: Building the Spring Framework step by step

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.