東川印記

一本東川,笑看爭龍斗虎;寰茫兦者,度橫佰昧人生。

通过Intellij idea 2020 搭建 Spring Boot 学习demo 01

2020年9月27日星期日



一晃十年,一别两宽

1,搭建项目,通过maven

新建项目类型,选择 Spring Initializr

然后配置 包的属性,看起来是个 maven pom 的配置

依赖 选择 Spring Web依赖,这样最后的产出是个 web。。。。

然后项目放哪,测试的先放android下。。。。

然后弹框创建打开项目,开始同步依赖。。。。

经过漫长的下载后,发现项目竟然可以直接运行。。。。


运行报错,Web server failed to start. Port 8080 was already in use.

SENRSL:~ senrsl$ cd j2ee/apache-tomcat-9.0.10/bin/
SENRSL:bin senrsl$ ./shutdown.sh
Using CATALINA_BASE:   /Users/senrsl/j2ee/apache-tomcat-9.0.10
Using CATALINA_HOME:   /Users/senrsl/j2ee/apache-tomcat-9.0.10
Using CATALINA_TMPDIR: /Users/senrsl/j2ee/apache-tomcat-9.0.10/temp
Using JRE_HOME:        /Users/senrsl/Library/Java/JavaVirtualMachines/corretto-11.0.8/Contents/Home
Using CLASSPATH:       /Users/senrsl/j2ee/apache-tomcat-9.0.10/bin/bootstrap.jar:/Users/senrsl/j2ee/apache-tomcat-9.0.10/bin/tomcat-juli.jar
NOTE: Picked up JDK_JAVA_OPTIONS:  --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED
SENRSL:bin senrsl$

。。。。stop掉独立的Tomcat,再次启动。。。。

看起来是启动成功了,然后访问 网页 404看起来是正常的呢。。。。


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.4.RELEASE)
2020-09-27 15:02:47.880  INFO 53253 --- [           main] dc.test.spring.boot.Application          : Starting Application on SENRSL with PID 53253 (/Users/senrsl/android/Project/spring_boot/target/classes started by senrsl in /Users/senrsl/android/Project/spring_boot)
2020-09-27 15:02:47.882  INFO 53253 --- [           main] dc.test.spring.boot.Application          : No active profile set, falling back to default profiles: default
2020-09-27 15:02:48.501  INFO 53253 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-09-27 15:02:48.508  INFO 53253 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-09-27 15:02:48.509  INFO 53253 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.38]
2020-09-27 15:02:48.569  INFO 53253 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-09-27 15:02:48.569  INFO 53253 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 656 ms
2020-09-27 15:02:48.689  INFO 53253 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-09-27 15:02:48.838  INFO 53253 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-09-27 15:02:48.847  INFO 53253 --- [           main] dc.test.spring.boot.Application          : Started Application in 1.253 seconds (JVM running for 1.708)
2020-09-27 15:03:02.309  INFO 53253 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-09-27 15:03:02.309  INFO 53253 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-09-27 15:03:02.314  INFO 53253 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 5 ms

然后打开网页 404

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Sep 27 15:03:02 CST 2020
There was an unexpected error (type=Not Found, status=404).


应该是正常的吧。。。。项目里的确没东西。。。。


2,简单实现 webService....

最简单的改一下先

直接修改Application类,增加 @RestController注解和 index方法

package dc.test.spring.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }


    @RequestMapping("/")
    public String index() {
        return "当前显示内容来自" + getClass().getSimpleName();
    }

}

再次运行,就有内容了。。。。

这么写很糟啊,

好吧,太久不用maven,还是改成gradle。。。。


3,搭建项目,通过gradle

改改这个就好了,其他不变。。。。

经历了更加漫长的等待,快下班了。。。。

这个看起来要清爽一些。。。。

这个的入口类竟然自动变成了 模块名+Application,比刚才那个好多了。。。。

依然是直接就可以运行。。。。

4,简单实现 webService....

按网上各种demo一直405,找了半天,发现 doGet注释掉 super.doGet()就好了。。。。

SENRSL:Downloads senrsl$ curl 'http://localhost:8080/test01?name=aaaa'
{"timestamp":"2020-09-27T08:32:33.972+00:00","status":405,"error":"Method Not Allowed","message":"","path":"/test01"}

SENRSL:Downloads senrsl$ curl 'http://localhost:8080/test01?name=aaaa'
Test01HttpServlet    name=aaaa    welcome!!!

SENRSL:Downloads senrsl$

终于换个页面


然后看了下super.doGet的实现

/**
 * Called by the server (via the <code>service</code> method) to
 * allow a servlet to handle a GET request.
 *
 * <p>Overriding this method to support a GET request also
 * automatically supports an HTTP HEAD request. A HEAD
 * request is a GET request that returns no body in the
 * response, only the request header fields.
 *
 * <p>When overriding this method, read the request data,
 * write the response headers, get the response's writer or
 * output stream object, and finally, write the response data.
 * It's best to include content type and encoding. When using
 * a <code>PrintWriter</code> object to return the response,
 * set the content type before accessing the
 * <code>PrintWriter</code> object.
 *
 * <p>The servlet container must write the headers before
 * committing the response, because in HTTP the headers must be sent
 * before the response body.
 *
 * <p>Where possible, set the Content-Length header (with the
 * {@link javax.servlet.ServletResponse#setContentLength} method),
 * to allow the servlet container to use a persistent connection
 * to return its response to the client, improving performance.
 * The content length is automatically set if the entire response fits
 * inside the response buffer.
 *
 * <p>When using HTTP 1.1 chunked encoding (which means that the response
 * has a Transfer-Encoding header), do not set the Content-Length header.
 *
 * <p>The GET method should be safe, that is, without
 * any side effects for which users are held responsible.
 * For example, most form queries have no side effects.
 * If a client request is intended to change stored data,
 * the request should use some other HTTP method.
 *
 * <p>The GET method should also be idempotent, meaning
 * that it can be safely repeated. Sometimes making a
 * method safe also makes it idempotent. For example,
 * repeating queries is both safe and idempotent, but
 * buying a product online or modifying data is neither
 * safe nor idempotent.
 *
 * <p>If the request is incorrectly formatted, <code>doGet</code>
 * returns an HTTP "Bad Request" message.
 *
 * @param req   an {@link HttpServletRequest} object that
 *                  contains the request the client has made
 *                  of the servlet
 *
 * @param resp  an {@link HttpServletResponse} object that
 *                  contains the response the servlet sends
 *                  to the client
 *
 * @exception IOException   if an input or output error is
 *                              detected when the servlet handles
 *                              the GET request
 *
 * @exception ServletException  if the request for the GET
 *                                  could not be handled
 *
 * @see javax.servlet.ServletResponse#setContentType
 */
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
{
    String msg = lStrings.getString("http.method_get_not_supported");
    sendMethodNotAllowed(req, resp, msg);
}

好吧,默认都是405.。。。。

然后 doPost:

SENRSL:Downloads senrsl$ curl 'http://localhost:8080/test01?name=aaaa&age=18'
Test01HttpServlet    name=aaaa&age=18    welcome!!!
Test01HttpServlet    name=aaaa&age=18    welcome!!!aaaaSENRSL:Downloads senrsl$
SENRSL:Downloads senrsl$
SENRSL:Downloads senrsl$ curl -d 'name=bbbb&age=16' -X POST http://localhost:8080/test01
Test01HttpServlet    null    welcome!!!
Test01HttpServlet    null    welcome!!!bbbbSENRSL:Downloads senrsl$


当然,茴字有四种写法。。。。

收拾收拾放假了!!!

2020年09月27日16:58:44


x. 缩写回顾

pom: Project Object Model,项目对象模型。

JPA: Java Persistence API,Java持久化API。


source: https://github.com/senRsl/TestSpringBoot


--
senRsl
2020年09月27日14:25:25

没有评论 :

发表评论