SpringMVC学习
SpringMVC学习
一、SpringMVC概述
- SpringMVC是基于Java实现了MVC模型的轻量级Web框架。
二、SpringMVC开发
2.1、基于配置开发
2.1.1、相关依赖导入
<?xml version="1.0" encoding="UTF-8"?>
4.0.0
com.itheima
SpringMVC01
1.0-SNAPSHOT
war
javax.servlet
javax.servlet-api
3.1.0
provided
javax.servlet.jsp
jsp-api
2.0
provided
org.springframework
spring-context
5.1.9.RELEASE
org.springframework
spring-web
5.1.9.RELEASE
org.springframework
spring-webmvc
5.1.9.RELEASE
org.projectlombok
lombok
1.16.6
com.fasterxml.jackson.core
jackson-core
2.9.0
com.fasterxml.jackson.core
jackson-databind
2.9.0
com.fasterxml.jackson.core
jackson-annotations
2.9.0
org.apache.maven.plugins
maven-compiler-plugin
1.8
1.8
utf-8
org.apache.tomcat.maven
tomcat7-maven-plugin
2.2
80
/
2.1.2、核心配置文件
1、在resources中定义spring-mvc.xml文件
<?xml version="1.0" encoding="UTF-8"?>
// Controller 处理之后的结果会被拼接这个地址,转发到对应JSP文件总展示
// “ /test ”是前端拼接的地址,对应的请求会被 class 对应的 Controller 处理
2、在WEB-INFO文件的web.xml文件中定义相关配置
<?xml version="1.0" encoding="UTF-8"?>
dispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath*:applicationcontent.xml
1
dispatcherServlet
/
1、springmvc配置拦截的三种方式
- " / ": 拦截所有请求但是不包括JSP页面,但是会拦截静态页面如:img、js、css
- " /* " : 拦截所有请求包括JSP页面
- “ *.do ” : 所以以“ .do ”结尾的前端请求都会被拦截
2.1.3、定义一个类作为控制器
1、方式一:实现“ Controller “ 接口,重写里面方法。
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndViw mv = new ModelAndView();
// 设置访问jsp文件的地址
mv.setViewNew("/hello.jsp");
// 设置需要返回的信息
mv.addObject("msg","welcome to springmvc");
return mv;
}
}
2、方式二:实现” HttpRequestHandler “ 接口,重写里面的方法。
public class TestController implements HttpRequestHandler
public void handleRequest(HttpServlertRequest request,HttpServlertResponse response) throws ServletException,IOException{
System.out.println("welcome to springmvc");
}
注:需要把创建对应的Controller 在 spring-mvc.xml文件中注册成Bean,交给Spring容器进行管理。
2.2、基于注解开发
2.2.1、相关依赖导入
- 和基于配置文件开发导入的依赖一致
2.2.2、核心配置文件
1、在resources中定义spring-mvc.xml文件
<?xml version="1.0" encoding="UTF-8"?>
// Controller 处理之后的结果会被拼接这个地址,转发到对应JSP文件总展示
2、在WEB-INFO文件的web.xml文件中定义相关配置
- 和基于配置文件开发进行的配置文件一致。
2.2.3、定义一个类作为控制器
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Controller是控制器的注解
*/
@Controller
@RequestMapping("/test")
public class UserController {
@RequestMapping("/save")
public String save() {
System.out.println("save is run .....");
return "/success.jsp";
}
@RequestMapping("/requestParam")
public String requestParam(String name){
System.out.println(name);
return "/success.jsp";
}
}
注:@RequestMapping("/test")这里的“ /test ”,作为父类的路径,前端请求的url地址为:http://localhost:8080/test/save,类里面的每个方法请求的都会加上这个前缀,其也可以不进行配置。如果不配置前端的访问地址为:http://localhost:8080/save。
2.3、基于java代码开发
2.3.1、相关依赖导入
- 和基于配置文件开发导入的依赖一致
2.3.2、配置类的创建
1、定义配置类代替“ 在resources中定义spring-mvc.xml文件 ”。
@Configuration
@ComponentScan("com.itheima.controller") // 指定包扫描的位置
@EnableWebMvc //mvc的注解驱动
public class SpringMVCConfig implements WebMvcConfigurer {
// 注解配置放行指定资源格式
/* public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").addResourceLocations("/img/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
}*/
/**
* 放行静态资源文件 (一般配置这种方式就可以)
* @param configurer
*/
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
==**注意:**==替代Spring-mvc.xml文件,必须实现WebMvcConfigurer接口。
==**注意:**==之前spring-mvc.xml文件是在web.xml中读取的,我们知道,服务器启动时,会自动解析web.xml;那么当我们采用纯注解配置时,如何自动去解析该配置类呢。这里我们会用到之前咱们提到的spi机制。
2、定义配置类代替“ 在WEB-INFO文件的web.xml文件 ”
package com.itheima.config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
import javax.servlet.Filter;
// 该类中onStartup方法会在服务器启动时自动执行
public class WebConfig extends AbstractDispatcherServletInitializer {
// 配置Springmvc容器,加载web层bean
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext acwc = new AnnotationConfigWebApplicationContext();
acwc.register(SpringMVCConfig.class);
return acwc;
}
// 配置DispatcherServlet的访问路径
protected String[] getServletMappings() {
return new String[]{"/"};
}
// 配置Spring容器,加载service层和dao层bean
protected WebApplicationContext createRootApplicationContext() {
AnnotationConfigWebApplicationContext acwc = new AnnotationConfigWebApplicationContext();
acwc.register(SpringConfig.class);
return acwc;
}
// 添加Post请求参数乱码过滤器
protected Filter[] getServletFilter(){
CharacterEncodingFilter cef = new CharacterEncodingFilter();
cef.setEncoding("utf-8");
cef.setForceEncoding(true);
return new Filter[]{cef};
}
}
2.3.2、定义一个类作为控制器
- 和基于注解开发定义的“ Controller ”一致。
三、SpringMVC请求
3.1、请求地址获取
- 1、@RequestMapping 获取请求url:
● 注解用于获取请求的url地址,其可以加在类上和方法上。加上类有作为父路径的作用,所以类中的方法的请求地址都会拼接类上的路径。
2、@RequestMapping 设置请求方式:
● @RequestMapping(value="/testMethod",method=RequestMethod.POST),其中" method "就是用于指定请求方式。
● @RequestMapping(value="/testMethod",method=RequestMethod.POST,method=RequestMethod.GET),支持POST和GET两种方式。
● @RequestMapping(value="/testMethod"),默认支持两种请求方式。
3、@RequestMapping 参数映射配合注解 @PathVariable使用
@RequestMapping(value="/detail/{id}", method = {RequestMethod.GET})
public ModelAndView getDetail(@PathVariable(value="id") Integer id){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("id", id);
modelAndView.setViewName("detail");
return modelAndView;
请求地址:http://localhost:8080/detail/123
4、URL通配符设置:
● 我们还可以通过通配符对URL映射进行配置。
○ “?”: 表示 1 个字符。
○ “*”:表示匹配多个字符。
○ “**”:表示匹配0个或多个路径。
5、URL正则表达式映射:
@RequestMapping(value="/reg/{name:\w+}-{age:\d+}", method = {RequestMethod.GET})
public ModelAndView regUrlTest(@PathVariable(value="name") String name, @PathVariable(value="age") Integer age){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("name", name);
modelAndView.addObject("age", age);
modelAndView.setViewName("regurltest");
return modelAndView;
}
请求地址:http://localhost:8080/reg/Lihua-18 该访问地址能正常访问。
请求地址:http://localhost:8080/reg/Lihua-xx 该访问地址不能正常访问。
6、限制URL所接收的请求参数:
● 指定映射请求必须包含某个参数:@RequestMapping(value="/paramstest", params="example")
○ 地址:http://localhost:8080/paramstest?example ,必须包含“example”才能正确访问。
● 指定映射请求必须不包含某个参数:@RequestMapping(value="/paramstest", params="!example")
○ 地址:http://localhost:8080/paramstest?example ,包含“example”不能正确访问。
● 指定映射请求中或者某参数必须等于某个值:@RequestMapping(value="/paramstest", params="example=test")
○ 地址:http://localhost:8080/paramstest?example=test ,example=test才能正确访问。
● 指定映射请求中或者某参数必须不等于某个值:@RequestMapping(value="/paramstest", params="example=!test")
○ 地址:http://localhost:8080/paramstest?example=test ,example=!test才能正确访问。
● 当我们为params指定多个参数时如:params={"example1", "example2"},表示的是and关系,即两个参数限制必须同时满足。
7、限制URL所接收请求头参数:
● 指定映射请求头必须包含某参数:@RequestMapping(value="/headerTest", headers = "example")
● 指定映射请求头必须不包含某参数:@RequestMapping(value="/headerTest", headers = "!example")。
● .指定映射请求头中或者某参数必须等于某个值:@RequestMapping(value="/headerTest", headers = "Accept=text/html")。
● .指定映射请求头中或者某参数必须不等于某个值:@RequestMapping(value="/headerTest", headers = "Accept!=text/html")。
● 当我们为headers指定多个参数时如:headers={"example1", "example2"},表示的是and关系,即两个参数限制必须同时满足。