SpringBoot整合Web开发

  1. SpringBoot通过CORS实现跨域
  2. SpringBoot中加载XML配置
  3. SpringBoot中注册拦截器
  4. CommandLineRunner实现系统启动任务
  5. ApplicationRunner实现系统启动任务
  6. SpringBoot整合Web基础组件
  7. SpringBoot路径映射
  8. SpringBoot中使用类型转换器
  9. SpringBoot整合AOP
  10. SpringBoot自定义欢迎页
  11. springBoot自定义favicon
  12. SpringBoot去除自动化配置

  • SpringBoot通过CORS(跨域源资源共享)实现跨域,是一个W3C标准,是JSONP模式的现代版
  • JSONP虽然能解决跨域问题,但是只支持GET请求
@CrossOrigin(origins="http://localhost:8081")  //表示我愿意接受这个地址的请求
//可以加在类上方也可以加在方法上

//还可以定义一个配置类来实现WebMvcConfigurer,重写里面的addCorsMappings方法,实现全局设置
//就不用再单独在每个controller类上或者方法上添加@CrossOrigin注解
//形如:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry){
        registry.addMapping(pathPattern:"/**")   //设置所有接口可以实现跨域请求
        .allowedOrigins("http://localhost:8081")   //添加需要跨域请求的URL
        .allowedHeaders("*")   //允许所有请求头实现跨域
        .allowedMethods("*")  //允许所有方法实现跨域
        .maxAge(30*1000);  //设置跨域访问的最大时间,30分钟
    }
}
//在前端页面中设置请求方式
<script src="jquery.3.3.1.js"></Script>
......
<body>
<div id="app"><div>
<input type="button" value="GET" onlick="getData()">  //get请求
 <input type="button" value="PUT" onlick="putData()">  //put请求
 <script>
     function getData(){
         $.get('http://localhost:8080/hello',function(msg){
             $("#app").html(msg);
         });
     }
     function putData(){
        $.ajax({
            type:'put',
            url:'http://localhost:8081/doput',
            success:function(msg){
                $("#app").html(msg);
            }
        });
     }
     
//写一个Controller类进行测试
@RestController
//@CorssOrgin(orgins="http://localhost:8081")
public class HelloController {
    @GetMapping("/hello")
    public String hello(){
        return "hello get cors";
    }
    @PutMapping("/doput")
    public String doPut(){
        return "hello put cors";
    }
}     

SpringBoot中加载XML配置

其实springBoot中不涉及XML配置了,如果想配置,也可以 需要在resources目录下新增一个xml文件,在包目录下新增一个configuration配置类,增加一个 @ImportResources注解,引入xml的配置即可 形如: 新建一个类

public class SayHello{
    public String SayHello() {
    return "hello xml";
    }
}

新建一个XML文件

<bean class="org.zh.xml.SayHello" id="sayHello"/>

 新建一个configuration配置类

@Configuration
@ImportResources(locations="classpath:beans.xml")
public class WebMvcConfig{
    
}

 


SpringBoot种注册拦截器,创建一个类 来实现HandlerInterceptor

public class MyInterceptor implements HandlerInterceptor {
     @Override
     public boolean preHandle(HttpServletRequet request,HttpServletResponse response,Object handler)throws Exception{
         System.out.println("preHandle");
         return true;
     }
      @Override
     public boolean postHandle(HttpServletRequet request,HttpServletResponse response,Object handler
     ModelAndView modelAndView)throws Exception{
         System.out.println("postHandle");
         return true;
     }
      @Override
     public boolean preHandle(HttpServletRequet request,HttpServletResponse response,Object handler,
     Exception ex)throws Exception{
         System.out.println("afterCompletion");
         return true;
     }
 }

创建一个WebMvcConfig来实现WebMvcConfigure

@Configuration
 public class WebMvcConfig implements WebMvcConfigurer {
     @Override
     public void addInterceptors(InterceptorRegistry registry) {
         registry.addInterceptor(myInterceptor()).addPathPatterns("/**");//拦截所有路径
         
     }
     @Bean
     MyInterceptor myInterceptor(){
         return new MyInterceptor();
     }
 }

 新建一个helloController测试

@RestController
 public calss helloController{
     @GetMapping("/hello")
     public String hello(){
         return "hello";
     }
 }

CommandLineRunner实现系统启动任务,即系统第一次启动的时候做,以后就不用做了

形同,监听器 新建一个类MyCommandLineRunner来实现CommandLineRunner

@Component
@Order(10)//如果有多个CommandLineRunner,可以用该注解确定优先级,数字越大优先级越低
public class MyCommandLineRunner implements CommandLineRunner{
    @Override
    public void run(String...args)throws Exception{
        
    }
}

 新建一个另一个类MyCommandLineRunner2来实现CommandLineRunner 这个MyCommandLineRunner2优先级大于上面MyCommandLineRunner

@Component
@Order(9)//如果有多个CommandLineRunner,可以用该注解确定优先级,数字越大优先级越低
public class MyCommandLineRunner2 implements CommandLineRunner{
    @Override
    public void run(String...args)throws Exception{
        
    }
}

 新建一个CommandLinerunnerApplication类

@SpringBootApplication //必须
public class CommandLinerunnerApplication{
    public static void main(String[] args){
        SpringApplication.run(CommandLinerunnerApplication.class,args);
    }
}

 

  • ApplicationRunner实现系统启动任务

是系统启动任务的另一种方案 新建一个MyApplicationRunner01实现ApplicationRunner

@Component
@Order(99)
public class MyApplicationRunner01 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args)throws Exception {
        String[] sourceArgs = args.gerSourceArgs();//获取启动的所有参数
        System.out.println("sourceArgs:"+Arrays.toString(sourceArgs));
        List<String> nonOptionArgs = args.getNonOptionArgs();//获取没有key的参数,像数组一样
        System.our.println("nonOptionArgs:"+nonOptionArgs);
        Set<String> OptionNames = args.getOptionNames();//通过key-value的形式获取参数
        for(String optionName : optionNames) {
            System.out.println(optionName+":"+args.getOptionValues(optionName));
        }
        System.out.println("==========MyApplicationRunner01 结束======");
    }
}

 新建一个MyApplicationRunner02实现ApplicationRunner

@Component
@Order(100)
public class MyApplicationRunner02 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args)throws Exception {
        String[] sourceArgs = args.gerSourceArgs();//获取启动的所有参数
        System.out.println("sourceArgs:"+Arrays.toString(sourceArgs));
        List<String> nonOptionArgs = args.getNonOptionArgs();//获取没有key的参数,像数组一样
        System.our.println("nonOptionArgs:"+nonOptionArgs);
        Set<String> OptionNames = args.getOptionNames();//通过key-value的形式获取参数
        for(String optionName : optionNames) {
            System.out.println(optionName+":"+args.getOptionValues(optionName));
        }
        System.out.println("==========MyApplicationRunner02 结束======");
    }
}

SpringBoot整合Web基础组件、Fillter、Servlet、Linstener

 

@WebServlet(urlPatterns="/myServlet")
@WebFilter(urlPatterns="/*")
@WebListener
//在SpringBootApplication启动类上加入
@ServletComponentScan(basePackagss="org.zenghao.servlet")//前提前面三个放在同一个servlet目录下

 


  • SpringBoot路径映射
  • 新建一个WebMvcConfig类实现WebMvcConfigurer
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer{
       @Override
       public void addViewControllers(ViewControllerRegistry registry){
           registry.addViewController(urlPath:"/zenghao").setViewName("hello");
       }
        }
    }

    SpringBoot种使用参数类型转换(假设前端传回来一个日期,后端如何用日期对象去接收)

    @RestController
    public class helloController{
        @Getmapping("/hello")
        public static hello(Date birthday){
            return "hello";
        }
    }
    //重前端浏览器地址栏输入 http://localhost:8080?birth=1997-8-25,后端不报错,前端页面
    //报错,其实是因为无法把String类型转换成Date类型的错误,此时需要新增加一个日期类型Converter转换器
    @Component
    public class DateConverter implements Converter<String,Date> {
          SimpleDateFormat sdf = new SimpleDateFormat(parttern:"yyyy-MM-dd");
          @Override
        public Date Convert(String source) {
            if(source != null&&!"".equals(source)) {
                try{
                    return sdf.parse(source);
                }catch(OarseException e){
                    e.printStackTrace();
                }
            }
            return null;
        }
    }

    SpringBoot整合AOP,(面向切面的编程)

    在pom文件中加入AOP的依赖 

    <dependency>
        <groupId>org.springFramework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

    新建一个UserService类

    public class UserService{
        public String getUserById(Interger id){
            return "zenghao";
        }
        public void deleteUserById(Integer id){
            System.out.println("shangchu")
        }
    }

    新建一个UserController

    @RestController
    public  class UserController{
        @AutoWride
        UserService userService
        @GetMapping("/test1")
        public String getUserById( Integer id){
           return  userService.getUserById(id);
        }
        @GetMapping("test2")
        public void deleteUserById(Integer id){
            userService.deleteUserById(id);
        }
    }

     新建一个SpringBoot组件

    @Component //表示为一个SpringBOot的一个组件
    @Aspect  //表示为一个切面
    public class LogComponent {
        @Poincut("execution(* org.zenmghao.aop.service.*.*(..)"))//所有方法名、类名、参数都可以
        public void pc1(){  //定义拦截规则
        }
        @Before(value="pc1()")  //点义前置通知
        public void before(JoinPoint jp){
            String name = jp.getSignature().getName();
            System.out.println("before"+name);
        }
         @After(value="pc1()")  //点义后前置通知
        public void after(JoinPoint jp){
            String name = jp.getSignature().getName();
            System.out.println("after"+name);
        }
         @AfterReturning(value="pc1()",returning="result")  //点义返回通知
        public void afterReturning(JoinPoint jp,Object result){
            String name = jp.getSignature().getName();
            System.out.println("AfterReturnning"+name+"------"+result);
        }
          @AfterThrowing(value="pc1()",throwing="e")  //点义异常通知
        public void afterThrowing(JoinPoint jp,Exception e){
            String name = jp.getSignature().getName();
            System.out.println("AfterThrowing"+name+"------"+e.getMessage());
        }
          @Around("pc1()")  //点义环绕通知,前面四个的综合
        public void around(ProceedingJoinPoint pip) throws Throwable{
           Object proceed = pjp.proceed();
           return proceed;
        }
    }

    SpringBoot自定义favicon(即访问前端页面时候,浏览器左上角的图标)

    https://tool.lu.favicon/ 放到static目录下,或者resources目录下,static优先级高于resources 放入即可!


  • SpringBoot除去自动化配置
  •  只需要在启动类中加入 @SpringBootApplication(exclude=WebMvcAutoConfiguration.class) //SpringMVC那一套就失效了.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值