1 整合SpringMVC:端口
(1)可以修改tomcat的端口和访问项目中的静态资源
(2)如何修改tomcat端口
查询**Properties
server.port=8090
server.servlet.context-path=/web01
设置配置项(前缀+类变量名)到application配置文件中
2 整合SpringMVC:静态资源
http://localhost:8090/web01/js/jquery-2.2.3.min.js
(1)static目录的作用是什么
类型webapp,存放静态资源,如CSS,js,image
该目录下的资源可以直接访问
http://localhost:8090/css/test.css
(2)全局搜索 CLASSPATH_RESOURCE_LOCATIONS
3 Spring的注解开发
(1)什么是@Configuration,@Bean
- spring提供xml与注解配置bean对象
- xml方式:applicationContext.xml中配置<Bean…/>
- 注解方式:
@Configuration
标记在类上,相当于applicationContext.xml
@Bean
配置在返回bean对象的方法上,将返回值对象放入ioc容器中之后可以使用@Autowired
依赖注入`
public class DaoBeanConfig {
@Bean//将当前方法的返回值 放到 ioc容器
public Person getPerson(){
//一般不是@Service @Repository @Controller
Person person = new Person();
person.setPassword("12345");
person.setUsername("root");
return person;
}
}
@Data
public class Person {
private String username;
private String password;
public Person() {
System.out.println("执行Person构造方法");
}
}
@SpringBootTest
class Demo07springmvcApplicationTests {
@Autowired
Person person;//从ioc里面取对象
@Test
void test01() {
System.out.println(person);
}
}
4 SpringMVC @RestController
//@Controller
@RestController
public class Demo01Controller {
只要是返回json给浏览器的方法,返回值类型设置为Object,不需要再加@ResponseBody
5 整合SpringMVC:SpringMVC拦截器
(1)SpringMVC拦截器是什么?
拦截用户对Controller的请求
(2)SpringBoot中如何开发?
1、斜边拦截器(实现HandlerInterceptor);
2、编写配置类实现 WebMvcConfigurer,在该类中添加各种组件;
3、测试
//以前是在springmvc.xml中配置,现在的话使用@Configuration加@Bean
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//拦截器 判断用户是否登录,未登录重定向到登录页
System.out.println("preHandle ");
return true;//true就是放行 false就是不放行
}
}
@Configuration
public class MySpringMVCConfiguration implements WebMvcConfigurer {
@Bean //<bean>
public MyInterceptor getMyInterceptor(){
MyInterceptor myInterceptor = new MyInterceptor();
return myInterceptor;
}
// /* 拦截所有 --> MyInterceptor -->preHandle -->true
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getMyInterceptor()).addPathPatterns("/*");
}
}
http://localhost:8090/web01/css/style.css
没有经过拦截器的
http://localhost:8090/web01/test03
经过拦截器