默认支持的文件路径:classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resources
mm.css:
body{
padding: 0;
}
tt.css:
body{
margin: 0;
padding: 0;
}
在我们没有在application.yml配置文件配置前,访问:http://localhost:8080/mm.css,结果如下↓
因为mm.css在自定义的mystatic文件夹下,不被静态资源识别,需要自定义。
但是可以直接访问:http://localhost:8080/common/tt.css,因为tt.css在static文件夹下。
当我们在application.yml配置文件夹下添加上自定义的文件夹后就可以访问了。
application.yml:
spring:
mvc:
static-path-pattern: /**
web:
resources:
static-locations: classpath:/mystatic,classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resources
访问:http://localhost:8080/mm.css,结果如下↓,配置后可以直接访问。
当我们修改application.xml文件后:
spring:
mvc:
static-path-pattern: /css/**
web:
resources:
static-locations: classpath:/mystatic,classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resources
像上面那样访问都是失败的了
我们需要加上/css
才可以
==================================================================================
Convert、Formatter:用于接收浏览器请求的参数自动转化成响应类型的数据Stirng(1988-01-01)-Date(1988-01-01)
User:
package com.keafmd.entity;
import lombok.Data;
import java.util.Date;
/**
-
Keafmd
-
@ClassName: User
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-07 9:53
-
@Blog: https://keafmd.blog.csdn.net/
*/
@Data
public class User {
private String id;
private Integer age;
private String address;
private Date createTime;
}
ConverterController:
package com.keafmd.controller;
import com.keafmd.entity.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
-
Keafmd
-
@ClassName: ConverterController
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-07 9:54
-
@Blog: https://keafmd.blog.csdn.net/
*/
@RestController
public class ConverterController {
/**
-
http://127.0.0.1:8080/user?createTime=2021-04-07 01:02:03
-
@param user
-
@return
*/
@GetMapping(“/user”)
User getUserInfo(User user){
return user;
}
}
DateConverter:
package com.keafmd.config;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
-
Keafmd
-
@ClassName: DateConverter
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-07 9:58
-
@Blog: https://keafmd.blog.csdn.net/
*/
public class DateConverter implements Converter<String, Date> {
/**
-
yyyy-MM-dd
-
@param source
-
@return
*/
@Override
public Date convert(String source) {
try {
return new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”).parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
BootWebMvcConfig:
package com.keafmd.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
-
Keafmd
-
@ClassName: BootWebMvcConfig
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-07 10:27
-
@Blog: https://keafmd.blog.csdn.net/
*/
@Configuration(proxyBeanMethods = false)
public class BootWebMvcConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DateConverter());
}
}
还需要在application.yml配置一下时区和格式。
application.yml:
spring:
jackson:
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss
启动springboot,访问:http://127.0.0.1:8080/user?createTime=2021-04-07 01:02:03
===================================================================
实现基础springmvc的拦截器
MyInterceptor:
package com.keafmd.config;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
-
Keafmd
-
@ClassName: MyInterceptor
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-07 11:41
-
@Blog: https://keafmd.blog.csdn.net/
*/
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println(“MyInterceptor.preHandle”);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println(“MyInterceptor.postHandle”);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println(“MyInterceptor.afterCompletion”);
}
}
在WebMvcConfig中注册拦截器,实现WebMvcConfigrer接口,并声明Bean。
BootWebMvcConfig:
package com.keafmd.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
-
Keafmd
-
@ClassName: BootWebMvcConfig
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-07 10:27
-
@Blog: https://keafmd.blog.csdn.net/
*/
@Configuration(proxyBeanMethods = false)
public class BootWebMvcConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DateConverter());
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册拦截
registry.addInterceptor(new MyInterceptor()).addPathPatterns(“/**”);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
}
@Override
public void configureHandlerExceptionResolvers(List resolvers) {
}
}
=================================================================
BootWebMvcConfig:
package com.keafmd.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
-
Keafmd
-
@ClassName: BootWebMvcConfig
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-07 10:27
-
@Blog: https://keafmd.blog.csdn.net/
*/
@Configuration(proxyBeanMethods = false)
public class BootWebMvcConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DateConverter());
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册拦截
registry.addInterceptor(new MyInterceptor()).addPathPatterns(“/**”);
}
/**
-
映射自定义的跳转界面
-
@param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController(“/index”).setViewName(“index.html”);
registry.addViewController(“/home”).setViewName(“index.html”);
}
}
=================================================================
1、自动配置(在全局额配置文件中修改)
**spring.mvc.static-path-pattern=/
spring.resources.static-locations= classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resources**
2、自定义资源路径
**自定义资源映射,重写WebMvcConfiger实现类的 重写addResourceHandler 方法
调用:addResourceHandler 用于处理哪些路径是静态资源
调用:addResourceLocations用于指定静态资源的实际目录
此方法会覆盖配置文件和默认的静态资源配置**
BootWebMvcConfig:
package com.keafmd.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
-
Keafmd
-
@ClassName: BootWebMvcConfig
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-07 10:27
-
@Blog: https://keafmd.blog.csdn.net/
*/
@Configuration(proxyBeanMethods = false)
public class BootWebMvcConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DateConverter());
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册拦截
registry.addInterceptor(new MyInterceptor()).addPathPatterns(“/**”);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/**
- http://127.0.0.1:8080/images/holiday.png
*/
// registry.addResourceHandler()
// registry.addResourceHandler(“/images/”).addResourceLocations(“classpath:/imgs/”);
registry.addResourceHandler(“/images/**”).
addResourceLocations(“classpath:/imgs/”,
“classpath:/mystatic/” ,
“classpath:/static/” ,
“classpath:/public/” ,
“classpath:/META-INF/resources”,
“classpath:/resources”);
}
}
===================================================================
错误的类型:
-
因为后台程序出错导致的Exception(http 500)
-
因为参数传递错误(http 400)
-
客户端的原因造成的路径不对(http 404)
当有错误产生,默认跳转到/error,指向的是BasicErrorController。
**定制错误响应:
1、有模板引擎的情况下;error/状态码; 【将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的error文件夹下】,发生此状态码的错误就会来到对应的页面
2、没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找
3、以上都没有错误页面,就是默认来到Spring Boot默认的错误提示页面
可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html)**
**页面能获取的信息:
timestamp:时间戳
status:状态码
error:错误提示
exception:异常对象
message:异常消息
errors:JSR303数据校验的错误都在这里**
在WebMvcConfiger的实现类中重写addViewConroller方法。
1、在Controller层面定义异常处理,哪里有异常哪里处理,只在某一个Controller中生效
JspController:
package com.keafmd.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
-
Keafmd
-
@ClassName: JspController
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-07 14:09
-
@Blog: https://keafmd.blog.csdn.net/
*/
@Controller
public class JspController {
/**
-
http://127.0.0.1:8080/toview
-
@return
*/
@GetMapping(“/toview”)
String toview(){
return “/hello.jsp”;
}
@GetMapping(“/business”)
String business(){
int result = 0/0;
return “/index.jsp”;
}
/* @ExceptionHandler(value = Exception.class )
@ResponseBody
String resolveException(HttpServletRequest request, HttpServletResponse response, Exception ex ){
System.out.println(ex.getMessage());
return “{status:‘unup’,msg:‘出错了’}”;
}*/
}
2、定义全局的异常处理方式,定义一个类使用@ControllerAdvice ,在类中定义@ExceptionHandler的注解方法。
MyControllerAdvice:
package com.keafmd.controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
-
Keafmd
-
@ClassName: MyControllerAdvice
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-07 14:07
-
@Blog: https://keafmd.blog.csdn.net/
*/
@RestControllerAdvice
public class MyControllerAdvice {
@ExceptionHandler(value = Exception.class )
// @ResponseBody
String resolveException(HttpServletRequest request, HttpServletResponse response, Exception ex ){
System.out.println(ex.getMessage());
return “{status:‘unup’,msg:‘全局的处理,Controller出错了’}”;
}
}
效果:
=================================================================
新建个项目:springboot-file
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”>
4.0.0
com.keafmd
springboot-file
1.0-SNAPSHOT
jar
org.springframework.boot
spring-boot-starter-parent
2.4.4
org.springframework.boot
spring-boot-devtools
org.springframework.boot
spring-boot-starter-web
org.apache.tomcat.embed
tomcat-embed-jasper
jstl
jstl
1.2
org.apache.tomcat.embed
tomcat-embed-jasper
启动类AppFile:
package com.keafmd;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
-
Keafmd
-
@ClassName: AppFile
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-07 15:08
-
@Blog: https://keafmd.blog.csdn.net/
*/
@SpringBootApplication
public class AppFile {
public static void main(String[] args) {
SpringApplication.run(AppFile.class,args);
}
}
BootConstants:
package com.keafmd.controller;
/**
-
Keafmd
-
@ClassName: BootConstants
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-07 16:07
-
@Blog: https://keafmd.blog.csdn.net/
*/
public interface BootConstants {
public static final String UPLOAD_DIR =“D:\upload”;
}
FileUploadController :
package com.keafmd.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
-
Keafmd
-
@ClassName: FileUploadController
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-07 15:05
-
@Blog: https://keafmd.blog.csdn.net/
*/
@Controller
public class FileUploadController {
@PostMapping(“upload”)
String upload(MultipartFile pic) throws IOException {
//1 将临时空间的文件,转储到 D:\upload
String originalFileName = pic.getOriginalFilename();
//扩展名
String ext = originalFileName.substring(originalFileName.lastIndexOf(“.”));
//转储的新文件名
String newFileName = UUID.randomUUID().toString() + ext;
//转储到 D:\upload 下的 uuid.png/uuid.jpg
pic.transferTo(new File(BootConstants.UPLOAD_DIR, newFileName));
//2 将数据存储到 db
/**
-
当前时间
-
上传的ip
-
操作的工号
-
上传的文件名
*/
//3 跳转到列表页
return “redirect:/list”;
}
@GetMapping(“list”)
String list(Model model) throws IOException {
File[] list = new File(BootConstants.UPLOAD_DIR).listFiles();
model.addAttribute(“fileList”,list);
return “/list.jsp”;
}
}
DownloadController :
package com.keafmd.controller;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
-
Keafmd
-
@ClassName: DownloadController
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-07 16:10
-
@Blog: https://keafmd.blog.csdn.net/
*/
@Controller
public class DownloadController {
/**
-
3000
-
1024 1024 (2048) 954
-
@param path
-
@param response
-
@throws IOException
*/
@GetMapping(“/d1/{path}”)
public void download(@PathVariable String path , HttpServletResponse response) throws IOException {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.addHeader(HttpHeaders.CONTENT_DISPOSITION,“attachment;filename=”+path);
InputStream is = new FileInputStream(new File(BootConstants.UPLOAD_DIR,path));
OutputStream os = response.getOutputStream();
int len = -1;
byte[] bytes = new byte[1024];
while ( (len = is.read(bytes)) != -1){
os.write(bytes,0,len);
}
os.close();
is.close();
}
@GetMapping(“/d2/{path}”)
public ResponseEntity download2(@PathVariable String path ) throws IOException {
return ResponseEntity.ok().
header(HttpHeaders.CONTENT_TYPE,“application/octet-stream”).
header(HttpHeaders.CONTENT_DISPOSITION,“attachment;filename=”+path).
body(new FileSystemResource(new File(BootConstants.UPLOAD_DIR,path)));
}
}
AppConfig :
package com.keafmd.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
-
Keafmd
-
@ClassName: AppConfig
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-07 16:05
-
@Blog: https://keafmd.blog.csdn.net/
*/
@Configuration
public class AppConfig implements WebMvcConfigurer {
/**
-
http://127.0.0.1/form
-
@param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController(“/form”).setViewName(“/upload.jsp”);
}
/**
-
http://127.0.0.1/down/ae37a66f-aec3-4e23-b2ed-7267adcfb2bb.png
-
@param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(“/down/**”).addResourceLocations(“file:D:\upload\”);
}
}
server:
port: 80
list.jsp:
<%–
Created by IntelliJ IDEA.
User: lenovo
Date: 2021/4/7
Time: 15:07
To change this template use File | Settings | File Templates.
–%>
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>
<%@taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core” %>
<c:forEach items=“${fileList}” var=“file” varStatus=“stat”>
${stat.count} ${file.getName()}</c:forEach>
upload.jsp:
<%–
Created by IntelliJ IDEA.
User: lenovo
Date: 2021/4/7
Time: 16:10
To change this template use File | Settings | File Templates.
–%>
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>
上传:
下载:
========================================================================
我们在传参的时候,有时候需要对传的参数进行验证是否符合要求,这就需要就行数据校验了。
说明:SpringBoot的2.2.x版本之前,如果使用starter-web默认包含校验框架,2.3.x之后或者没有使用starter-web,需要添加starter-validation的校验框架。
common的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”>
spring-boot-02
com.keafmd
1.0-SNAPSHOT
4.0.0
common
org.hibernate.validator
hibernate-validator
spring-boot-06的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 https://maven.apache.org/xsd/maven-4.0.0.xsd”>
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.4.4
com.keafmd
spring-boot-06
0.0.1-SNAPSHOT
spring-boot-06
Demo project for Spring Boot
<java.version>1.8</java.version>
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
com.keafmd
common
1.0-SNAPSHOT
org.hibernate.validator
hibernate-validator
org.springframework.boot
spring-boot-maven-plugin
org.projectlombok
lombok
common的实体类User:
package com.keafmd.entity;
import lombok.Data;
import javax.validation.constraints.Max;
import java.util.Date;
/**
-
Keafmd
-
@ClassName: User
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-08 9:07
-
@Blog: https://keafmd.blog.csdn.net/
*/
@Data
public class User {
private String id;
@Max(value = 18,message = “年龄不符合”)
private Integer age;
private String address;
private Date createTime;
}
UserController:
package com.keafmd.controller;
import com.keafmd.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
-
Keafmd
-
@ClassName: UserController
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-08 9:10
-
@Blog: https://keafmd.blog.csdn.net/
*/
@RestController
@RequestMapping(“user”)
public class UserController {
/**
-
http://127.0.0.1/user/save?age=20
-
@param user
-
@return
*/
@RequestMapping(“save”)
User save(@Validated User user,BindingResult bindingResult){
System.out.println(bindingResult.getFieldError().getDefaultMessage());
return user;
}
}
SpringBoot06Application
package com.keafmd;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBoot06Application {
public static void main(String[] args) {
SpringApplication.run(SpringBoot06Application.class, args);
}
}
浏览器访问:http://127.0.0.1/user/save?age=20
idea控制台的输出信息:
注册Servlet三大组件【Servlet、Filter、Listener】
================================================================================================
在启动类上添加@ServletComponentScan
SpringBoot06Application:
package com.keafmd;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
@ServletComponentScan
public class SpringBoot06Application {
public static void main(String[] args) {
SpringApplication.run(SpringBoot06Application.class, args);
}
}
定义Servlet
FirstSerlvet :
package com.keafmd.servletcomponent;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
-
Keafmd
-
@ClassName: FirstSerlvet
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-08 9:55
-
@Blog: https://keafmd.blog.csdn.net/
*/
/**
- http://127.0.0.1/my
*/
@WebServlet(urlPatterns = “/my”)
public class FirstSerlvet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(“FirstSerlvet.doPost”);
System.out.println("sessionid: "+req.getSession().getId());
}
}
定义的Filter
FirstFilter:
package com.keafmd.servletcomponent;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
-
Keafmd
-
@ClassName: FirstFilter
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-08 9:56
-
@Blog: https://keafmd.blog.csdn.net/
*/
@WebFilter(urlPatterns=“/*”)
public class FirstFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println(“FirstFilter.doFilter”);
filterChain.doFilter(servletRequest,servletResponse);
}
}
定义Listener
FirstListener:
package com.keafmd.servletcomponent;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
-
Keafmd
-
@ClassName: FirstListener
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-08 9:57
-
@Blog: https://keafmd.blog.csdn.net/
*/
@WebListener
public class FirstListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println(“FirstListener.sessionCreated: Session被创建”);
}
}
效果
访问:http://127.0.0.1/my
访问后,前端不会有什么效果。
idea的控制台的输出证明使用成功。
注意:当我们二次访问http://127.0.0.1/my的时候session应该是一样的。
三大组件使用代码(不需要,@WebListener、@WebServlet(urlPatterns = “/servlet”)、@WebFilter(urlPatterns = “/*”))
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 https://maven.apache.org/xsd/maven-4.0.0.xsd”>
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.4.4
com.keafmd
spring-boot-07
0.0.1-SNAPSHOT
spring-boot-07
Demo project for Spring Boot
<java.version>1.8</java.version>
org.springframework.boot
spring-boot-starter-web
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
org.projectlombok
lombok
application.yml:
server:
port: 80
使用@Bean配合RegistrationBean类型注册
Appconfig:
package com.keafmd.servlet.config;
import com.keafmd.servlet.component.MySessionListener;
import com.keafmd.servlet.component.SecondFilter;
import com.keafmd.servlet.component.SecondServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
-
Keafmd
-
@ClassName: Appconfig
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-08 17:40
-
@Blog: https://keafmd.blog.csdn.net/
*/
@Configuration(proxyBeanMethods = false)
public class Appconfig implements WebMvcConfigurer {
// 使用@Bean配合RegistrationBean类型注册 – star
/**
-
http://127.0.0.1:80/sec
-
http://127.0.0.1:80/second
-
@return
*/
@Bean
ServletRegistrationBean getServletRegistrationBean(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean();
registrationBean.setServlet(new SecondServlet());
registrationBean.addUrlMappings(“/sec”,“/second”);
return registrationBean;
}
@Bean
FilterRegistrationBean getFilterRegistrationBean(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new SecondFilter());
registrationBean.addUrlPatterns(“/*”);
return registrationBean;
}
@Bean
ServletListenerRegistrationBean getServletListenerRegistrationBean(){
ServletListenerRegistrationBean registrationBean = new ServletListenerRegistrationBean();
registrationBean.setListener(new MySessionListener());
return registrationBean;
}
// 使用@Bean配合RegistrationBean类型注册 – end
/* 使用Bean注解定义跨域的Filter*/
@Bean
FilterRegistrationBean cors(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin(“*”);
config.addAllowedHeader(“*”);
config.addAllowedMethod(“*”);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration(“/**”, config);
CorsFilter filter = new CorsFilter(source);
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数前端工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Web前端开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(资料价值较高,非无偿)
![](https://i-blog.csdnimg.cn/blog_migrate/e72b1b3c0d024f1460200bd23681ff29.jpeg)
最后
整理面试题,不是让大家去只刷面试题,而是熟悉目前实际面试中常见的考察方式和知识点,做到心中有数,也可以用来自查及完善知识体系。
《前端基础面试题》,《前端校招面试题精编解析大全》,《前端面试题宝典》,《前端面试题:常用算法》PDF完整版点击这里即可获取!!!!
lter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
-
Keafmd
-
@ClassName: Appconfig
-
@Description:
-
@author: 牛哄哄的柯南
-
@Date: 2021-04-08 17:40
-
@Blog: https://keafmd.blog.csdn.net/
*/
@Configuration(proxyBeanMethods = false)
public class Appconfig implements WebMvcConfigurer {
// 使用@Bean配合RegistrationBean类型注册 – star
/**
-
http://127.0.0.1:80/sec
-
http://127.0.0.1:80/second
-
@return
*/
@Bean
ServletRegistrationBean getServletRegistrationBean(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean();
registrationBean.setServlet(new SecondServlet());
registrationBean.addUrlMappings(“/sec”,“/second”);
return registrationBean;
}
@Bean
FilterRegistrationBean getFilterRegistrationBean(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new SecondFilter());
registrationBean.addUrlPatterns(“/*”);
return registrationBean;
}
@Bean
ServletListenerRegistrationBean getServletListenerRegistrationBean(){
ServletListenerRegistrationBean registrationBean = new ServletListenerRegistrationBean();
registrationBean.setListener(new MySessionListener());
return registrationBean;
}
// 使用@Bean配合RegistrationBean类型注册 – end
/* 使用Bean注解定义跨域的Filter*/
@Bean
FilterRegistrationBean cors(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin(“*”);
config.addAllowedHeader(“*”);
config.addAllowedMethod(“*”);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration(“/**”, config);
CorsFilter filter = new CorsFilter(source);
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数前端工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Web前端开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-XuBwkhFU-1711723342083)]
[外链图片转存中…(img-w57CjuoP-1711723342084)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!
[外链图片转存中…(img-kSN5rH8r-1711723342084)]
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(资料价值较高,非无偿)
![](https://i-blog.csdnimg.cn/blog_migrate/e72b1b3c0d024f1460200bd23681ff29.jpeg)
最后
整理面试题,不是让大家去只刷面试题,而是熟悉目前实际面试中常见的考察方式和知识点,做到心中有数,也可以用来自查及完善知识体系。
《前端基础面试题》,《前端校招面试题精编解析大全》,《前端面试题宝典》,《前端面试题:常用算法》PDF完整版点击这里即可获取!!!!
[外链图片转存中…(img-DBlsM9ad-1711723342085)]
[外链图片转存中…(img-Y4o3rt5O-1711723342085)]
[外链图片转存中…(img-8iCyXMMy-1711723342085)]