Abstract

I have spent several months learning the basics of Java, and I feel that they are scattered knowledge points, not only do not know how to use them in practice, but also easy to forget. Therefore, it is necessary to start a real application, not only to integrate the previous knowledge, but also to start to touch the real work content. Here’s how to build a SpringBoot container from scratch.

1. Start with an empty folder

A basic Spring project includes:

  • Pom. The XML file
  • src\main\java\hello\Application.java
  • src\main\java\hello\HelloController.java

1.1 Adding Content

Maven’s project-object-Model (POM) configuration file is also the core file of Java projects. First of all, follow the official websitepromptCreate a new folder in an empty folderpom.xmlFile, and then willBuild With MavenPaste the contents of the.

Configure ali cloud mirror to ensure access speed, add to pom.xml:

<repositories>
    <repository>
        <id>alimaven</id>
        <name>aliyun maven</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
Copy the code

Create a new Application class and a new HelloController class, and copy the code into them as prompted.Refresh the MavenAfter that, you can find that the project is ready to run. And type it in a browserlcoalhost:8080You can see that the project has started:

2. The nature of Web applications

2.1 Processing HTTP Requests

  • Extract queryString from HTTP request.
  • Accepts parameters in the payload from HTTP.

For example, we fill in the Google Chrome search barspringbootNow you can see that the URL is changedhttps://www.google.com/search?q=springboot&oq=springboot&aqs=chrome.. 69 i57l2j69i60j69i61j69i60l2. 2979 j0j7 & sourceid = chrome&ie = utf-8

then?The following series of key-value pairs are called query strings. A footnote: Search is called an interface in the production dimension.

2.2 Returning an HTTP Response

The response includes:

  1. status code
  2. HTTP response header
  3. HTTP response body

Supplementary notes:

  1. The HTTP header and HTTP body in the byte stream are separated by four delimiters \r\n\r\n.
  2. Body includes JSON, HTML, CSS, etc

2.3 How do I Obtain a Query String

Let’s say we’re Google, and the user types in a url like thishttp://localhost:8080//search?q=dogSo how do we get thisdogWhat about keywords? Back to the code:

// Specify the interface name as /search @requestMapping ("/search"Public String search(@requestParam ()"q") String searchKeyWord) {
        return "you are searching:"+searchKeyWord;
    }
Copy the code

Click Run again and enter the url:

@RequestMapping("/search"// Set charset to optional public String search(@requestParam ("q") String searchKeyWord,
                         @RequestParam(required = false,value = "charset") String charset) {
        return "you are searching:"+searchKeyWord + " with charset is :"+charset;
    }
Copy the code

A GET request is usually used to transmit non-sensitive information. Because the account name and password in a GET request are displayed in the URL, sensitive information cannot be sent through a GET request.

2.4 a RESTful API

A RESTful API is a set of API design specifications used to design WEB data interfaces, specifying urls, status codes, and server responses.developer.github.com/v3/Github’s API has been called the industry benchmark and worth learning from.

  • Use HTTP verbs to represent actions
  1. GET- Obtains resources
  2. POST- Creates a resource
  3. PUT- Updates resources
  4. DELETE- Deletes the resource
  • Use urls to represent resources
  1. There are no nouns in the resource
  2. Use plural numbers to represent lists of resources

Method to obtain parameters


RestController // Map all requests to a method @requestMapping ("repos")
public class IssueController {
    @DeleteMapping("/{owner}/{repo}/issues/{issuesNumber}/lock")
    public void unlock(
            @PathVariable("owner") String owner,
            @PathVariable("repo") String repo,
            @PathVariable("issuesNumber") String issueNumber
    ) {
        System.out.println(owner+""+repo+""+issueNumber); }}Copy the code

Since a DELETE operation cannot be initiated by a browser, Postman is used to simulate a DELETE request.

2.5 Getting the Body from the HTTP POST

When a request has a large number of parameters, it is common to put the parameters in the body of the HTTP post. How do you get the parameters from the body of the HTTP post? Take the GitHub POST as an example:

The requested path isPOST /repos/:owner/:repo/issues

The body is:

{
  "title": "Found a bug"."body": "I'm having a problem with this."."assignees": [
    "octocat"]."milestone": 1,
  "labels": [
    "bug"]}Copy the code

The code is as follows:

    @PostMapping("/{owner}/{repo}/issues")
    public void createAnIssue(
            @PathVariable("owner") String owner,
            @PathVariable("repo") String repo,
            @RequestBody HashMap requestBody
    ){
        System.out.println(requestBody);
    }
Copy the code

Using the same PostMan simulation post request: url: http://localhost:8080/repos/hello/world/issues the body:



GsonFormat











PostBody{title='Found a bug', body='I'm having a problem with this.', milestone=1, assignees=[octocat], labels=[bug]}

2.6 Get the Body from the form

The code is as follows:

@PostMapping("/getForm")
    public void getForm(
            @RequestParam("name") String name,
            @RequestParam("city") String city
    ){
        System.out.println(name);
        System.out.println(city);
    }
Copy the code

The post request is as follows:

zhangsan
beijin
Copy the code

As you can see, you have implemented fetching parameters from the form form, which is suitable for cases with few parameters.

3. Generate an HTTP response

After taking the parameters of the HTTP request in the previous ways, it’s time to do the appropriate processing and generate the HTTP response to the front end.

First of all, we know that the HTTP response returns essentially an HTML text, with some markup language to beautify the result. So the simplest thing we can do is add HTML tags directly to our Java code:

@RequestMapping("/getForm")
    public String getForm(
            @RequestParam("name") String name,
            @RequestParam("city") String city) {// Add a label to the returned resultreturn ("<em>" + name + "</em>" + "" + "<strong>" + city + "</strong>");
    }
Copy the code

Results:


@RequestMapping("/Servlet") public void controlRawServlet(HttpServletRequest request, HttpServletResponse Response) throws IOException {// Returns a status code=403 error response.setStatus(HttpServletResponse.SC_FORBIDDEN); // Write information to HTTP reponse response.getwriter ().write("hello world 403");
    }
Copy the code

The results are as follows:


JSON


@RequestMapping("/GetBody")
    @ResponseBody
    public Object writeIntoBody(){
        Map<String,Object> map = new HashMap<>();
        map.put("result", Arrays.asList("zhangsan"."beijin"));
        return map;
    }
Copy the code

Results:

HttpMediaTypeNotAcceptableException



4. Ask questions

4.1 HTTP GET can’t include a body?

Answers from WebTechGarden’s personal blog and StackOverflow:

First of all, there is no regulation in HTTP protocol that BODY can not be carried in GET, and the author proves that HTTP GET can carry body in various ways. But GET is designed to identify resources with urIs, and if you let it carry data in the request body, the usual caching service fails and the URI cannot be used as a cache Key.

On the other hand, if you need to send a large amount of data using the Body just to read the resource, switching to a POST request is incompatible with RESTFul POST semantics. It might be possible to GET + body at this point, but you can’t cache the request with the URI as the Key.

So, it doesn’t make sense to add a body to GET.

5. Necessary knowledge

5.1 Servlets, Servlet containers

From: Zhihu. whales from the island

  • Servlet

Java Servlets (Java server applets) are Java technolog-based Web components that run on the server side and are managed by the Servlet container to generate dynamic content. Servlets are platform-independent Java classes, and writing a Servlet is actually writing a Java class according to the Servlet specification. Servlets are compiled into platform-independent bytecode that can be dynamically loaded to run in a Java technology-enabled Web server.

  • The Servlet container

A Servlet container, also known as a Servlet engine, is a part of a Web server or application server that provides Web services on top of sent requests and responses, decodes MIME-based requests, and formats MIME-based responses. A Servlet does not have a main method and cannot run on its own; it must be deployed into a Servlet container that instantiates and invokes Servlet methods (such as doGet() and doPost()), which contains and manages servlets for the life of the Servlet. After the introduction of JSP technology, the containers that manage and run servlets/JSPS are also called Web containers.

6. References:

1. Personal blog: who says HTTP GET can’t send data through Body? “HTTP GET with request body” “HTTP GET with request body” “99% of people understand the difference between GET and POST in HTTP” jump to the source article 4. Personal blog. RESTful API Best Practices Jump to source article 5. Zhihu. Several concepts: Servlet, Servlet Container, Tomcat jump to the source article