Spring Security 初始化

  1. 导入依赖
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>6.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>6.1.1</version>
</dependency>
  1. 创建SecurityInitializer
package com.example.init
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
//不用重写任何内容
//这里实际上会自动注册一个Filter,SpringSecurity底层就是依靠N个过滤器实现的,我们之后再探讨
}
  1. 创建配置类
package com.example.config
@Configuration
@EnableWebSecurity //开启WebSecurity相关功能
public class SecurityConfiguration {

}
  1. MainInitializer添加配置文件
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{MainConfiguration.class, SecurityConfiguration.class};
}

Post表单认证

在POST请求中需要携带页面中的csrfToken,否则一律进行拦截操作

<input type="text" th:id="${_csrf.getParameterName()}" th:value="${_csrf.token}" hidden>

密码加密

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

//将BCryptPasswordEncoder直接注册为Bean,Security会自动进行选择
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}

使用

encoder.encode(yourPassword);

关闭CSFR

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csfr(conf -> {
// 关闭CSFR
conf.disable();
})
}
}

自定义登录页

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
// 验证请求拦截和放行配置
.authorizeHttpRequests(auth -> {
// 将所有请求全部拦截,一律需要验证
auth.anyRequest().authenticated();
})
// 表单登录相关配置
.formLogin(conf -> {
conf.loginPage("/login"); // 将登录页设置为我们自己的登录页面
conf.loginProcessingUrl("/doLogin"); // 登录表单提交的地址,可以自定义
conf.defaultSuccessUrl("/"); // 登录成功后跳转的页面
conf.permitAll(); // 将登录相关的地址放行,否则未登录的用户无法进入登录界面
// 用户名和密码的表单字段名称
conf.usernameParameter("username");
conf.passwordParameter("password");
})
// 退出登录
.logout(conf -> {
...
})
.build();
}
}

记住密码

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.rememberMe(conf -> {
conf.alwaysRemember(false);
})

MVC

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.0.10</version>
</dependency>

Controller

页面

@Controller   //直接添加注解即可
public class HelloController {

@RequestMapping("/index") //直接填写访问路径
public ModelAndView index(){
ModelAndView modelAndView = new ModelAndView("index");
modelAndView.getModel().put("arg", "value"); //将name传递给Model
return modelAndView;
//返回后会经过视图解析器进行处理
}

@RequestMapping(value = "/index")
public String index(Model model){ //这里不仅仅可以是Model,还可以是Map、ModelMap
model.addAttribute("arg", "value");
return "index";
}
}

重定向

@RequestMapping("/index")
public String index(){
return "redirect:page";
}

请求转发

@RequestMapping("/index")
public String index(){
return "forward:home";
}

Bean的Web作用域

Bean的作用域:

  1. Singleton
  2. Prototype
  3. Request HTTP请求产生新实例,结束后Bean消失
  4. Session 每一个会话
  5. Global Session

RESTFul

一种设计风格。RESTful风格的设计允许将参数通过URL拼接传到服务端。

http://localhost:8080/mvc/index/13579
@RequestMapping("/index/{str}")
public String index(@PathVariable String str) {
System.out.println(str);
return "index";
}

文件上传

public class MainInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

...

@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
// 直接通过registration配置Multipart相关配置,必须配置临时上传路径,建议选择方便打开的
// 同样可以设置其他属性:maxFileSize, maxRequestSize, fileSizeThreshold
registration.setMultipartConfig(new MultipartConfigElement("/path/to/save"));
}
}

Controller模板

@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam MultipartFile file) throws IOException {
File fileObj = new File("filename.png");
file.transferTo(fileObj);
System.out.println("用户上传的文件已保存到:"+fileObj.getAbsolutePath());
return "文件上传成功!";
}

前端模板

<div>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
</div>

application.properties

Property形式

server.port=80 // 端口号
aruge.arugement=value
@Value("{argue.argument}")
String argu;

YAML形式

server:
port: 80

spring:
datasource:
url: jdbc:mysql://localhost:3306/db_name
username:
password:
driver-class-name: com.mysql.cj.Driver
mvc:
static-path-pattern: /static/**
security:
filter:
order: -100 # Spring Security Filter 优先级
user:
name: 'admin'
password: 'Abc123.'
roles:
- admin
- user
阅读全文 »

所有的Java云平台都能够使用基于JAR的打包方式,WAR文件只在一些云平台上能够运行。

Pom.xml 更换 Maven 源

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.springframework.quoters</groupId>
<artifactId>quoters-incorporated</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>quoters-incorporated</name>
<description>REST service to support the guides</description>

<developers>
<developer>
<id>gturnquist</id>
<name>Greg Turnquist</name>
<email>gturnquist at vmware.com</email>
<organization>VMware, Inc.</organization>
<roles>
<role>Project Lead</role>
</roles>
</developer>
</developers>

<organization>
<name>VMware, Inc.</name>
<url>https://spring.io</url>
</organization>

<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>https://www.apache.org/licenses/LICENSE-2.0</url>
<comments>
Copyright 2011 the original author or authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied.
See the License for the specific language governing permissions and
limitations under the License.
</comments>
</license>
</licenses>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<!-- 配置阿里云仓库 -->
<repositories>
<repository>
<id>aliyun-repos</id>
<url>https://maven.aliyun.com/repository/public</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>aliyun-repos</id>
<url>https://maven.aliyun.com/repository/public</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

Tight Coupling 紧耦合

在Spring框架以前,使用排序算法需要将算法实例化

public class ComplexBusinessService {
SortAlgorithm sortAlgorithm = new BubbleSortAlgorithm;
}
public class BubbleSortAlgorithm implements SortAlgorithm {...}

Good code has loose coupling.

移除依赖项的实例化可以移除紧耦合

public class ComplexBusinessService {
SortAlgorithm sortAlgorithm; // = new BubbleSortAlgorithm();

public ComplexBusinessService(SortAlgorithm sortAlgorithm) { // 创建构造函数
this.sortAlgorithm = sortAlgorithm;
}

public classBubbleSortAlgorithm implements SortAlgorithm {...}

Spring Framework instantiates objects and populates the dependencies.

阅读全文 »

网络搜索

网站 URL 备注
哔哩哔哩 https://search.bilibili.com/all?keyword={query}
知乎 https://www.zhihu.com/search?type=content&q={query}
百度贴吧 https://tieba.baidu.com/f?ie=utf-8&kw={query}&fr=search 优先搜索吧名
小红书 https://www.xiaohongshu.com/search_result?keyword={query}&source=web_search_result_notes 需要登录
淘宝 https://s.taobao.com/search?q={query}&commend=all&search_type=item&sourceId=tb.index&ie=utf8
京东 https://search.jd.com/Search?keyword={query}&enc=utf-8
咸鱼 https://www.goofish.com/search?q={query}
Yandex https://yandex.com/search/?text={query}
GitHub https://github.com/search?q={query}&type=repositories
tldr https://tldr.inbrowser.app/pages/common/{query} mannual查Linux命令
必应翻译 https://cn.bing.com/translator?ref=TThis&text={query}&from=en&to=zh-Hant 英译中
DeepL翻译 https://www.deepl.com/translator#en/zh/{query} 英译中
Wiki外部网站 https://encyclopedia.thefreedictionary.com/{query}
求闻百科 https://www.qiuwenbaike.cn/wiki/{query}
Wolfram|Alpha https://www.wolframalpha.com/input?i={query}&lang=zh
  • 有时候站内搜索没有搜索引擎准确,可以使用搜索引擎过滤网站
    过滤站点:
http://<ENGINE.URL>/search?text=site%3A<SITE.URL>%20{query}

启动应用

功能 路径 参数
当前目录启动终端 wt.exe -d “{current_folder}”
Golden Dict查词 GoldenDict.exe -s {query}
启动ipython wt.exe ipython
查看网络连接 control.exe ncpa.cpl
编辑环境变量(需要管理员权限) rundll32 sysdm.cpl,EditEnvironmentVariables

信息系统架构

  • 信息化系统:前台 + 后台 + 数据库
  • B/S 模式
  • 前端 -> Server[Apache->PHP(TP6.0)] -> SQL DataBase
  • 运行逻辑:
    • Client发送require请求(http协议),包含header(length、refer信息)、body(数据)
    • Apache接受请求,给PHP做处理
    • PHP读取、处理数据;判断数据是否损毁、是否需要退回
    • 数据更新到前端,并返回结果(success/fail)
阅读全文 »

“When in doubt go to the library.” – J.K.Rowling

Catalog

Article1: What Are You Going to Do With That?

What Are You Going to Do With That?

William Deresiewicz(《国家》杂志撰稿人和《新共和》杂志编辑)在斯坦福大学的演讲

The question my title poses, of course, is the one that is classically aimed at humanities majors. What practical value could there possibly be in studying literature or art or philosophy? So you must be wondering why I’m bothering to raise it here, at Stanford, this renowned citadel of science and technology. What doubt can there be that the world will offer you many opportunities to use your degree?

(学习文学、艺术或哲学能有什么用呢?所以你肯定纳闷,我为什么在在以科技堡垒而闻名的斯坦福提出这个问题呢?在大学学位给人带来众多机会的问题上还有什么可怀疑的吗?)

But that’s not the question I’m asking. By “do” I don’t mean a job, and by “that” I don’t mean your major. We are more than our jobs, and education is more than a major. Education is more than college, more even than the totality of your formal schooling, from kindergarten through graduate school. By “What are you going to do,” I mean, what kind of life are you going to lead? And by “that,” I mean everything in your training, formal and informal, that has brought you to be sitting here today, and everything you’re going to be doing for the rest of the time that you’re in school.

(但那不是我提出的问题。这里的“做”并不是指工作,“那”并不是指你的专业。我们不仅仅是要个工作,教育不仅仅是学一门专业。教育也不仅仅是上大学,甚至也不仅是从幼儿园到研究生院的正规学校教育。我说的“你要做什么”的意思是你要过什么样的生活?我所说的“那”指的是你得到的正规或非正规的任何训练, 那些把你送到这里来的东西,你在学校的剩余时间里将要做的任何事。)

阅读全文 »

笔记

命令

hexo new "postName" # 新建文章
hexo new page "pageName" # 新建页面
hexo generate # 生成静态页面至public目录
hexo server # 开启预览访问端口(默认端口4000,'ctrl + c'关闭server)
hexo deploy # 部署到GitHub
hexo help # 查看帮助
hexo version # 查看Hexo的版本

按文章更新时间排序

# Home page setting
# path: Root path for your blogs index page. (default = '')
# per_page: Posts displayed per page. (0 = disable pagination)
# order_by: Posts order. (Order by date descending by default)
index_generator:
path: ''
per_page: 10
order_by: -updated # 默认是-date

背景设置

把你挑选的背景图片命名为:background.jpg,放在blog\themes\next\source\images里,在blog\themes\next\source\css_custom文件的custom.styl首部添加

body {
background:url(/images/background.jpg);
background-attachment: fixed;
}

符号链接

# Windows,有些文件需要文件名相同才能打开
# -d 目录符号链接
mklink /d C:\file\path\Target C:\file\path\Source

安装主题

  1. npm安装在modules下
cd hexo-site
npm install hexo-theme-next
  1. git clone安装
cd hexo-site
git clone https://github.com/next-theme/hexo-theme-next themes/next
# Upgrade
cd themes/next
git pull origin master
# Configuration
cp themes/next/_config.yml _config.next.yml

Hexo

我的配置

# 设置英文字体
global:
family: Source Serif Pro

# layout\_partials\head\head.njk 设置中文字体
{{ next_font() }}
{{ next_vendors('fontawesome') }}
<link href="https://fonts.googleapis.com/css?family=Noto+Serif+SC&display=swap" rel="stylesheet">
# source\css\_variables\base.styl 添加中文字体
$font-family-chinese = "Noto Serif SC"

codes:
family: IBM Plex Mono

codeblock:
theme:
light: stackoverflow-light

Quick Start

npm install hexo-cli -g
hexo init blogFolderName
cd blog
npm install
hexo server

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Create a new post

$ hexo new "My New Post"

More info: Writing

Run server

$ hexo server

More info: Server

Generate static files

$ hexo generate

More info: Generating

Deploy to remote sites

$ hexo deploy

More info: Deployment

Gradescope Autograder

Spring 2018

44个Assn,偏向数据结构
邀请码:MNXYKX
学校:UC Berkeley
直接输入,不要选择2U-UC Berkeley,否则将提示COURSE ENTRY CODE IS INVALID

Spring 2021

19个Assn,偏向软件工程
邀请码:MB7ZPY

文章收录

The Law of the Broken Futon 浮沙筑高台法则

“Since I’m fine now, can’t I add that missing piece later, when it’s actually needed?” Sometimes, yes. But it’s much harder.
Adding the missing piece later means waiting until the damage is already underway, and hellishly difficult to undo.

A Response to “Why Most Unit Testing is Waste”

(Unit Tests) They are based on programmers’ fantasies about how the function should work. But programmers break down requirements into smaller components all the time – this is how you program. Sometimes there are misunderstandings, but that is the exception, not the rule, in my opinion.

2.1 Mystery of Java Restore

When instantiate an Object, obj = new Object(), obj stores the address of the Object, not the specific data struction.

(That is why all type of variables create memory boxes of 64 bits. It is just the memory of the address.)

Therefore, When we use obj2 = obj, Java simply copy the addr of obj and assign it to obj2 (They are pointing to the same Object), that is why when we change obj2.weight it effects obj.weight too.

阅读全文 »

Windows

# 模板
netsh dns add encryption server=<IP Address> dohtemplate=<DOH Template> autoupgrade=yes udpfallback=no

# 腾讯
netsh dns add encryption server=1.12.12.12 dohtemplate=https://doh.pub/dns-query autoupgrade=yes udpfallback=no

netsh dns add encryption server=120.53.53.53 dohtemplate=https://doh.360.cn/dns-query autoupgrade=yes udpfallback=no

查看DoH模板:

$ netsh dns show encryption

223.5.5.5 加密设置
----------------------------------------------------------------------
DNS-over-HTTPS 模板 : https://dns.alidns.com/dns-query
自动升级 : yes
UDP 回退 : no
0%