SpringMVC
1.SpringMVC介绍
springMVC是一种基于Java实现MVC模型的轻量级Web框架
优点:
-
使用简单,开发便捷(相较于Servelt)
-
灵活性强
使用SpringMVC技术开发web程序流程
-
创建web工程(Maven结构)
-
设置tomcat服务器,加载web工程(tomcat插件)
-
导入坐标(SpringMVC+Servlet)
-
定义处理请求的功能类(UserController)
-
设置请求映射(配置映射关系)
-
将SpringMVC设定加载到Tomcat容器中
SpringMVC入门案例
-
导入SpringMVC坐标与Servlet坐标
<dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version><scope>provided</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.1.5.RELEASE</version> </dependency>
-
初始化SpringMVC环境
@Configuration public class SpringMvcConfig { }
-
创建SpringMVC控制器类(等同于Servlet功能)
@Controller public class UserController {@RequestMapping("/save")@ResponseBodypublic String save(){System.out.println("user save ...");return "{'info':'springmvc'}";} }
-
设定SpringMVC加载对应的bean
@Configuration @ComponentScan("com.zkw.controller") public class SpringMvcConfig { }
-
初始化Servlet容器,加载SpringMVC环境,并设置SpringMVC请求拦截的路径
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {@Overrideprotected WebApplicationContext createServletApplicationContext() {AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();ctx.register(SpringMvcConfig.class);return ctx;} @Overrideprotected String[] getServletMappings() {return new String[]{"/"}; //所有的请求都归springmvc处理} @Overrideprotected WebApplicationContext createRootApplicationContext() {return null;} }
部分代码介绍:
-
@RequestMapping:设置当前控制器方法请求访问路径
-
@ResponseBody:设置当前控制器方法响应内容为当前返回值,无需解析
-
createServletApplicationContext
protected WebApplicationContext createServletApplicationContext()//加载容器 {AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();//初始化容器对象ctx.register(SpringMvcConfig.class);//将配置注册到容器中return ctx;}
-
getServletMappings:设定那些请求归springmvc处理
2.bean的加载控制
因为功能不同,如何避免Spring错误的加载到S平日那个MVC的bean?
A:加载Spring控制的bean的时候,排除掉SpringMVC控制的bean
方式一:设定扫描范围为com.zkw,排除掉controller包内的bean
@Configuration @ComponentScan({"com.zkw.service","com.zkw.dao"}) public class SpringConfig{ }
方式二:设定扫描范围为精准范围,如service包、dao包等
@Configuration @ComponentScan(value="com.zkw",excludeFilters = @ComponentScan.Filtertype = FilterType.ANNOTATION,//排除方法classes = Controller.class) public class SpringConfig{ }
简化开发
public class ServletContainersInitConfig extend AbstractAnnotationConfigDispatcherServeletInitializer{protected Class<?>[] getServletConfigClasses() {return new Class[]{SpringMvcConfig.class};}protected String[] getServletMappings(){return new String[]{"/"};}protected Class<?>[] getRootConfigClasses(){return new Class[0];} }
3.请求与响应
1.请求映射路
@Controller @RequestMapping("/user") public class UserController {@RequestMapping("/save")@ResponseBodypublic String save(){System.out.println("user save ...");return "{'module':'user save'}";}@RequestMapping("/delete")@ResponseBodypublic String delete(){System.out.println("user delete ...");return "{'module':'user delete'}";} }
2.参数传递
Get请求传参
普通参数:url地址传参
public class UserController {@RequestMapping("/commonParam")@ResponseBodypublic String commonParam(String name){System.out.println("普通参数传递 name==>" + name);return "{'module':'common param'}";} }
Post请求传参
传参汉字会出现乱码问题,添加字符过滤器
//乱码处理 @Override protected Filter[] getServletFilters() {CharacterEncodingFilter filter = new CharacterEncodingFilter();filter.setEncoding("UTF-8");return new Filter[]{filter}; }
普通参数:请求参数名与形参名不同
public class UserController {@RequestMapping("/commonParam")@ResponseBodypublic String commonParam(@RequestParam("name") String userName){System.out.println("普通参数传递 name ==>" + userName);return "{'module':'common param'}";} }
集合参数
public class UserController {@RequestMapping("/listParam")@ResponseBodypublic String commonParam(@RequestParam List<String> likes){System.out.println("集合参数传递 likes ==>" + likes);return "{'module':'list param'}";} }
传递json数据
-
导入JSON坐标
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.0</version> </dependency>
-
@EnableWebMvc:开启自动转换json对象的支持
-
集合参数:json格式 在方法体里不在RequestParam中
public String listParamForJson(@RequestBody List<String> likes) {System.out.println("list common(json)参数传递 list ==>" + likes);return "{'module':'list common for json param'}"; }
POJO参数:JSON格式
{"name":"itcast","age";"15" }
@RequestBody和@RequestParam区别
-
区别:
-
@RequestParam用于接收url地址传参,表单传参
-
@RequestBody用于接收json数据
-
-
应用
-
后期开发中,发送json格式数据为主,@RequestBody应用较广
-
如果发送非json格式数据,选用@RequestParam接收请求参数
-
日期类型参数传递
接收形参时,根据不同的日期格式设置不同的接收方式
@RequestMapping("/dataParam") @ResponseBody public String dataParam(Date date,@DateTimeFormat(pattern="yyyy-MM-dd")Date date1,@DateTimeFormat(pattern="yyyy/MM/dd HH:mm:ss")Date date2){System.out.println(...);System.out.println(...);System.out.println(...);return "{'module':'data param'}";}
3.响应
-
响应页面
@RequestMapping("/toPage") public String toPage(){return "page.jsp"; }
-
响应文本数据
@RequestMapping("/toPage") @ResponseBody public String toPage(){return "page.jsp"; }
-
响应json数据
@RequestMapping("/toJsonPOJO") @ResponseBody public String toJsonPOJO(){User user = new User();user.setName("赵云");user.setAge(41);return user; }
-
响应json数据,集合
@RequestMapping("/toJsonPOJO") @ResponseBody public String toJsonPOJO(){User user = new User();user.setName("赵云");user.setAge(41);return user;User user2 = new User();user2.setName("神赵云");user2.setAge(40);List<User> userList = new ArrayList<User>();userList.add(user1);userList.add(user2);return userList; }
4.REST风格
REST(Representational State Transfer),表现形式状态转换
可以隐藏资源的访问行为,无法通过地址得知对资源是何种操作
-
设置http请求动作(RequestMethod)
public class UserController {@RequestMapping(value = "/users",method = RequestMethod.POST)@ResponseBodypublic String save(){System.out.println("user save ...");return "{'module':'user save'}";}@RequestMapping(value = "/users",method = RequestMethod.PUT)@ResponseBodypublic String update(){System.out.println("user update ...");return "{'module':'user update'}";}@RequestMapping(value = "/users",method = RequestMethod.GET)@ResponseBodypublic String getAll(){System.out.println("user getAll ...");return "{'module':'user getAll'}";} }
-
设定请求参数("/users/{id}" 和 @PathVariable)
@RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)@ResponseBodypublic String delete(@PathVariable Integer id){System.out.println("user delete ..." + id);return "{'module':'user delete'}";}@RequestMapping(value = "/users/{id}",method = RequestMethod.GET)@ResponseBodypublic String getById(@PathVariable Integer id){System.out.println("user getById ...");return "{'module':'user getById'}";
@PathVariable
用于接收路径参数,使用{参数名称}描述路劲参数
RESTful快速开发
@RestController @RequestMapping("/books") public class UserController {@PostMappingpublic String save(){System.out.println("user save ...");return "{'module':'user save'}";}@PutMappingpublic String update(){System.out.println("user update ...");return "{'module':'user update'}";}@DeleteMappingpublic String delete(@PathVariable Integer id){System.out.println("user delete ..." + id);return "{'module':'user delete'}";}@GetMappingpublic String getById(@PathVariable Integer id){System.out.println("user getById ...");return "{'module':'user getById'}";}@GetMappingpublic String getAll(){System.out.println("user getAll ...");return "{'module':'user getAll'}";} }
@RestController:@Controller和@ResponseBody两个注解组合功能