Elegant Springmvc and restful

Source: Internet
Author: User

I. Preface

1. The previous period of time has been in the request to write a small program, finally the client's request was fixed, but the service side, how to write, Tangled half a day, with a servlet temporarily wrote a: http://www.cnblogs.com/JJDJJ/p/7299274.html

Let's take a look at the whole code: Of course there's a bunch of them underneath.

Did not find that the code is so messy that I now look at the brain pain.

2. Later think of the form of the API to write a server, the applet side post the past JSON format data, and then the server to get the JSON, and then manipulate the data, and finally return the result is OK. Similar to the Baidu takeaway API such as:

As you can see, the JSON data in request and response is very elegant.

So how do we write such an elegant API server to the client call it. Finally found a better way to achieve: Restful

Two. Implement

1.jar Package Import

Let's start with zero, create a project first, and then import the jar package:

All of these operations are used in the back, so it's all in. These resources on the CSDN should be rotten on the street.

2. Construction of the project structure:

First add the Xml:springmvc-servlet.xml file under src:

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "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-4.1.xsd Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/ Spring-mvc-4.1.xsd ">        <!--Scan The package and the sub package -    <Context:component-scanBase-package= "Com.restful"  />    <!--Configuring the View resolver -    <Beanclass= "Org.springframework.web.servlet.view.InternalResourceViewResolver"ID= "Internalresourceviewresolver">        < Propertyname= "prefix"value= "/web-inf/jsp/"/>        < Propertyname= "suffix"value= ". jsp"/>    </Bean>     <!--don ' t handle the static resource -    <Mvc:default-servlet-handler/>    <!--If you use annotation must configure following setting -    <Mvc:annotation-driven/></Beans>

Then add the following in Web. xml:

<servlet>        <Servlet-name>Springmvc</Servlet-name>        <Servlet-class>Org.springframework.web.servlet.DispatcherServlet</Servlet-class>        <Init-param>            <Param-name>Contextconfiglocation</Param-name>            <Param-value>Classpath:springmvc-servlet.xml</Param-value>        </Init-param>        <!--Configure an initialization parameter for Dispatcherservlet: Configure the location and name of the SPRINGMVC configuration file -        <!--you can actually configure the SPRINGMVC configuration file without contextconfiglocation and use the default. The default configuration file is:/web-inf/<servlet-name>-serv Let.xml -        <!--<init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath: Springmvc-servlet2.xml</param-value> </init-param> -        <Load-on-startup>1</Load-on-startup>    </servlet>    <servlet-mapping>        <Servlet-name>Springmvc</Servlet-name>        <Url-pattern>/</Url-pattern>    </servlet-mapping>

Then we look at this line of XML configuration, you need to configure the view resolver, create JSP folder under Web-inf, to store JSP resources, of course, can be other names, but your configuration and directory to be consistent

Then create a hello.jsp file in the JSP folder, the usual, write on the page Hello World:D

Start building the package below, remember the XML configuration of this sentence?

He needs to scan the com.restful package, so we create a new one and then create a new controller in this package.

So the structure of the project is built.

3. Write the Code:

First, start the Mycontroller:

@Controller means to register a bean into the spring container, let the spring container know, you this class is a controller, if not this note, will report 404, we use Postman (a Send Request tool, can Baidu) test found:

Even if you write a URL map, it's the same.

Here's a look at the @requestmap annotation, which is the URL map:.

As you can see, the request I just had was http://localhost:6789/RestFul/mvc/xxx/xxx.

And not HTTP://LOCALHOST:6789/RESTFUL/MVB or HTTP://LOCALHOST:6789/RESTFUL/MVD.

This URL depends on the value in this annotation. Wrote the wrong 404.

Then the method above the mapping, the same, what is written here, the URL of the request is what, I wrote a/hello here, the request is:

Http://localhost:6789/RestFul/mvc/hello

Then look at this method, there are two parameters, you can try to request a URL:

Http://localhost:6789/RestFul/mvc/hello?name=zjj&age=20 and Http://localhost:6789/RestFul/mvc/hello?name= adminj&age=233

What is output separately, above operation no problem should output this:

The last return "Hello";

is the name of the returned view, remember when the view resolver was configured before, the prefix is web-inf/jsp, and the suffix is. jsp. So the name of the middle part of the JSP, that is, this hello, even up is hello.jsp

Let's Test it:

You can see that you have entered this URL and jump directly to the previously created hello.jsp.

So the question is, does this URL take advantage of the concatenation parameter, and what do we do when we need to get an object, don't worry, set the parameter of the method to an entity class, and he will automatically help you to pack:

Create a person First:

Next, create a person.jsp in the same directory as the hello.jsp

Finally we test:

Here the parameters correspond to the attributes in the person class.

The console also outputs:

As you can see, the parameter of this method becomes an object, and if you use the & stitching parameter in the URL, he will automatically pack it for you as long as the parameters and attributes correspond.

3.Restful debut

The above is just a simple application of spring MVC, and of course we are not enough to accomplish the goal: API server. We also need to use restful.

Create a new Restcontroller controller, and then write a POST method:

The meaning of this @pathvariable is to dynamically get the parameters in the request URL, such as I am now using the tool to send a POST request:

As you can see, this request URL is: HTTP://LOCALHOST:6789/RESTFUL/REST/USER/1

You can see the status of this request:

Is successful, let's take a look at the console output:

Successful output of the method name and the passed-in ID parameter

Of course, restful includes several other kinds of request, such as get/delete/put here is not an example, you can write a few and then use the Postman test, there are many different ways to request:

(The way to enter a URL in a Web page is get)

Congratulations, it's easy to get started here, but we're not enough. There is one more important thing in our goal: the transfer of JSON data

4.json Join

Create a new controller:

This writes:

This is a direct return to p, you'll find it strange at first, but you can test it:

Well, it's very powerful, just return a JSON-formatted data.

What if we post a JSON-formatted data in the past, what should we do? Continue to write:

Here, we add a parameter, which is the user class, preceded by a @requestbody annotation, which is used to accept JSON data

Then return a map type of data and you will find the result of the test, magically very elegant:

As you can see, we post a set of JSON data, where name and ID must correspond to attributes in the user class, few fields are OK, only null or 0 is shown, such as the above birth, I do not have this field in post, he directly shows NULL, cannot be wrong, Wrong back to the direct report 400.

(A friend who has played JSON to obj or obj to JSON should know that the JSON field and the properties of obj need to be mapped after the conversion class has been serialized)

Three. Conclusion

In this case, basically we have achieved almost the goal, the acceptance of JSON and return data are implemented, using spring MVC and restful, rather than the servlet, the rest of the processing logic, here is not to repeat. I hope this article is helpful to the newcomers.

Elegant Springmvc and restful

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.