Spring Boot---web开发

web开发

    • 1、SpringMVC自动配置概览
    • 2、简单功能分析
    • 3、请求参数处理
        • 3.1、注解
        • 3.2、Servlet API
        • 3.3、复杂参数
        • 3.4、自定义参数
    • 4、数据响应与内容协商
    • 5、视图解析与模板引擎
    • 6、拦截器
    • 7、文件上传
    • 8、异常处理
    • 9、原生Servlet组件
        • 9.1、Servlet API
        • 9.2、RegistrationBean

1、SpringMVC自动配置概览

Spring Boot provides auto-configuration for Spring MVC that works well with most applications.(大多场景我们都无需自定义配置)

2、简单功能分析

  1. 静态资源访问
    静态资源默认目录:called /static (or /public or /resources or /META-INF/resources
    访问 : 当前项目根路径/ + 静态资源名
    改变默认目录和访问路径

application.properties


spring.webflux.static-path-pattern=/resources/**

application.yaml

spring:
  mvc:
    static-path-pattern: /res/** #改变静态资源访问路径(资源存放的路径不会改变)

  resources:
    static-locations: [ classpath:/haha/ ]  #改变静态资源默认存放路径

  1. 欢迎页 index.html
  2. favicon favicon.ico 放在静态资源目录下即可。

3、请求参数处理

@GetMapping("/user") 相当于

@RequestMapping(value = “/user”,method = RequestMethod.GET)

@PostMapping("/user") 相当于
@RequestMapping(value = “/user”,method = RequestMethod.POST)

@DeleteMapping("/user")相当于
@RequestMapping(value = “/user”,method = RequestMethod.DELETE)

@PutMapping("/user") 相当于
@RequestMapping(value = “/user”,method = RequestMethod.PUT)

3.1、注解

@PathVariable(路径变量)

    //  user/2/owner/zhangsan
    @GetMapping("/user/{id}/owner/{username}")
    public Map<String,Object> fun01(@PathVariable("id")Integer id,
                                    @PathVariable("username") String name,
                                    @PathVariable Map<String,String> pv){
     

        Map<String,Object> map = new HashMap<>();


        map.put("id",id);
        return map;
    }

@RequestHeader(请求请求头)
@RequestAttribute(获取request域属性)
@RequestParam(获取请求参数)
@MatrixVariable(矩阵变量)
@CookieValue(获取Cookie值)
@RequestBody(获取请求体)

3.2、Servlet API

WebRequest
ServletRequest
MultipartRequest
HttpSession
javax.servlet.http.PushBuilder
Principal
InputStream
Reader
HttpMethod
Locale
TimeZone
ZoneId

3.3、复杂参数

Map
Errors
BindingResult
Model
RedirectAttributes
ServletResponse
SessionStatus
UriComponentsBuilder
ServletUriComponentsBuilder

3.4、自定义参数

提交过来的所有参数就会全部封装到Person person里面传过来

    @RequestMapping("/index")
    public Map<String,String> fun01(Person person){
     

        Map<String,String> map = new HashMap<>();


        return map;
    }

4、数据响应与内容协商

5、视图解析与模板引擎

thymeleat(引入依赖)

因为SpringBoot不支持jsp,所以引入thymeleat,在html页面引入thymeleat命名空间借此在html页面显示后台传过来的数据

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>

6、拦截器

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
     

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     

        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUser");
        if(null != loginUser){
     

            //放行
            return true;
        }
        response.sendRedirect("login");
        //拦截
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
     

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
     
        
    }
}

import com.miao.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class AdminWebConfig implements WebMvcConfigurer {
     


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
     
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")//拦截的路径
                .excludePathPatterns("/","/login","/css/**","/fonts/**","/js/**","/images/**");//放行的路径
    }
}

7、文件上传

  <form role="form" th:action="@{/load}" method="post" enctype="multipart/form-data">
      <div class="form-group">
          <label for="exampleInputEmail1">邮箱label>
          <input type="email" name="emil" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
      div>
      <div class="form-group">
          <label for="exampleInputPassword1">姓名label>
          <input type="password" name="uname" class="form-control" id="exampleInputPassword1" placeholder="Password">
      div>
      <div class="form-group">
          <label for="exampleInputFile">头像label>
          <input type="file" name="headerImg" id="exampleInputFile">
          <p class="help-block">Example block-level help text here.p>
      div>
      <div class="form-group">
          <label for="exampleInputFile">生活照片label>
          <input type="file" name="photos" id="exampleInputFiles" multiple>
          <p class="help-block">Example block-level help text here.p>
      div>
      <div class="checkbox">
          <label>
              <input type="checkbox"> Check me out
          label>
      div>
      <button type="submit" class="btn btn-primary">提交button>
  form>
    @PostMapping("/load")
    public String load(@RequestParam("emil") String emil, @RequestParam("uname") String uname, @RequestPart("headerImg") MultipartFile headerImg, @RequestPart("photos") MultipartFile[] photos) throws IOException {
     

        if(!headerImg.isEmpty()){
     
            String originalFilename = headerImg.getOriginalFilename();
            headerImg.transferTo(new File("F:\\abc\\"+originalFilename));
        }
        
        if(photos.length>0){
     
            for (MultipartFile photo : photos) {
     
                String originalFilename = photo.getOriginalFilename();
                photo.transferTo(new File("F:\\abc\\"+originalFilename));
            }
        }

        return "index";
    }

8、异常处理

发生异常默认访问/error下的文件
Spring Boot---web开发_第1张图片

9、原生Servlet组件

9.1、Servlet API

@ServletComponentScan(basePackages = “com.miao”)扫描com.miao包下所有类,把Servlet组件加入容器
2、Servlet :@WebServlet(urlPatterns = “/myser”)该Servlet的访问路径为/myser
Filter: @WebFilter(urlPatterns={"/css/","/images/"})
Listener :@WebListener

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;


@WebServlet(urlPatterns = "/myser")
public class UserServlet extends HttpServlet {
     

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        super.doPost(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        super.doGet(req, resp);
    }
}
package com.miao.servlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(urlPatterns = {
     "/css/*","/js/*"})
public class myFilter implements Filter {
     
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
     

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
     

    }

    @Override
    public void destroy() {
     
    
    }
}

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class MyListener  implements ServletContextListener {
     

    @Override
    public void contextInitialized(ServletContextEvent sce) {
     
        System.out.println("监听到项目初始化完成");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
     
        System.out.println("监听到项目销毁");
    }
}

9.2、RegistrationBean

ServletRegistrationBean, FilterRegistrationBean, ServletListenerRegistrationBean

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 javax.servlet.ServletRegistration;
import java.util.Arrays;

@Configuration
public class RegistConfig {
     

    @Bean
    public ServletRegistrationBean myServlet1() {
     
        MyServlet myServlet = new MyServlet();
        return new ServletRegistrationBean(myServlet, "/my", "/my1");
    }

    @Bean
    public FilterRegistrationBean myFilter1() {
     


        MyFilter myFilter = new MyFilter();
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter);

        filterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/css/*"));
        return filterRegistrationBean;

    }

    @Bean
    public ServletListenerRegistrationBean myListener1(){
     

        MyListener listener = new MyListener();
        return new ServletListenerRegistrationBean(listener);
    }
}

(proxyBeanMethods = true) 单实例

你可能感兴趣的:(Spring,Boot,javaweb,SpringBoot)