SpringBoot2.0 集成 springmvc

SpringBoot 集成 springmvc

1.创建项目,勾选依赖

在这里插入图片描述

2.编写controller

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class Testcontroller {
    @RequestMapping ("test")
    public @ResponseBody  String testBoot(){
        return "hi,boot";
    }
}

3.启动项目,测试

运行启动的类的main方法,在浏览器中输入http://localhost:8080/test

在这里插入图片描述

4.修改应用的端口,路径

application.properties

server.port=8090
server.servlet.context-path=/web01

5.访问项目的静态资源

在这里插入图片描述

Spring的注解开发

(1)什么是@Configuration ,@Bean?
》spring提供xml与注解配置bean对象
》xml方式:applicationContext.xml 中配置 <bean …/>
》注解方式:
@Configuration标记在类上,相当于applicationContext.xml
@Bean配置在返回bean对象的方法上,将返回值对象放入ioc容器中
之后可以使用@Autowired 依赖注入

SpringMVC拦截器

自定义拦截器
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        System.out.println("请求拦截:"+uri);
        return true;
    }

}

在对应application.xml的添加了@Configuration注解的类中注入bean,通过编写方法放回自定义拦截器对象,配置文件类需要实现WebMvcConfigurer接口
import com.lzq.demo_webconfiguration.interceptor.MyInterceptor;
import org.springframework.context.annotation.Bean;
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 MySpringMVCConfiguration implements WebMvcConfigurer {
    @Bean
    public MyInterceptor getMyInterCeptor(){
        return new MyInterceptor();
    }
	//为拦截器添加拦截路径
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getMyInterCeptor()).addPathPatterns("/*");
    }
}

静态资源不会被拦截器所拦截,如static下的文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值