SpringBoot的Web开发支持【超详细【一篇搞定】果断收藏系列】下

简介: SpringBoot的Web开发支持【超详细【一篇搞定】果断收藏系列】

文件上传与下载


项目目录


新建个项目:springboot-file

1.png


pom.xml


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>com.keafmd</groupId>
    <artifactId>springboot-file</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
        <!--devtools-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- 解析jsp类库  -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
    </dependencies>
</project>

启动类


启动类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);
    }
}

controller


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\\");
    }
}

application.yml


server:
  port: 80

SpringBoot集成使用jsp(超详细)


点这里:SpringBoot集成使用jsp(超详细)


jsp


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" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table border="1" cellspacing="0" cellpadding="0" width="100%">
    <tr>
        <th>序号</th>
        <th>文件名称</th>
        <th>操作</th>
    </tr>
    <c:forEach items="${fileList}" var="file" varStatus="stat">
        <tr>
            <td>${stat.count}</td>
            <td>${file.getName()}</td>
            <td>
                <a href="${pageContext.request.contextPath}/down/04971284-d789-470a-a991-4d690c36b4ac.jpg">下载1</a>
                <a href="${pageContext.request.contextPath}/d1/04971284-d789-470a-a991-4d690c36b4ac.jpg">下载2</a>
                <a href="${pageContext.request.contextPath}/d2/04971284-d789-470a-a991-4d690c36b4ac.jpg">下载3</a>
            </td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

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" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data">
    <input type="file" name="pic">
    <input type="submit" value="上传头像" >
</form>
</body>
</html>

效果


上传:

1.png

下载:

2.png


SpringBoot数据校验


问题引入


     我们在传参的时候,有时候需要对传的参数进行验证是否符合要求,这就需要就行数据校验了。


样例代码


说明:SpringBoot的2.2.x版本之前,如果使用starter-web默认包含校验框架,2.3.x之后或者没有使用starter-web,需要添加starter-validation的校验框架。

1.png


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">
    <parent>
        <artifactId>spring-boot-02</artifactId>
        <groupId>com.keafmd</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>common</artifactId>
<dependencies>
    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
    </dependency>
</dependencies>
</project>

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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.keafmd</groupId>
    <artifactId>spring-boot-06</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-06</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.keafmd</groupId>
            <artifactId>common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

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

1.png


idea控制台的输出信息:

2.png


注册Servlet三大组件【Servlet、Filter、Listener】


使用ServletComponentScan注解扫描

1.png


在启动类上添加@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

1.png

访问后,前端不会有什么效果。


idea的控制台的输出证明使用成功。2.png


注意:当我们二次访问http://127.0.0.1/my的时候session应该是一样的。

3.png


使用registration的Bean注册组件


三大组件使用代码(不需要,@WebListener、@WebServlet(urlPatterns = “/servlet”)、@WebFilter(urlPatterns = “/*”))

1.png


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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.keafmd</groupId>
    <artifactId>spring-boot-07</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-07</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

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<SecondServlet> registrationBean = new ServletRegistrationBean<SecondServlet>();
        registrationBean.setServlet(new SecondServlet());
        registrationBean.addUrlMappings("/sec","/second");
        return registrationBean;
    }
    @Bean
    FilterRegistrationBean getFilterRegistrationBean(){
        FilterRegistrationBean<SecondFilter> registrationBean = new FilterRegistrationBean<SecondFilter>();
        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<CorsFilter> cors(){
        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<CorsFilter>();
        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);
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }
  // 另外一种跨域方式
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedHeaders("*").allowedOrigins("*").allowedMethods("*");
    }
}

定义Servlet


SecondServlet:


package com.keafmd.servlet.component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * Keafmd
 *
 * @ClassName: SecondServlet
 * @Description:
 * @author: 牛哄哄的柯南
 * @Date: 2021-04-08 17:41
 * @Blog: https://keafmd.blog.csdn.net/
 */
public class SecondServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("SecondServlet.doGet");
        System.out.println("sessionid: "+req.getSession().getId());
    }
}

定义Filter


SecondFilter:


package com.keafmd.servlet.component;
import javax.servlet.*;
import java.io.IOException;
/**
 * Keafmd
 *
 * @ClassName: SecondFilter
 * @Description:
 * @author: 牛哄哄的柯南
 * @Date: 2021-04-08 17:41
 * @Blog: https://keafmd.blog.csdn.net/
 */
public class SecondFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("SecondFilter.doFilter 生效了");
        chain.doFilter(request, response);
    }
}

定义Listener


package com.keafmd.servlet.component;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
 * Keafmd
 *
 * @ClassName: MySessionListener
 * @Description:
 * @author: 牛哄哄的柯南
 * @Date: 2021-04-08 17:42
 * @Blog: https://keafmd.blog.csdn.net/
 */
public class MySessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("Session对象被创建");
    }
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
    }
}

使用Bean注解定义跨域的Filter


Appconfig部分代码:


// 使用Bean注解定义跨域的Filter
    @Bean
    FilterRegistrationBean<CorsFilter> cors(){
        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<CorsFilter>();
        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);
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }

第二种跨域方式


Appconfig部分代码:


@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedHeaders("*").allowedOrigins("*").allowedMethods("*");
    }

效果

访问:http://127.0.0.1/sec

1.png

访问:http://127.0.0.1/second

2.png

idea控制台输出效果:

3.png


以上就是SpringBoot的Web开发支持【超详细【一篇搞定】】的全部内容。


相关文章
|
24天前
|
Java API 数据库
构建RESTful API已经成为现代Web开发的标准做法之一。Spring Boot框架因其简洁的配置、快速的启动特性及丰富的功能集而备受开发者青睐。
【10月更文挑战第11天】本文介绍如何使用Spring Boot构建在线图书管理系统的RESTful API。通过创建Spring Boot项目,定义`Book`实体类、`BookRepository`接口和`BookService`服务类,最后实现`BookController`控制器来处理HTTP请求,展示了从基础环境搭建到API测试的完整过程。
36 4
|
26天前
|
XML JSON API
ServiceStack:不仅仅是一个高性能Web API和微服务框架,更是一站式解决方案——深入解析其多协议支持及简便开发流程,带您体验前所未有的.NET开发效率革命
【10月更文挑战第9天】ServiceStack 是一个高性能的 Web API 和微服务框架,支持 JSON、XML、CSV 等多种数据格式。它简化了 .NET 应用的开发流程,提供了直观的 RESTful 服务构建方式。ServiceStack 支持高并发请求和复杂业务逻辑,安装简单,通过 NuGet 包管理器即可快速集成。示例代码展示了如何创建一个返回当前日期的简单服务,包括定义请求和响应 DTO、实现服务逻辑、配置路由和宿主。ServiceStack 还支持 WebSocket、SignalR 等实时通信协议,具备自动验证、自动过滤器等丰富功能,适合快速搭建高性能、可扩展的服务端应用。
86 3
|
8天前
|
设计模式 前端开发 数据库
Python Web开发:Django框架下的全栈开发实战
【10月更文挑战第27天】本文介绍了Django框架在Python Web开发中的应用,涵盖了Django与Flask等框架的比较、项目结构、模型、视图、模板和URL配置等内容,并展示了实际代码示例,帮助读者快速掌握Django全栈开发的核心技术。
82 44
|
3天前
|
前端开发 API 开发者
Python Web开发者必看!AJAX、Fetch API实战技巧,让前后端交互如丝般顺滑!
在Web开发中,前后端的高效交互是提升用户体验的关键。本文通过一个基于Flask框架的博客系统实战案例,详细介绍了如何使用AJAX和Fetch API实现不刷新页面查看评论的功能。从后端路由设置到前端请求处理,全面展示了这两种技术的应用技巧,帮助Python Web开发者提升项目质量和开发效率。
11 1
|
6天前
|
XML 安全 PHP
PHP与SOAP Web服务开发:基础与进阶教程
本文介绍了PHP与SOAP Web服务的基础和进阶知识,涵盖SOAP的基本概念、PHP中的SoapServer和SoapClient类的使用方法,以及服务端和客户端的开发示例。此外,还探讨了安全性、性能优化等高级主题,帮助开发者掌握更高效的Web服务开发技巧。
|
9天前
|
安全 数据库 开发者
Python Web开发:Django框架下的全栈开发实战
【10月更文挑战第26天】本文详细介绍了如何在Django框架下进行全栈开发,包括环境安装与配置、创建项目和应用、定义模型类、运行数据库迁移、创建视图和URL映射、编写模板以及启动开发服务器等步骤,并通过示例代码展示了具体实现过程。
26 2
WK
|
9天前
|
安全 Java 编译器
C++和Java哪个更适合开发web网站
在Web开发领域,C++和Java各具优势。C++以其高性能、低级控制和跨平台性著称,适用于需要高吞吐量和低延迟的场景,如实时交易系统和在线游戏服务器。Java则凭借其跨平台性、丰富的生态系统和强大的安全性,广泛应用于企业级Web开发,如企业管理系统和电子商务平台。选择时需根据项目需求和技术储备综合考虑。
WK
10 0
|
1月前
|
设计模式 测试技术 持续交付
开发复杂Web应用程序
【10月更文挑战第3天】开发复杂Web应用程序
34 2
|
1月前
|
Java PHP
PHP作为广受青睐的服务器端脚本语言,在Web开发中占据重要地位。理解其垃圾回收机制有助于开发高效稳定的PHP应用。
【10月更文挑战第1天】PHP作为广受青睐的服务器端脚本语言,在Web开发中占据重要地位。其垃圾回收机制包括引用计数与循环垃圾回收,对提升应用性能和稳定性至关重要。本文通过具体案例分析,详细探讨PHP垃圾回收机制的工作原理,特别是如何解决循环引用问题。在PHP 8中,垃圾回收机制得到进一步优化,提高了效率和准确性。理解这些机制有助于开发高效稳定的PHP应用。
43 3
|
10天前
|
JavaScript 前端开发 Java
SpringBoot_web开发-webjars&静态资源映射规则
https://www.91chuli.com/ 举例:jquery前端框架
12 0