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下的文件