SpringBoot入门,这一篇就够了
SpringBoot总结(一)——第一个SpringBoot项目
SpringBoot总结(十二)——登录界面的实现
SpringBoot总结(十)——SpringBoot+Mybatis实现数据库的CRUD(从创建到实现【超详细附代码】)
SpringBoot总结(十五)——接口架构风格(RESTful)
SpringBoot相关笔记
JavaEE进阶 - Spring Boot 日志文件 - 细节狂魔
Spring Boot 的 10 个核心模块
Spring Boot项目的搭建和运行 - 聚合工程/父子模块
Vue+SpringBoot(二)实现后台获取数据在前台显示
Vue+SpringBoot(一)简单登录界面的实现
Spring Boot面试题(2020最新版)
springboot个人博客项目面试准备
SpringBoot+Vue项目校园博客系统
基于 SpringBoot + MyBatis 的在线音乐播放器
springboot+jwt+shiro+vue+elementUI+axios+redis+mysql完成一个前后端分离的博客项目(笔记,帮填坑)
(阿里云)Linux部署springboot项目全过程
SpringBoot+Vue项目漫画网站
基于Java+SpringBoot+vue+elementui社区疫情防控系统详细设计实现
springboot+vue练手小项目[前台搭建+后台编写](非常详细)
springboot+vue练手级项目,真实的在线博客系统
叮当外卖单体项目SpringBoot+Mybatis-Plus+Redis(附源码)
SpringBoot知识点整理
Springboot----项目整合微信支付与RabbitMQ(使用RabbitMQ延迟插件实现订单管理)
Springboot----项目整合微信支付(利用RabbitMQ延迟队列处理用户退款)
Springboot----项目整合微信支付(获取支付二维码)
Spring-boot项目练习笔记(三) 文件上传与下载
SSM+Maven高级+MybatisPlus万字笔记
Springboot+Vue前后端分离项目的部署
基于Java+SpringBoot+vue+element实现物流管理系统
你知道Spring Boot项目是怎么启动的吗?
SpringBoot集成Shiro
Springboot 图片上传及图片回显
探究Springboot自动装配原理
【原理分析】细说SpringBoot的自动装配原理
今天面了一个大学生:这82道SpringBoot面试题都答不上来?还想进大厂?
SpringBoot系列学习汇总
源码地址
https://github.com/cainiaolianmengdaduizhang/ssm.git
Spring Web MVC起源
Spring Web MVC 是基于 Servlet API 构建的原始 Web 框架,从⼀开始就包含在 Spring 框架中。它的正式名称“Spring Web MVC”来⾃其源模块的名称(Spring-webmvc),但它通常被称为“SpringMVC”.
1.1 什么是 MVC?
Model View Controller(模型,视图,控制器),他是一种设计模式,这种设计模式将软件(项目)分为三部分: 模型,视图,控制器
MVC思想
MVC 是一种设计思想,而 SpringMVC 是一个 具体的实现框架.
SpringMVC 是一个 基于 MVC 设计模式 和 Servlet API 实现的 Web 框架,同时 SpringMVC 又是 Spring 框架中的一个 WEB 模块,他是随着 Spring 的诞生而存在的一个框架.
Spring 和 SpringMVC 诞生历史比较久远,在他们之后才有了 Spring boot.
为什么需要这么多类注解?
@Controller:表示的是业务逻辑层;
@Servie:服务层;
@Repository:持久层;
@Configuration:配置层;
<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.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>springboot_demoartifactId>
<version>1.0-SNAPSHOTversion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.1.5.RELEASEversion>
parent>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.8version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-loggingartifactId>
dependency>
dependencies>
project>
UserController.java
package com.itterence.controller;
import com.itterence.model.UserInfo;
import lombok.extern.java.Log;
import lombok.extern.jbosslog.JBossLog;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.logging.Logger;
@Slf4j
@Controller
@ResponseBody // 表示的是返回一个非静态页面的数据
@RequestMapping("/user") //类上面的 RequestMapping 可以省略
public class UserController {
@RequestMapping("/sayhi")
public String sayHi(){
return "Hello World!";
}
@RequestMapping("/login")
public String login(String username,String password){
return "用户名 : "+username +"密码 : " +password;
}
@RequestMapping("/getuserbyid")
public UserInfo getUserById(Integer id){
UserInfo userInfo = new UserInfo();
userInfo.setUsername("张三");
userInfo.setAge(18);
return userInfo;
}
@RequestMapping("/getinfo/{id}/{name}")
public String getInfo(@PathVariable Integer id,@PathVariable String name){
return "ID: "+id+"| Name: "+name;
}
@RequestMapping("/upload")
public boolean upload(Integer uid, @RequestPart("img")MultipartFile file){
boolean result = false;
try{
file.transferTo(new File("C:\\Users\\U100926\\Desktop\\spt\\img.jpg"));
result = true;
}catch (IOException e){
log.error("上传失败");
}
return result;
}
// 从配置文件中读取图片的保存路径
@Value("${img.path}")
private String imgPath;
@RequestMapping("/upimg")
public boolean upImg(Integer uid, @RequestPart("img") MultipartFile file) {
boolean result = false;
String fileName = file.getOriginalFilename(); // 得到原图片的名称(xxx.png)
fileName = fileName.substring(fileName.lastIndexOf(".")); // 得到图片后缀(png)
fileName = UUID.randomUUID().toString() + fileName;
// 保存图片到本地目录
try {
file.transferTo(new File(imgPath + fileName));
result = true;
} catch (IOException e) {
log.error("上传图片失败:" + e.getMessage());
}
return result;
}
}
TestController.java
package com.itterence.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
//@ResponseBody
public class TestController {
@RequestMapping("/hi")
public String hii(){
return "index.html";
}
}
CalcController.java
package com.itterence.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CalcController {
@RequestMapping("/calc")
public String calc(Integer num1, Integer num2) {
if (num1 == null || num2 == null) {
return "参数错误
返回";
}
return "结果: "
+ (num1 + num2) + "返回";
}
}
HelloController.java
package com.itterence.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("hello")
public String helloo(){
return "hello,springboot!";
}
}
UserInfo.java
package com.itterence.model;
import lombok.Data;
@Data
public class UserInfo {
private int id;
private String username;
private String password;
private int age;
}
Application.java
package com.itterence;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
logback-spring.xml
<configuration>
<property name="CONSOLE_LOG_PATTERN" value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%level){blue} %clr(${PID}){magenta} %clr([%thread]){orange} %clr(%logger){cyan} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<property name="PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" />
<property name="DEV_FILE_PATH" value="./logs" />
<property name="PRO_FILE_PATH" value="/opt/prod/logs" />
<appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}pattern>
encoder>
appender>
<appender name="fileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%npattern>
encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${DEV_FILE_PATH}/output-%d{yyyy-MM-dd}.logfileNamePattern>
<maxFileSize>10MBmaxFileSize>
<maxHistory>60maxHistory>
a
<totalSizeCap>2GBtotalSizeCap>
rollingPolicy>
appender>
<appender name="errorAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERRORlevel>
filter>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%npattern>
encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${DEV_FILE_PATH}/error-%d{yyyy-MM-dd}.logfileNamePattern>
<maxFileSize>10MBmaxFileSize>
<maxHistory>60maxHistory>
<totalSizeCap>2GBtotalSizeCap>
rollingPolicy>
appender>
<springProfile name="dev">
<root level="INFO">
<appender-ref ref="consoleAppender" />
<appender-ref ref="fileAppender" />
<appender-ref ref="errorAppender" />
root>
springProfile>
<springProfile name="pro">
<root level="INFO">
<appender-ref ref="consoleAppender" />
<appender-ref ref="fileAppender" />
<appender-ref ref="errorAppender" />
root>
springProfile>
configuration>
calc.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<form action="/calc">
<h1>计算器h1>
数字1 : <input name = "num1" type="text"><br>
数字2 : <input name = "num2" type="text"><br>
<input type="submit" value="点击相加">
form>
body>
html>
index.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1 style="color: indianred">
hello springMvc
h1>
body>
html>
http://localhost:8080/calc.html
http://localhost:8080/user/getuserbyid
jQuery Core - All 1.x Versions
LoginController.java
package com.itterence.controller;
import com.itterence.model.UserInfo;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
@RestController
/*
或者这么写
@Controller
@ResponseBody // 表示的是返回一个非静态页面的数据
*/
public class LoginController {
/**
* 获取前端的 json 数据
*
* @param userInfo
* @return
*/
@RequestMapping("/login")
public HashMap<String, Object> login(@RequestBody UserInfo userInfo) {
HashMap<String, Object> result = new HashMap<String, Object>();
int state = 200;
int data = -1; // 等于 1,登录成功,否则登录失败
String msg = "未知错误";
if (StringUtils.hasLength(userInfo.getUsername()) && StringUtils.hasLength(userInfo.getPassword())) {
if (userInfo.getUsername().equals("admin") && userInfo.getPassword().equals("admin")) {
data = 1;
msg = "";
} else {
msg = "用户名或密码失败!";
}
} else { // 参数为空
msg = "非法参数";
}
result.put("state", state);
result.put("data", data);
result.put("msg", msg);
return result;
}
}
doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="js/jquery-1.9.1.min.js">script>
<title>Documenttitle>
<script>
// ajax 提交
function mysub(){
// 1.判空
var username = jQuery("#username");
var password = jQuery("#password");
if(jQuery.trim(username.val())==""){
alert("请先输入用户名!");
username.focus(); // 光标重制到此元素
return;
}
if(jQuery.trim(password.val())==""){
alert("请先输入密码!");
password.focus(); // 光标重制到此元素
return;
}
jQuery.ajax({
url:"/login",
type:"POST",
contentType:"application/json",
data:JSON.stringify({"username":username.val(),
"password":password.val()}),
success:function(result){
alert(JSON.stringify(result));
}
});
}
script>
head>
<body>
<div style="text-align: center;">
<h1>登录h1>
用户:<input id="username">
<br>
密码:<input id="password" type="password">
<br>
<input type="button" value=" 提交 " onclick="mysub()" style="margin-top: 20px;margin-left: 50px;">
div>
body>
html>
http://localhost:8080/login.html
ForwardController.java
package com.itterence.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Controller
//RestController不能用这个
public class ForwardController {
@RequestMapping("/fw")
public String myForward(){
return "forward:/hello.html";
}
@RequestMapping("/fw1")
public String myForward1(){
return "hello.html";
}
@RequestMapping("/rd")
public String myRedirect(){
return "redirect:/hi.html";
}
}
hello.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1 style="color: indianred">
hello springmvc forward
h1>
body>
html>
hi.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1 style="color: royalblue">
hello springmvc redirect
h1>
body>
html>