重新学习SpringMVC——高级
30. SpringMVC_RESTRUL_CRUD_显示所有员工信息
31. SpringMVC_RESTRUL_CRUD_添加操作&表单标签
32. SpringMVC_RESTRUL_CRUD_删除操作&处理静态资源
33. SpringMVC_RESTRUL_CRUD_修改操作
34. SpringMVC_数据绑定流程分析
35. SpringMVC_自定义类型转换器
36. SpringMVC_annotation-driven配置
37. SpringMVC_InitBinder注解
38. SpringMVC_数据的格式化
39. SpringMVC_JSR303数据校验
40. SpringMVC_错误消息的显示及国际化
41. SpringMVC_返回JSON
42. SpringMVC_HttpMessageConverter原理
43. SpringMVC_使用HttpMessageConverter
44. SpringMVC_国际化_概述
45. SpringMVC_国际化_前两个问题
46. SpringMVC_国际化_通过超链接切换Locale
47. SpringMVC_文件上传
48. SpringMVC_第一个自定义的拦截器
49. SpringMVC_拦截器的配置
50. SpringMVC_多个拦截方法的执行顺序
51. SpringMVC_异常处理_ExceptionHandler注解
52. SpringMVC_异常处理_ResponseStatusExceptionResolver
53. SpringMVC_异常处理_DefaultHandlerExceptionResolver
54. SpringMVC_异常处理_SimpleMappingExceptionResolver
55. SpringMVC_运行流程图解
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.atguigu.springmvc"></context:component-scan> <!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean> <!--
default-servlet-handler 将在 SpringMVC 上下文中定义一个 DefaultServletHttpRequestHandler,
它会对进入 DispatcherServlet 的请求进行筛查, 如果发现是没有经过映射的请求, 就将该请求交由 WEB 应用服务器默认的
Servlet 处理. 如果不是静态资源的请求,才由 DispatcherServlet 继续处理 一般 WEB 应用服务器默认的 Servlet 的名称都是 default.
若所使用的 WEB 服务器的默认 Servlet 名称不是 default,则需要通过 default-servlet-name 属性显式指定 -->
<mvc:default-servlet-handler/> <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven> <!-- 配置 ConversionService -->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="employeeConverter"/>
</set>
</property>
</bean> <!-- 配置国际化资源文件 -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="i18n"></property>
</bean> <!-- 配置 SessionLocalResolver -->
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean> <mvc:interceptors>
<!-- 配置自定义的拦截器 -->
<bean class="com.atguigu.springmvc.interceptors.FirstInterceptor"></bean> <!-- 配置拦截器(不)作用的路径 -->
<mvc:interceptor>
<mvc:mapping path="/emps"/>
<bean class="com.atguigu.springmvc.interceptors.SecondInterceptor"></bean>
</mvc:interceptor> <!-- 配置 LocaleChanceInterceptor -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
</mvc:interceptors> <!--
<mvc:view-controller path="/i18n" view-name="i18n"/>
-->
<mvc:view-controller path="/i18n2" view-name="i18n2"/> <!-- 配置 MultipartResolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="1024000"></property>
</bean> <!-- 配置使用 SimpleMappingExceptionResolver 来映射异常 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionAttribute" value="ex"></property>
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
</props>
</property>
</bean> </beans>
EmployeeHandler.Java
@Controller
public class EmployeeHandler { @Autowired
private EmployeeDao employeeDao; @Autowired
private DepartmentDao departmentDao; @ModelAttribute
public void getEmployee(@RequestParam(value="id",required=false) Integer id,
Map<String, Object> map){
if(id != null){
map.put("employee", employeeDao.get(id));
}
} @RequestMapping(value="/emp", method=RequestMethod.PUT)
public String update(Employee employee){
employeeDao.save(employee); return "redirect:/emps";
} @RequestMapping(value="/emp/{id}", method=RequestMethod.GET)
public String input(@PathVariable("id") Integer id, Map<String, Object> map){
map.put("employee", employeeDao.get(id));
map.put("departments", departmentDao.getDepartments());
return "input";
} @RequestMapping(value="/emp/{id}", method=RequestMethod.DELETE)
public String delete(@PathVariable("id") Integer id){
employeeDao.delete(id);
return "redirect:/emps";
} @RequestMapping(value="/emp", method=RequestMethod.POST)
public String save(@Valid Employee employee, Errors result,
Map<String, Object> map){
System.out.println("save: " + employee); if(result.getErrorCount() > 0){
System.out.println("出错了!"); for(FieldError error:result.getFieldErrors()){
System.out.println(error.getField() + ":" + error.getDefaultMessage());
} //若验证出错, 则转向定制的页面
map.put("departments", departmentDao.getDepartments());
return "input";
} employeeDao.save(employee);
return "redirect:/emps";
} @RequestMapping(value="/emp", method=RequestMethod.GET)
public String input(Map<String, Object> map){
map.put("departments", departmentDao.getDepartments());
map.put("employee", new Employee());
return "input";
} @RequestMapping("/emps")
public String list(Map<String, Object> map){
map.put("employees", employeeDao.getAll());
return "list";
} // @InitBinder
// public void initBinder(WebDataBinder binder){
// binder.setDisallowedFields("lastName");
// } }
SpringMVCTest.java
@Controller
public class SpringMVCTest { @Autowired
private EmployeeDao employeeDao; @Autowired
private ResourceBundleMessageSource messageSource; @RequestMapping("/testSimpleMappingExceptionResolver")
public String testSimpleMappingExceptionResolver(@RequestParam("i") int i){
String [] vals = new String[10];
System.out.println(vals[i]);
return "success";
} @RequestMapping(value="/testDefaultHandlerExceptionResolver",method=RequestMethod.POST)
public String testDefaultHandlerExceptionResolver(){
System.out.println("testDefaultHandlerExceptionResolver...");
return "success";
} @ResponseStatus(reason="测试",value=HttpStatus.NOT_FOUND)
@RequestMapping("/testResponseStatusExceptionResolver")
public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
if(i == 13){
throw new UserNameNotMatchPasswordException();
}
System.out.println("testResponseStatusExceptionResolver..."); return "success";
} // @ExceptionHandler({RuntimeException.class})
// public ModelAndView handleArithmeticException2(Exception ex){
// System.out.println("[出异常了]: " + ex);
// ModelAndView mv = new ModelAndView("error");
// mv.addObject("exception", ex);
// return mv;
// } /**
* 1. 在 @ExceptionHandler 方法的入参中可以加入 Exception 类型的参数, 该参数即对应发生的异常对象
* 2. @ExceptionHandler 方法的入参中不能传入 Map. 若希望把异常信息传导页面上, 需要使用 ModelAndView 作为返回值
* 3. @ExceptionHandler 方法标记的异常有优先级的问题.
* 4. @ControllerAdvice: 如果在当前 Handler 中找不到 @ExceptionHandler 方法来出来当前方法出现的异常,
* 则将去 @ControllerAdvice 标记的类中查找 @ExceptionHandler 标记的方法来处理异常.
*/
// @ExceptionHandler({ArithmeticException.class})
// public ModelAndView handleArithmeticException(Exception ex){
// System.out.println("出异常了: " + ex);
// ModelAndView mv = new ModelAndView("error");
// mv.addObject("exception", ex);
// return mv;
// } @RequestMapping("/testExceptionHandlerExceptionResolver")
public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i){
System.out.println("result: " + (10 / i));
return "success";
} @RequestMapping("/testFileUpload")
public String testFileUpload(@RequestParam("desc") String desc,
@RequestParam("file") MultipartFile file) throws IOException{
System.out.println("desc: " + desc);
System.out.println("OriginalFilename: " + file.getOriginalFilename());
System.out.println("InputStream: " + file.getInputStream());
return "success";
} @RequestMapping("/i18n")
public String testI18n(Locale locale){
String val = messageSource.getMessage("i18n.user", null, locale);
System.out.println(val);
return "i18n";
} @RequestMapping("/testResponseEntity")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{
byte [] body = null;
ServletContext servletContext = session.getServletContext();
InputStream in = servletContext.getResourceAsStream("/files/abc.txt");
body = new byte[in.available()];
in.read(body); HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=abc.txt"); HttpStatus statusCode = HttpStatus.OK; ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
return response;
} @ResponseBody
@RequestMapping("/testHttpMessageConverter")
public String testHttpMessageConverter(@RequestBody String body){
System.out.println(body);
return "helloworld! " + new Date();
} @ResponseBody
@RequestMapping("/testJson")
public Collection<Employee> testJson(){
return employeeDao.getAll();
} @RequestMapping("/testConversionServiceConverer")
public String testConverter(@RequestParam("employee") Employee employee){
System.out.println("save: " + employee);
employeeDao.save(employee);
return "redirect:/emps";
} }
重新学习SpringMVC——高级的更多相关文章
- (转)SpringMVC学习(六)——SpringMVC高级参数绑定与@RequestMapping注解
http://blog.csdn.net/yerenyuan_pku/article/details/72511749 高级参数绑定 现在进入SpringMVC高级参数绑定的学习,本文所有案例代码的编 ...
- 学习SpringMVC——如何获取请求参数
@RequestParam,你一定见过:@PathVariable,你肯定也知道:@QueryParam,你怎么会不晓得?!还有你熟悉的他(@CookieValue)!她(@ModelAndView) ...
- Shell高级编程视频教程-跟着老男孩一步步学习Shell高级编程实战视频教程
Shell高级编程视频教程-跟着老男孩一步步学习Shell高级编程实战视频教程 教程简介: 本教程共71节,主要介绍了shell的相关知识教程,如shell编程需要的基础知识储备.shell脚本概念介 ...
- Python3学习(3)-高级篇
Python3学习(1)-基础篇 Python3学习(2)-中级篇 Python3学习(3)-高级篇 文件读写 源文件test.txt line1 line2 line3 读取文件内容 f = ope ...
- Python学习之高级数组(一)
1.Python基础学习之高级数组(一) 1.1视图:就是与较大数组共享相同数据的较小数组.Numpy包提供数据视图的概念是为了精确地控制内存的使用方式. 数组视图.切片视图.转置和重塑视图等 数组 ...
- (转)跟着老男孩一步步学习Shell高级编程实战
原文:http://oldboy.blog.51cto.com/2561410/1264627/ 跟着老男孩一步步学习Shell高级编程实战 原创作品,允许转载,转载时请务必以超链接形式标明文章 原 ...
- 数据库MySQL学习笔记高级篇
数据库MySQL学习笔记高级篇 写在前面 学习链接:数据库 MySQL 视频教程全集 1. mysql的架构介绍 mysql简介 概述 高级Mysql 完整的mysql优化需要很深的功底,大公司甚至有 ...
- 2.学习SpringMVC注解入门篇
一.SpringMVC执行流程 . 二.创建项目学习SpringMVC注解 按照我之前的SpringMVC创建项目,首先创建一个项目springmvc01,配置好pom.xml,web.xml,spr ...
- 萌新学习SpringMVC
前言 只有光头才能变强. 文本已收录至我的GitHub精选文章,欢迎Star:https://github.com/ZhongFuCheng3y/3y 这篇SpringMVC被催了很久了,这阵子由于做 ...
随机推荐
- 《淘宝数据库OceanBase SQL编译器部分 源码阅读--解析SQL语法树》
淘宝数据库OceanBase SQL编译器部分 源码阅读--解析SQL语法树 曾经的学渣 2014-06-05 18:38:00 浏览1455 云数据库Oceanbase OceanBase是 ...
- python中实现单例模式
单例模式的目的是一个类有且只有一个实例对象存在,比如在复用类的过程中,可能重复创建多个实例,导致严重浪费内存,此时就适合使用单例模式. 前段时间需要用到单例模式,就称着机会在网上找了找,有包含了__n ...
- Haproxy+Keepalived构建高可用负载均衡集群
实验环境: 主机名 IP地址 VIP 192.168.200.254 Haproxy-1 192.168.200.101 Haproxy-2 192.168.200.102 Nginx1 192.16 ...
- 入门理解mysql-binlog
mysql-binlog简介: mysql的二进制日志记录了所有DDL和DML(除select) 开启binlog日志后会有1%左右的的性能损耗 二进制日志包括两类 索引文件 XXXX.index 日 ...
- torch_13_自定义数据集实战
1.将图片的路径和标签写入csv文件并实现读取 # 创建一个文件,包含image,存放方式:label pokemeon\\mew\\0001.jpg,0 def load_csv(self,file ...
- Window权限维持(一):注册表运行键
在红队行动中在网络中获得最初的立足点是一项耗时的任务.因此,持久性是红队成功运作的关键,这将使团队能够专注于目标,而不会失去与指挥和控制服务器的通信.在Windows登录期间创建将执行任意负载的注册表 ...
- 用Python帮你上马,哪里无码打哪里
目录 0 引言 1 环境 2 需求分析 3 代码实现 4 代码全景展示 5 后记 0 引言 所谓的像素图,就是对图像做一个颗粒化的效果,使其产生一种妙不可言的朦胧感.费话不多说,先来看一张效果图. ▲ ...
- Docker 指定数据储存目录
Docker 指定储存目录(原参数 --graph 已经失效 .) 方法一 一.在 Docker 配置文件中配置 /etc/docker/daemon.json 下面的命令是在 daemon.json ...
- java中级,知识点归纳(一)
一.接口和抽象类的区别 抽象类中可以含有构造方法,而接口内不能有. 抽象类中可以有普通成员变量,而接口中不能有. 抽象类中可以包含非抽象的普通方法,而接口中所有方法必须是抽象的,不能有非抽象的普通方法 ...
- Android studio R文件丢失或错误解决方法
android studio中有时引用资源会出现R文件丢失或报错,大多数情况下是由于引入资源时R文件没有及时更新造成的 (在代码没有错误或资源引用没有错误的前提下) 注意:资源文件的文件名必须小写,即 ...