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:

The different versions of spring depend on the version you use to be consistent.

Fourth Step: Writing code

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

Package com.fengyu.test;

Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RequestMethod;
Import Org.springframework.web.bind.annotation.RequestParam;
Import Org.springframework.web.bind.annotation.ResponseBody;
Import Org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping ("/test")
public class Simplecontroller {
@RequestMapping (value = "Hello", method = Requestmethod.get) br/> @ResponseBody

Return "Hello" + UserName + "!";
}
}

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 "

  &lt; Context:annotation-config/&gt;&lt;!  --automatic scanning of web packages, incorporating annotated classes into Spring container management--&gt;  &lt;context:component-scan base-package= "Com.fengyu.test" &gt;&lt;/context:component-scan&gt;  

</beans>

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. xml

Web. XML is automatically generated when we configure the second step, it is the configuration that Tomcat needs to rely on when booting, it can configure some servlet, filter, listener, etc. for simple use of spring, only one servlet is configured, All requests have this servlet for routing.

<?xml version= "1.0" encoding = "UTF-8"?
<web-app xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns=" Http://java.sun.com/xml/ns/javaee "xsi:schemalocation=" http://java.sun.com/xml/ns/ Java ee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "id=" webapp_id "Version =" 2.5 ";
<servlet >
<servlet-name> dispatcherservlet</servlet-name;
<servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class >
<init-param>
< param-name> contextconfiglocation</param-name >
<param-value> classpath:applicationContext.xml </param-value >
</init-param>
<load-on-startup> 1</load-on-startup>
</ servlet >
<servlet-mapping >
<servlet-name> dispatcherservlet</servlet-name >
< Url-pattern>/</url-pattern>
</servlet-mapping;
</web-app>

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

The first need 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

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, etc., if the port or file does not conflict, try not to modify, the one that needs to be modified is the Server Options tick on "Publish module contexts to separate XML files", although do not know what this is to do, but the blood and tears of the lesson told me to choose this, directly save.

Nineth Step: Start Tomcat

There may be someone to ask why there is no plugin for Tomcat on Eclipse, 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: Test

After the boot is complete, there is generally no error, open the browser input http://localhost:8080/SpringTest/test/hello?user=World, this time you can see the following output:

There is the result we want, 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:

If you do not want such a situation can be HelloWorld this parameter @requestparam modified to @requestparam (value= "User", Required=false, defaultvalue= "World"), Of course it's just a very small example. Note The power of annotations, and spring provides a rich set of annotations to implement different requirements, simply programmed with configuration and annotations.

11th Step: Complex Data structures

The above test is to return a string, but we generally develop a complex data structure when it comes to the general use of JSON as a serialization tool for communication, then how to 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) br/> @ResponseBody

map<string, string> ret = new hashmap<string, string> ();
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:

<mvc:annotation-driven>
<mvc:message-converters register-defaults= "false" >
<bean
class= "Com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter" >
<property name= "Supportedmediatypes" >
<list>
<value> text/html; Charset=utf-8</value >
<value> Application/json; Charset=utf-8</value >
</list>
</property>
</bean>
</mvc:message-converters>
> </mvc:annotation-driven>

Retry the URL discovery now to return the map to JSON.

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, through the 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.

Summarize
Learn the spring framework, mother 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.