Use SPRINGMVC to develop restful-style interface Java-web projects, tomcat deployment and Client Access __web

Source: Internet
Author: User
Tags constant wrapper

1. Use IntelliJ idea Development, Gradle construction project. Webcollection module is the interface of the project module, Handlemessage class is the interface class.

2. The Build.gradle configuration file for the interface Project module reads as follows:

Apply plugin: ' java ' Apply plugin: ' idea ' Apply plugin: ' War ' group = ' com.cloudcollection ' archivesbasename = ' Webcollec tion ' Version = ' 0.1 ' sourcecompatibility = 1.8 targetcompatibility = 1.8//Java compilation will fail because of the Chinese character in the default state [Compilejava,compile testjava,javadoc]*.options*.encoding = ' UTF-8 ' webappdirname = ' webapp ' war{archivename = ' Webcollection.war '} Build Script {repositories {maven {URL ' https://repo.spring.io/libs-release '} Jcenter ()}} task Wrapper (type:wrapper) {gradleversion = ' 3.5 '} idea {module {Downloadjavadoc = False download
    Sources = False}} sourcesets {main {output.resourcesdir = ' bin/classes '} repositories { Mavencentral () mavencentral name: "Erichseifert.de", Artifacturls: ["Http://mvn.erichseifert.de/maven2"]} Dependenci ES {Compile project (": Commons") Compile project (": Model") testcompile (' junit:junit:4.12 ') compile ' org. Springframework:spring-cOre:4.3.6.release ' compile ' org.springframework:spring-web:4.3.6.release ' compile ' ORG.SPRINGFRAMEWORK:SPRING-WEBM Vc:4.3.6.release ' providedcompile group: ' Javax.servlet ', Name: ' Javax.servlet-api ', version: ' 3.1.0 '} war {fro M ' Src/main/webapp '//Adds a file-set to the root of the archive}

The contents of 3.web.xml are as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <web-app version= "3.1"
        metadata-complete= "false"
        xmlns= "Http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemalocation= "Http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" >

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class> org.springframework.web.servlet.dispatcherservlet</servlet-class>
</servlet>

< servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</ url-pattern>
</servlet-mapping>

</web-app>

4. Interface-dependent lookup requires a configuration file Dispatcher-servlet.xml, which reads as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "http://www.springframework.org/ Schema/beans "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xmlns:context=" Http://www.springframewor K.org/schema/context "xmlns:mvc=" Http://www.springframework.org/schema/mvc "xsi:schemalocation=" http://www.s
                        Pringframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/context HTTP://WWW.SPRINGFRAMEWORK.ORG/SC
                        Hema/context/spring-context.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MVC Http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <context:component-scan base-package=" Repository.collect.controller "></context:component-scan> <mvc:annotation-driven></mvc: Annotation-driven> </beans> 

5. All ready to start the development of the server-side interface: Handlemessage.java class

@RestController @RequestMapping ("/repository") public class Handlemessage {private final Logger Logger = Loggerfactor

    Y.getlogger (This.getclass ());
    Public Handlemessage () {}/** * obtains the Token interface * @param json unique identification of different systems, can generate a unique token return * @return * * @ResponseBody @RequestMapping (value= "/getcollecttasktoken", method = Requestmethod.post, produces = "applic  Ation/json;charset=utf-8 ") Public String Getcollecttasktoken (@RequestBody string json) {Jsonobject Jsonobject
        = Jsonobject.fromobject (JSON);

        String key = jsonobject.getstring ("key");
        String token = ""; String msg = "token build succeeded.
        ";
        String response = "true";
            try {//First query from database table based on key, return token if there is one, or create save if not. Document doc = Mongodb.getmongodb (). Getdatabase (Constant.mongo_db_name). GetCollection (Constant.web_collection_
            TOKEN). Find (Filters.eq ("Key", key)).
              if (doc!=null) {  token = doc.getstring ("token");
                else {//Generate a unique token based on key and generate JSON to return token = Stringutils.hash (key); Save the system's identity key and corresponding token to Mongodb Mongodb.getmongodb (). Getdatabase (Constant.mongo_db_name). GetCollection (Con Stant.
            Web_collection_token). Insertone (New Document ("Key", key). Append ("TOKEN", TOKEN));
            The catch (Exception e) {logger.error ("system generation Token failed:", e); msg = "Token build failed.
            ";
        Response = "false";
    Return "{\" msg\ ": \" "+msg+" \ ", \" response\ ": \" "+response+" \ "," token\ ": \" "+token+" \ "}"; }

6. The parameters passed are JSON strings, and interface processing returns are also JSON strings.

7. Use the Gradle build command to play the war package and deploy in Tomcat.

8. Client Request class:

public class Testwebcollection {//post commit calling method public static string post (String uri, map<string,object> Map) Throws Unsupportedencodingexception {//All parameters are placed in the map and then converted to a JSON string passed to the interface string str = JSONOBJECT.FROMOBJEC
        T (map). ToString ();

        SYSTEM.OUT.PRINTLN ("JSON parameter:" +STR);
        HttpClient httpclient = new Defaulthttpclient ();
        HttpPost HttpPost = new HttpPost (URI);
        Httppost.setentity (New stringentity (str, charset.forname ("Utf-8"));
            try {httpresponse response = Httpclient.execute (HttpPost);
            int statusCode = Response.getstatusline (). Getstatuscode ();
            System.out.println ("http Return code:" +statuscode);
                If the return state is 200, the print return information if (statuscode==200) {httpentity entity = response.getentity ();
                String entitystr = entityutils.tostring (entity);
            SYSTEM.OUT.PRINTLN ("Client receives content:" +ENTITYSTR);
            } catch (Exception e) {E.printstacktrace ();
    return null;  public static void Main (string[] args) throws Unsupportedencodingexception {map<string,object> Map =

        New Hashmap<> (); Interface 1 map.put ("Key", "Irr2_0"), or the number of parameters, can be placed in the map post ("Http://localhost:8080/webcollection/repository/getCo
    Llecttasktoken ", map); }
}

The client invokes the interface console log with the following contents:

JSON parameter: {"key": "Irr2_0"}
HTTP return code: 200

Client receive content: {"msg": "Token build succeeded." "," Response ":" True "," token ":" D71161A15E23713AEDC7CB4BD0438FC5 "}

9. Special note: The project uses the associated Tomcat boot service in the Idea tool, and the URL of the interface is not required for the project name, as follows:

"Http://localhost:8080/repository/getCollectTaskToken"

When the project is deployed separately in Tomcat, the URL of the interface needs to be added with the Web project name "Webcollection" or it will be reported to 404.







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.