日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

【Java】SpringBoot入门学习及基本使用

發布時間:2025/5/22 java 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Java】SpringBoot入门学习及基本使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

SpringBoot入門及基本使用

SpringBoot的介紹我就不多說了,核心的就是“約定大于配置”,接下來直接上干貨吧!

本文的實例: github-LPCloud,歡迎star&fork。

SpringBoot基礎配置

web.xml保持原樣即可:

<?xml version="1.0" encoding="UTF-8"?> <web-app 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"version="3.1"><!--<welcome-file-list>--><!--<welcome-file>index.html</welcome-file>--><!--</welcome-file-list>--> </web-app>

pom.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>groupId</groupId><artifactId>863Project1</artifactId><version>1.0.0</version><!--以war包形式打包,很關鍵!--><packaging>war</packaging><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.3.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.22</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId><scope>provided</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency></dependencies><!--支持maven--><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build> </project>

啟動入口 SpringBootApplication MainController.java

package com.springboot;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan;/*** Author: puyangsky* Date: 17/5/7*/@SpringBootApplication @EnableConfigurationProperties @ComponentScan(basePackages = {"com.springboot"}) public class Application extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(Application.class);} }

Controller層跳轉到頁面

修改appliction.properties,增加以下配置:

# 配置jsp文件的位置,默認位置為:src/main/webapp spring.mvc.view.prefix=/views/ # 配置jsp文件的后綴 spring.mvc.view.suffix=.html

因此在Controller層返回一個字符串如“index”可以映射到src/main/webapp/views/index.html,即跳轉到該頁面。

靜態資源訪問

兩種方式可以實現靜態資源訪問,參考文章:

一、修改application.properties:
加入以下配置:

# 默認值為 /** spring.mvc.static-path-pattern= # 默認值為 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ spring.resources.static-locations=/static/,這里設置要指向的路徑,多個使用英文逗號隔開,

注意這里有個非常坑的地方,SpringBoot默認的classpath為/src/main/resources目錄,也就是說在spring.resources.static-locations中配置的地址都是在這個文件夾下面,放在其他地方就無法訪問了,直接報404。

二、自定義配置,增加資源處理器:

StaticConfig.java

package com.springboot.config;import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;/*** Author: puyangsky* Date: 17/5/8*/ @Configuration public class StaticConfig extends WebMvcConfigurerAdapter {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");super.addResourceHandlers(registry);} }

中文亂碼解決

向application.properties中添加以下配置,參考文章:

spring.http.encoding.force=true spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true server.tomcat.uri-encoding=UTF-8

@Autowired、@Resource無法自動注入Bean

開始我也遇到了這個問題,搜索之后看到這篇文章,其中的原因是啟動入口Application.java的位置太深入了,如果沒有手動對掃描的包進行配置,如

@ComponentScan(basePackages = {"com.springboot"})

Spring就不會對相應的層級進行掃描,而只掃描Applciation.java當前及其中的類,所以一種范式就是把入口啟動文件放在最外層,或者自己手動配置一下掃描的包。

前后端交互例子

實體類:User.java

package com.springboot.model;/*** Author: puyangsky* Date: 17/5/9*/ public class User {private String email;private String password;public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;} }

Controller層代碼,POST請求,接收json格式,使用@RequestBody將接收到數據轉換為User對象,并用@ResponseBody注解將字符串直接返回到前端。

@Controller @RequestMapping("/api") public class ApiController {@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "application/json")@ResponseBodyString login(HttpServletRequest request, @RequestBody User user) {if (user == null)return "fail";if (user.getEmail().equals("admin@osvt.net") && user.getPassword().equals("123456")){request.getSession().setAttribute("user", "admin");return "success";}else {return "fail";}} }

前端頁面使用ajax與后端API交互,html文件太長就不全貼上來了只放核心部分,文件地址:

<script>$("#submit").click(function () {var email = $("#inputEmail").val();var pwd = $("#inputPassword").val();var user = {"email": email, "password": pwd};$.ajax({url:"api/login", //指定POST的API地址type:"POST",contentType: 'application/json', //指定json格式async:false, //默認為異步,false指定為同步timeout:1000,data: JSON.stringify(user), //json化對象success:function(result){if (result == "success") {$("#loginSuccess").html("登錄成功").show().delay(2000).hide(0);setTimeout(function () {window.location.href = "/index";}, 2000);}else {$("#loginSuccess").html("登錄失敗").show().delay(2000).hide(0);setTimeout(function () {window.location.href = "/login";}, 2000);}},error:function (xhr,status) {alert("error: " + status);window.location.href = "/login";}});}); </script>

注意:

  • 如果前后端數據格式沒有對上,比如后端實體類參數和前端發送的json數據不匹配,就會報400Error。
  • 我在使用ajax過程中遇到一個詭異的錯誤:

    org.apache.catalina.connector.ClientAbortException: java.io.IOException: Broken pipe

    也沒有搜到合適的方式解決,只是說原因是因為后端還在發送數據,前端就將這個連接關閉,比如說頁面跳轉,那么這個連接肯定就關閉了(http協議底層是TCP連接)。所以我猜測是ajax異步搞的鬼,將ajax的async調為false,即使用同步方式請求后端API,問題就消失了。

轉載于:https://www.cnblogs.com/puyangsky/p/6832017.html

總結

以上是生活随笔為你收集整理的【Java】SpringBoot入门学习及基本使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。