使用IDEA新建springboot项目时,若出现报错:Cannot download 'https://start.spring.io': connect timed out
解决方法1:手机开热点,电脑连接,再创建springboot项目即可

解决方法2:将url地址改为http://start.spring.io即可

解决方法3:进入到settings,搜索 HTTP Proxy,选择Auto-detect proxy settings,点击下面的Check connection,输入https://start.spring.io点击ok,如果successful证明连接成功

解决方法4:来到电脑的“Windows 安全中心” >“防火墙和网络保护”>“Windows Defender 防火墙”,关闭防火墙

解决方法5:在浏览器中打开:https://start.spring.io或者http://start.spring.io
点击GENERATE CTRL+,然后解压,打开IDEA:file->open->选择解压后的文件夹

0x01 新建spring boot,输出helloworld


0x02 spring boot传递参数
使用@requestParam注解,传入a,b,返回两数和


0x03 spring boot操作mysql数据库
先初始化表

新建spring boot

新建controller包,UserController类
package com.example.demo.web;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
//展示数据
@GetMapping("/getAll")
public List<User> getAll(){
return userMapper.getAll();
}
//插入数据
@GetMapping("/install")
public List<User> install(User user){
userMapper.install(user);
return userMapper.getAll();
}
//删除数据
@GetMapping("/delete")
public List<User> delete(int id){
userMapper.delete(id);
return userMapper.getAll();
}
//修改数据
@GetMapping("/update")
public List<User> update(User user){
userMapper.Update(user);
return userMapper.getAll();
}
//查询数据
@GetMapping("/get")
public User get(int id){
return userMapper.getById(id);
}
}
新建entity包,User(实体)类
package com.example.demo.entity;
public class User {
private int id;
private String name;
private String gender;
}
新建mapper包,UserMapper接口
package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserMapper {
@Select("SELECT * FROM user")
@Results({
@Result(property = "name", column = "name")
})
List<User> getAll();
@Select("select * from user where id=#{id}")
User getById(int id);
@Insert({"insert into user(id,name,gender) values(#{id},#{name},#{gender})"})
void install(User person);
@Update({"update user set name=#{name},gender=#{gender} where id=#{id}"})
void Update(User person);
@Delete("delete from user where id=#{id}")
void delete(int id);
}
application.properties中添加下列语句连接数据库,密码yydl,端口8080
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=yydl
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.type-aliases-package=com.example.demo.mapper
server.port=${port:8080}
pom.xml添加下列依赖,注意mysql版本
<!-- 添加 MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<!-- 注意官网的更新,旧版也不是不可以 -->
<version>1.3.2</version>
</dependency>
<!-- 添加 MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!-- 我的版本是5.7.29 -->
<version>5.7.29</version>
</dependency>
预览

查询数据

增加数据

删除数据

修改数据

0x04 spring boot freemarker
新建spring boot

配置src/main/resources/application.properties
spring.freemarker.template-loader-path=classpath:/templates
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl
编写src/main/resources/templates/index.ftl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>He1lo_W0rld_!<h1>
</body>
</html>
编写src/main/java/com.example.demo/Controller/Hellocontroller.java
package com.example.demo.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class Hellocontroller {
@RequestMapping(value="/")
public String index(){
return "index";
}
}
总览图

运行

0x05 利用http协议抓取微博动态
新建maven项目

添加系统参数:archetypeCatalog=internal

配置settings.xml文件镜像
<mirrors>
<!-- maven官方镜像 -->
<mirror>
<id>mirrorId</id>
<mirrorOf>central</mirrorOf>
<name>Human Readable Name </name>
<url>http://repo1.maven.org/maven2/</url>
</mirror>
<!-- 又一个镜像 -->
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://central.maven.org/maven2</url>
<mirrorOf>central</mirrorOf>
</mirror>
<!-- 阿里云镜像 -->
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/repositories/central/</url>
<mirrorOf>central</mirrorOf>
</mirror>
<!-- junit镜像地址 -->
<mirror>
<id>junit</id>
<name>junit Address/</name>
<url>http://jcenter.bintray.com/</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
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>
<dependencies>
<!--这里这里这里-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
</dependencies>
<groupId>org.example</groupId>
<artifactId>http</artifactId>
<version>1.0-SNAPSHOT</version>
</project>
完整源码:
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
static CloseableHttpClient httpClient= HttpClients.createDefault();
public static void main(String[] args) throws IOException {
String url = "https://weibo.com/u//*你的id*//home?wvr=5&lf=reg";
Map<String,String> map = new LinkedHashMap<>();
map.put("Cookie","/*这里换成你的小饼干*/");
File file = new File("collection.txt");
if(file.exists()){
file.delete();
}
FileOutputStream fout = new FileOutputStream(file);
int times = 100;
for (; times > 0; times--) {
String s = getWithHeader(url, map);
Document document = Jsoup.parse(s);
Elements elements = document.getElementsByTag("script"); //获取所有标签为script的元素
for (Element script : elements) {
String t = script.data();
if (t.contains("pl.content.homefeed.index")) {//寻找目标内容
JSONObject jsonObject = JSONObject.parseObject(t.substring(8, t.lastIndexOf(")"))); //截取出来的字符串为json格式
String html = "<!DOCTYPE html>\n" +
"<html lang=\"en\">\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title>Title</title>\n" +
"</head>\n" +
"<body>\n" +
jsonObject.get("html").toString() +
"\n</body>\n" +
"</html>";//生成html字符串
document = Jsoup.parse(html);//解析html,这里循环利用document节省内存
Elements WB_feed_details = document.getElementsByClass("WB_feed_detail");
for (Element WB_feed_detail : WB_feed_details) {
Elements W_f14s = WB_feed_detail.getElementsByClass("W_f14");//按F12分析出来的,W_f14类包含ID及正文内容
Elements WB_froms = WB_feed_detail.getElementsByClass("WB_from");//微博来源(时间及客户端,超话等等)
for (Element W_f14 : W_f14s) {
fout.write(W_f14.text().getBytes(StandardCharsets.UTF_8));
fout.write("\n".getBytes(StandardCharsets.UTF_8));
}
for (Element WB_from : WB_froms) {
fout.write(WB_from.text().getBytes(StandardCharsets.UTF_8));
fout.write("\n".getBytes(StandardCharsets.UTF_8));
}
fout.write("\n".getBytes(StandardCharsets.UTF_8));
fout.write("\n".getBytes(StandardCharsets.UTF_8));
}
break;
}
}
}
fout.close();
}
public static String getWithHeader(String url , Map<String,String> headers) throws IOException {
HttpGet httpGet = new HttpGet(url);
Header [] header = getHeaders(headers);
httpGet.setHeaders(header);
HttpResponse httpResponse = httpClient.execute(httpGet);
return EntityUtils.toString(httpResponse.getEntity());
}
private static Header[] getHeaders(Map<String,String> headers){
Header[] header = null;
if(headers != null){
header = new Header[headers.size()];
int index = 0;
for(Map.Entry<String,String> entry : headers.entrySet()){
header[index++] = new BasicHeader(entry.getKey(),entry.getValue());
}
}
return header;
}
}
总览图

点击run--edit configurations

运行

0x06 做一个简单登陆系统
直接套用上次的spring boot freemarker项目

Hellocontroller.java
package com.example.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
public class Hellocontroller {
@RequestMapping(value = "/set", method = RequestMethod.POST)
public String setCookies(String id, String pwd, HttpServletResponse response){
if(pwd.equals("123456")){
Cookie cookie=new Cookie("id",id);
response.addCookie(cookie);
return "login";
}
else{
return "index";
}
}
@RequestMapping("/local")
public String local(HttpServletRequest request){
Cookie[] cookies = request.getCookies();
if(cookies != null && cookies.length > 1){//服务器会自动分配一个session id到cookie里面
for(Cookie cookie : cookies)
System.out.println(cookie.getValue());
return "login";
}
else {
return "index";
}
}
@ResponseBody
@RequestMapping(value = "/test",method = RequestMethod.GET)
public String testCookieValue(@CookieValue("id") String id ) {
return "id="+id;
}
}
index.ftl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="/set" method="post">
<label> ID: </label><input type="text" name="id"><br/>
<label>密码: </label><input type="password" name="pwd"><br/>
<input type="submit" value="登录">
</form>
</body>
</html>
运行

0x07 springboot集成ueditor富文本编辑器
①新建springboot项目,添加web和thymeleaf依赖

②下载UEditor源码:https://download.csdn.net/download/m0_37770508/10202511
解压至项目的src/main/resources/static目录下,将jsp目录下的config.json复制到项目的resources根目录下

将index.html复制到项目的src/main/resources/templates目录中
修改其中引入js的src
<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"> </script>
<!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败-->
<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文-->
<script type="text/javascript" charset="utf-8" src="/ueditor/lang/zh-cn/zh-cn.js"></script>
然后进行图片上传配置
<script type="text/javascript">
UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.Editor.prototype.getActionUrl = function(action) {
if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage') {
return 'http://localhost:8080/imgUpload';
//'http://localhost:8080/imgUpload';为方法imgUpload的访问地址
} else {
return this._bkGetActionUrl.call(this, action);
}
}
</script>
③ 创建UeditorContorller类
package com.example.demo.Controller;
@Controller
public class UeditorController {
@RequestMapping("/")
private String showPage(){
return "index";
}
@RequestMapping(value="/ueditor")
@ResponseBody
public String ueditor(HttpServletRequest request) {
return PublicMsg.UEDITOR_CONFIG;
}
@RequestMapping(value="/imgUpload")
@ResponseBody
public Ueditor imgUpload(MultipartFile upfile) {
Ueditor ueditor = new Ueditor();
return ueditor;
}
}
在pom.xml引入相关的依赖
<!--UEditor依赖的jar包 -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
创建Ueditor对象
package com.example.demo.domain;
public class Ueditor {
private String state;private String url;private String title;private String original;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getOriginal() {
return original;
}
public void setOriginal(String original) {
this.original = original;
}
}
新建PublicMsg类
package com.example.demo.util;
public class PublicMsg {
public final static String UEDITOR_CONFIG = "{\n" +
" \"imageActionName\": \"uploadimage\",\n" +
" \"imageFieldName\": \"upfile\",\n" +
" \"imageMaxSize\": 2048000,\n" +
" \"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
" \"imageCompressEnable\": true,\n" +
" \"imageCompressBorder\": 1600,\n" +
" \"imageInsertAlign\": \"none\",\n" +
" \"imageUrlPrefix\": \"\",\n" +
" \"imagePathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
"\n" +
" \"scrawlActionName\": \"uploadscrawl\",\n" +
" \"scrawlFieldName\": \"upfile\",\n" +
" \"scrawlPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
" \"scrawlMaxSize\": 2048000,\n" +
" \"scrawlUrlPrefix\": \"\",\n" +
" \"scrawlInsertAlign\": \"none\",\n" +
"\n" +
" \"snapscreenActionName\": \"uploadimage\",\n" +
" \"snapscreenPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
" \"snapscreenUrlPrefix\": \"\",\n" +
" \"snapscreenInsertAlign\": \"none\",\n" +
"\n" +
" \"catcherLocalDomain\": [\"127.0.0.1\", \"localhost\", \"img.baidu.com\"],\n" +
" \"catcherActionName\": \"catchimage\",\n" +
" \"catcherFieldName\": \"source\",\n" +
" \"catcherPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
" \"catcherUrlPrefix\": \"\",\n" +
" \"catcherMaxSize\": 2048000,\n" +
" \"catcherAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
"\n" +
" \"videoActionName\": \"uploadvideo\",\n" +
" \"videoFieldName\": \"upfile\",\n" +
" \"videoPathFormat\": \"/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
" \"videoUrlPrefix\": \"\",\n" +
" \"videoMaxSize\": 102400000,\n" +
" \"videoAllowFiles\": [\n" +
" \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
" \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\"],\n" +
"\n" +
" \"fileActionName\": \"uploadfile\",\n" +
" \"fileFieldName\": \"upfile\",\n" +
" \"filePathFormat\": \"/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
" \"fileUrlPrefix\": \"\",\n" +
" \"fileMaxSize\": 51200000,\n" +
" \"fileAllowFiles\": [\n" +
" \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
" \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
" \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
" \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
" \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +
" ],\n" +
"\n" +
" \"imageManagerActionName\": \"listimage\",\n" +
" \"imageManagerListPath\": \"/ueditor/jsp/upload/image/\",\n" +
" \"imageManagerListSize\": 20,\n" +
" \"imageManagerUrlPrefix\": \"\",\n" +
" \"imageManagerInsertAlign\": \"none\",\n" +
" \"imageManagerAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
"\n" +
" \"fileManagerActionName\": \"listfile\",\n" +
" \"fileManagerListPath\": \"/ueditor/jsp/upload/file/\",\n" +
" \"fileManagerUrlPrefix\": \"\",\n" +
" \"fileManagerListSize\": 20,\n" +
" \"fileManagerAllowFiles\": [\n" +
" \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
" \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
" \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
" \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
" \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +
" ] \n" +
"\n" +
"}";
/**
* Ueditor的返回状态类型
*/
public enum UeditorMsg{
SUCCESS("SUCCESS"),ERROR("上传失败");
private String v;
UeditorMsg(String v){
this.v =v;
}
public String get(){
return this.v;
}
}
}
配置ueditor.config.js
将:
, serverUrl: URL + "jsp/controller.jsp"
替换为:
, serverUrl: "/ueditor"
结构预览

运行项目,访问localhost:8080看一下效果

运行时可能报错:Can't use Subversion command line client: svn Probably the path to Subversion executable is wrong
解决方法在这:https://www.jianshu.com/p/785c618ccfd2?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation
最后附上集成后的源码
链接:https://pan.baidu.com/s/18PAybpYhKGhFKvXgC4Qtmg 提取码:57wm
网友评论