重新学习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被催了很久了,这阵子由于做 ...
随机推荐
- xargs 用法理解
原来一直不理解,linux shell下 xargs和 管道的区别: 1.管道在linux shell用得比较广泛,管道常常用来组合两个及以上的命令,共同完成一个功能: 比如:我们要统计某一个文件有多 ...
- ESP8266 AT指令开发(基于STC89C52单片机): 测试下诱人的程序(51单片机,8266,MQTT远程通信控制)
前言 实现的功能,APP通过SmartConfig给Wi-Fi模块配网并绑定设备,然后通过MQTT远程控制开发板的继电器, 简而言之: 51单片机+ESP8266用AT指令实现实现MQTT,(连接的本 ...
- java.util.concurrent各组件分析 一 sun.misc.Unsafe
java.util.concurrent各组件分析 一 sun.misc.Unsafe 说到concurrent包也叫并发包,该包下主要是线程操作,方便的进行并发编程,提到并发那么锁自然是不可缺少的, ...
- 一、Spring注解之@ComponentScan
Spring注解之@ComponentScan [1]@ComponentScan注解是什么 @ComponentScan主要就是定义扫描的路径从中找出标识了需要装配的类自动装配到spring的bea ...
- C++:Name Lookup & Best Match
名字查找 每当一个变量或者一个对象出现,编译器都会进行名字查找(name lookup),以确认这个变量或对象的具体属性.一般情况下,程序会从变量出现的地方开始向上查找,由内向外查找各级作用域直到全局 ...
- 第二十一节:Asp.Net Core MVC和WebApi路由规则的总结和对比
一. Core Mvc 1.传统路由 Core MVC中,默认会在 Startup类→Configure方法→UseMvc方法中,会有默认路由:routes.MapRoute("defaul ...
- LinqToSql
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConsoleA ...
- [.NET] 控制只启动单个指定外部程序
独立观察员 2019 年 6 月 12 日 有的时候我们程序需要启动外部程序来配合实现某些功能,比如启动一个 Cef 相关程序来承载网页.那么如果那个外部程序并没有实现单例启动,我们程序去启动它的时候 ...
- CentOS6 + MapServer7.4编译
先升级gcc 1.python3.6 ./configure --enable-shared --enable-profiling make –j 20 make install 2.proj-4.9 ...
- Winform(C#)中Chart控件鼠标点击显示波形上相应点对应坐标轴的x,y值
方法一:鼠标点击波形 鼠标点击波形,显示点击位置的x,y值 private void chart1_MouseClick(object sender, MouseEventArgs e) //cha ...