SpringMVC(一种基于java实现的轻量级web框架)
请求与响应
REST风格
SSM整合
拦截器
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(SpringMvcConfig.class);
return ctx;
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
}
@Configuration
@ComponentScan("com.example.controller")
public class SpringMvcConfig {
}
@Controller
public class UserController {
@RequestMapping("/save")
@ResponseBody
public String save(){
System.out.println("user save ...");
return "{'module','springmvc'}";
}
}
创建一个SpringMvc(要注意tomcat和spring版本问题)
1.创建ServletContainersInitConfig配置类,他在tomcat启动时加载
2.创建SpringMvcConfig配置类来配置springmvc
3.创建UserController来配置Controller
启动服务器初始化过程
配置类spring和springmvc在一起
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(SpringMvcConfig.class);
return ctx;
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Override
protected WebApplicationContext createRootApplicationContext() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(SpringConfig.class);
return ctx;
}
}
或者继承AbstractAnnotationConfigDispatcherServletInitializer接口可以更吉简单
public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[0];
}
}
请求和响应
请求映射路径
请求参数
日期类型参数传递
响应json数据
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/save")
@ResponseBody
public String save(){
System.out.println("user save ...");
return "{'module','user save'}";
}
@RequestMapping("/delete")
@ResponseBody
public String delete(){
System.out.println("user delete ...");
return "{'module','user delete'}";
}
}
请求映射路径
在控制器类最上方加入@RequestMapping(“/user”)注释表示类访问路径前缀
请求方式
1.get请求
2.post请求
在spring里不需要区分get和post,已经合二为一了
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("utf-8");
return new Filter[]{filter};
}
中文乱码处理,在ServletContainersInitConfig类中设置过滤器
参数种类
1.普通参数
2.POJO类型参数
3.嵌套POJO类型参数
4.数组类型参数
5.集合类型参数
@RequestMapping("/commenParam")
@ResponseBody
public String save(@RequestParam("name") String username, int age){
System.out.println("普通参数传递 username ==> "+username);
System.out.println("普通参数传递 age ==> "+age);
return "{'module','common param'}";
}
@RequestParam(“name”)注解把对应html访问路径的参数与函数参数相对应
POJO参数(包含引用类型)
@RequestMapping("/pojoParam")
@ResponseBody
public String pojoParam(User user){
System.out.println("pojoParam参数传递 user ==> "+user);
return "{'module','pojo param'}";
}
数组参数
@RequestMapping("/arrayParam")
@ResponseBody
public String arrayParam(String[] likes){
System.out.println("arrayParam参数传递 likes ==> "+ Arrays.toString(likes));
return "{'module','array param'}";
}
数组只需要传入相同的名字就可以,不同名字无法接收
List集合
@RequestMapping("/listParam")
@ResponseBody
public String listParam(@RequestParam List<String> likes){
System.out.println("listParam参数传递 likes ==> "+ likes);
return "{'module','list param'}";
}
参数前面要加入@RequestParam注解
不加的话,因为默认是按照集合的属性,使用set方法注入进去,所以会出错,spring把集合当初实体类处理了,加入之后就会按照参数把数据传入
json传递参数
集合参数
@RequestMapping("/listParamForJson")
@ResponseBody
public String listParamForJson(@RequestBody List<String> likes){
System.out.println("list common参数传递 list ==> "+ likes);
return "{'module','list common for json param'}";
}
1.导入jackson坐标,因为spring没有处理json格式的方法
2.在springmvc配置类加入@EnableWebMvc注释
3.加入@RequestBody来把请求体的参数传入,否则list集合无法识别
pojo参数
@RequestMapping("/pojoParamForJson")
@ResponseBody
public String pojoParamForJson(@RequestBody User user){
System.out.println("pojo common参数传递 user ==> "+ user);
return "{'module','pojo common for json param'}";
}
POJO集合参数
@RequestMapping("/listPojoParamForJson")
@ResponseBody
public String listPojoParamForJson(@RequestBody List<User> list){
System.out.println("list pojo common参数传递 user ==> "+ list);
return "{'module','list pojo for json param'}";
}
日期类型参数传递
日期类型数据基于系统格式不同也不相同
2088-08-18
2088/08/18
08/18/2088
@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("参数传递 date ==> "+ date);
System.out.println("参数传递 date1 ==> "+ date1);
System.out.println("参数传递 date2 ==> "+ date2);
return "{'module','date param'}";
}
date类型的参数除了斜线以外都需要添加@DateTimeFormat注解来解析日期格式,否则出错
@EnableWebMvc功能之一:根据类型匹配对应的类型转换器
响应
- 响应页面
- 响应数据
- 文本数据
- json数据
响应页面/跳转页面
@RequestMapping("/toJumpPage")
public String toJumpPage(){
System.out.println("返回纯文本数据");
return "index.jsp";
}
响应文本(加入@ResponseBody注释即变为字符串)
@RequestMapping("/toText")
@ResponseBody
public String toText(){
System.out.println("返回纯文本数据");
return "response text";
}
响应POJO
@RequestMapping("/toJsonPOJO")
@ResponseBody
public User toJsonPOJO(){
System.out.println("返回json对象数据");
User user = new User();
user.setName("itcast");
user.setAge(15);
return user;
}
响应POJOlist集合
@RequestMapping("/toJsonList")
@ResponseBody
public List<User> toJsonList(){
System.out.println("返回json对象数据");
User user = new User();
user.setName("itcast");
user.setAge(15);
List<User> users = new ArrayList<>();
users.add(user);
return users;
}
@ResponseBody
作用:设置当前控制器返回值为响应体
Rest风格(Representational State Transfer)
表现形式状态转换
@RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
@ResponseBody
public String delete(@PathVariable Integer id){
System.out.println("user delete ..."+id);
return "{'module':'user delete'}";
}
@PathVariable注解表示将路径中的路径变量与参数变量对应
@RequestMapping(value = "/users",method = RequestMethod.POST)
@ResponseBody
public String save(){
System.out.println("user save ...");
return "{'module':'user save'}";
}
@RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
@ResponseBody
public String delete(@PathVariable Integer id){
System.out.println("user delete ..."+id);
return "{'module':'user delete'}";
}
@RequestMapping(value = "/users",method = RequestMethod.PUT)
@ResponseBody
public String update(){
System.out.println("user update ...");
return "{'module':'user update'}";
}
@RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
@ResponseBody
public String getById(@PathVariable Integer id){
System.out.println("user getById ..."+id);
return "{'module':'user getById'}";
}
@RequestMapping(value = "/users",method = RequestMethod.GET)
@ResponseBody
public String getAll(){
System.out.println("user getAll ...");
return "{'module':'user getAll'}";
}
@RestController
@RequestMapping("/users")
public class UserController {
@PostMapping
public String save(){
System.out.println("user save ...");
return "{'module':'user save'}";
}
@DeleteMapping("/{id}")
public String delete(@PathVariable Integer id){
System.out.println("user delete ..."+id);
return "{'module':'user delete'}";
}
@PutMapping
public String update(){
System.out.println("user update ...");
return "{'module':'user update'}";
}
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println("user getById ..."+id);
return "{'module':'user getById'}";
}
@GetMapping
public String getAll(){
System.out.println("user getAll ...");
return "{'module':'user getAll'}";
}
}
@RestController注解代表@Controller+@ResponseBody
如果无法访问html和js等文件,加入SpringMvcSupport类来让springmvc对spring放行
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
}
}
SSM整合
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id) {
Book book = bookService.getById(id);
Integer code = book!=null ? Code.SELECT_OK:Code.SELECT_ERR;
String msg = book!=null ? "":"数据查询失败请重试";
return new Result(code,book,msg);
}
异常处理器
出现异常的常见位置和常见诱因如下
- 框架内部抛出的异常:因使用不合规导致
- 数据层抛出的异常:因外部服务器故障导致(例如:服务器访问超时)
- 业务层抛出的异常:因业务逻辑书写错误导致(例如:遍历业务书写操作,导致索引异常)
- 表现层抛出的异常:因数据收集,校验等规则导致(例如:不匹配的数据类型间导致异常)
- 工具类抛出的异常:因工具类书写不严谨不够健壮导致(例如:必要释放的连接长期未释放等)
所有异常均抛出到表现层处理
使用aop处理,但spring有异常处理器
异常处理器
集中的统一的处理项目中的异常