springmvc-首页访问
jar包依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.16</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.12.RELEASE</version> </dependency>
|
web.xml
<!-- 配置springmvc前端控制器,对浏览器发送的请求统一处理--> <servlet> <servlet-name>springmvcdemo</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置springmvc的配置文件的 位置 和 名称--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springMVC.xml</param-value> </init-param> <!-- 将前端控制器dispatcherServlet的初始化时间 提前到 服务器 启动时--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvcdemo</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
|
springMVC.xml配置
<!-- 配置组件扫描--> <context:component-scan base-package="com.miao.controller"></context:component-scan>
<!-- 配置Thymeleaf视图解析器 --> <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <!-- 优先级--> <property name="order" value="1"/> <property name="characterEncoding" value="UTF-8"/> <property name="templateEngine"> <bean class="org.thymeleaf.spring5.SpringTemplateEngine"> <property name="templateResolver"> <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!-- 视图前缀 --> <property name="prefix" value="/WEB-INF/templates/"/>
<!-- 视图后缀 --> <property name="suffix" value=".html"/> <property name="templateMode" value="HTML5"/> <property name="characterEncoding" value="UTF-8" /> </bean> </property> </bean> </property> </bean>
|

访问页面


web.xml

webapp

@requestmapping-value
alt + 7 查看 structure

@AliasFor("path") String[] value() default {};
|
可以多个地址访问同一个页面

@requestmapping-method


多个请求方法方式


@requestmapping-params
请求路径携带参数



@PathVariable


原生servletapi 调用


@RequestParam



结果


域对象共享数据
servletAPI共享数据



modelandview共享数据

model

map

modelmap

model–modelmap–map关系
modelmap

model

map

实现

dispatcherServlet流程


对应


springMVC的视图
thymeleaf解析器
dispatcherservlet–processdispatchresult–render

forward转发–地址不变
执行

第一次请求

第二次请求

redirect重定向–两次请求

view-controller
mvc中用来制定首页
<!-- path:设置处理的 请求地址,view-name:请求地址对应的视图名称--> <mvc:view-controller path="/" view-name="index"></mvc:view-controller> <!-- 开启注解驱动--> <mvc:annotation-driven/>
|
restful中的请求方式



开放对静态资源的访问
对静态资源的访问
先是dispatcherservlet寻找–若找不到,交给默认的defaultservlet找

httpMessageConverter–报文信息转换
提供了两个注解和类型
- @requestbody———requestentity
- @responsebody———–responseentity
将请求报文转换为java对象
将java对象转换为响应报文
@responsebody
不走视图,返回字符-succes-

json–返回对象

拦截器的配置
springMVC中的拦截器用于dispatcherservlet
- prehandle:控制器方法执行之前执行,返回类型boolean,返回true放行,false表示拦截
- posthandle:控制器方法执行之后执行
- aftercomplation:处理完视图和模型视图,渲染视图后执行
拦截器配置
@Component public class FirstInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("prehandler"); return HandlerInterceptor.super.preHandle(request, response, handler);
}
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle"); HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); }
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion"); HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } }
@Component public class SecondInterceptor implements HandlerInterceptor {。。。。}
|
springmvc.xml配置
<!-- 配置拦截器_三种方式--> <mvc:interceptors> <!-- <bean class="com.miao.controller.interceptor.FirstInterceptor"></bean>--> <!-- <ref bean="firstInterceptor"></ref>--> <mvc:interceptor> <mvc:mapping path="/**"/> <mvc:exclude-mapping path="/"/> <ref bean="firstInterceptor"></ref> </mvc:interceptor> </mvc:interceptors>
|
三个拦截方法

prehandle
控制器之前执行–按照遍历的顺序

posthandle
控制器之后执行–遍历–倒叙执行

aftercomplation
渲染视图之后执行–遍历–倒叙执行

基于配置异常处理
显示结果


xml中配置

基于注解配置异常处理


注解配置springmvc
用于替换springmvc.xml
@Configuration
@ComponentScan("com.miao.mvc")
@EnableWebMvc public class Webconfig implements WebMvcConfigurer {
@Bean public ITemplateResolver contextTemplateResolver(){ WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext(); ServletContextTemplateResolver contextTemplateResolver = new ServletContextTemplateResolver( webApplicationContext.getServletContext() ); contextTemplateResolver.setPrefix("/WEB-INF/templates/"); contextTemplateResolver.setSuffix(".html"); contextTemplateResolver.setCharacterEncoding("UTF-8"); contextTemplateResolver.setTemplateMode(TemplateMode.HTML); return contextTemplateResolver; } @Bean public SpringTemplateEngine templateEngine(ITemplateResolver contextTemplateResolver){ SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(contextTemplateResolver); return templateEngine; } @Bean public ViewResolver viewResolver(SpringTemplateEngine templateEngine){ ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setCharacterEncoding("UTF-8"); viewResolver.setTemplateEngine(templateEngine); return viewResolver; }
@Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); }
@Override public void addInterceptors(InterceptorRegistry registry) { TestInterceptor testInterceptor = new TestInterceptor(); registry.addInterceptor(testInterceptor).addPathPatterns("/**"); }
@Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/hello").setViewName("hello"); }
@Override public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) { SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver(); Properties properties = new Properties(); properties.setProperty("java.lang.ArithmeticException","error"); simpleMappingExceptionResolver.setExceptionMappings(properties); simpleMappingExceptionResolver.setExceptionAttribute("ex"); resolvers.add(simpleMappingExceptionResolver); } }
|
用来替代web.xml
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{SpringConfig.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{Webconfig.class}; }
@Override protected String[] getServletMappings() { return new String[]{"/"}; }
@Override protected Filter[] getServletFilters() { CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding("UTF-8"); encodingFilter.setForceResponseEncoding(true); HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter(); return new Filter[]{encodingFilter,methodFilter}; } }
|
dispatcherservlet–关系
