springmvc小结(下)
1.@ModelAttribute
2.多个对象的传递
//自定义属性注解,用于请求参数转移到对应的对象参数中去
//把一dog.开头的参数封装到dog中
@InitBinder("dog")
public void initBing(WebDataBinder binder){
binder.setFieldDefaultPrefix("dog.");
} @InitBinder("cat")
public void initBing1(WebDataBinder binder){
binder.setFieldDefaultPrefix("cat.");
} @RequestMapping("/testmany")
public String test(Cat cat,Dog dog){ System.out.println(cat);
System.out.println(dog);
return null;
}
<form method="post" action="model/testmany">
catName:<input type="text" name="cat.name"><br/>
catAge:<input type="text" name="cat.age"><br/>
DogName:<input type="text" name="dog.name"><br/>
DogAge:<input type="text" name="dog.age"><br/>
<input type="submit" value="submit">
</form>
处理不同的数据可以传递到不同的pojo实现类中。
3.处理json
①.单个对象
//@ResponseBody
//处理响应,把对象转为json字符串
//贴在方法上,只针对当前的方法做json处理
//在类上会对当前类的所有方法做json处理 //把单个对象转为json
@RequestMapping("/user1")
@ResponseBody
public User user1(){
User u = new User();
u.setName("MrChegns");
u.setAge(12);
return u;
}

②.多个对象
//多个对象
@RequestMapping("/user2")
@ResponseBody
public List<User> user2(){
List<User> users = new ArrayList<>();
User u1 = new User("MrChengs",12);
User u2 = new User("MrChengs",13);
users.add(u1);
users.add(u2);
return users;
}

注意://返回一个String,把返回的字符串不会当作物理逻辑返回 ,当作json
@RequestMapping(value="/test1",produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String test1(){
return "success“;
}

4.日期处理
//把请求参数封装成Date字符串
//前台向后台传数据
@RequestMapping("/test1")
public ModelAndView test(@DateTimeFormat(pattern="yyyy-MM-dd")Date d){
System.out.println(d);
return null;
}

time时的Date类型:
@InitBinder
public void initBind(WebDataBinder binder){
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern("yyyy-MM-dd");
binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(sdf, true));
}
@RequestMapping("/test2")
public ModelAndView dates(User u){
System.out.println(u);
return null;
}

@ControllerAdvice
public class DateformateConfig {
@InitBinder
public void initBind(WebDataBinder binder){
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern("yyyy-MM-dd");
binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(sdf, true));
}
}
@RequestMapping("/test2")
public ModelAndView dates(User u){
System.out.println(u);
return null;
}
得到结果不变
jsp页面处理:


后台向前台
public class User {
private String name;
private int age;
//东八区
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date time;
....
}
@RequestMapping("/test4")
@ResponseBody
public User user12(){
User u = new User();
u.setAge(12);
u.setName("Mrcheng");
u.setTime(new Date());
return u;
}

5.拦截器

配置
<!-- 拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 对那些资源及进行拦截 -->
<mvc:mapping path="/**"/>
<!-- 派出不需要被拦截的 -->
<mvc:exclude-mapping path="login"/>
<bean class="com.MrChengs.interceptor.LoginCheckInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
实现类登陆拦截
public class LoginCheckInterceptor implements HandlerInterceptor{
//登陆判断
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if(request.getSession() == null){
response.sendRedirect(request.getContextPath()+ "/login.jsp");
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
6.异常处理:
<!-- 配置异常处理器 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
//设置错误的默认视图
<property name="defaultErrorView" value="error/erroes"></property>
</bean>
错误的提示页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
error:<%=exception.getMessage() %>
</body>
</html>

错误页面获取异常信息的变量名称
<property name="exceptionAttribute" value="qqq"></property>

根据不同类型的异常配置不同的异常
<!-- 根据不同的异常类型,跳转到不同的页面 -->
<property name="exceptionMappings"> </property>
7.数据校验


springmvc.xml中
<!-- 数据校验 -->
<bean class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"></bean>
pojo中
public class User {
private int id;
@NotNull(message="username 不可以为空")
private String username;
@Size(max=5,min=1,message="密码大于1小于5")
private String password;
...
}
BindingResult 必须在 @Valid之后
@RequestMapping("/insertuser")
public String Users(@Valid User user,BindingResult bindingResult,Model model) throws Exception{
List<ObjectError> es = bindingResult.getAllErrors();
if(es.size() > 0){
model.addAttribute("es", es);
return "/insert";
}
System.out.println("hellouser");
System.out.println(user);
UserMapper um = (UserMapper) getContext().getBean("userMapper");
um.addUser(user);
return "redirect:/select/selectall";
}
jsp页面上
<c:forEach items="${es}" var="e">
<p>${e.defaultMessage}</p>
</c:forEach>

更多的可以从参考网上的更多教程.......
8.文件上传

<!-- 文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048000"></property>
</bean>
jsp页面
<form action="upload" method="post" enctype="multipart/form-data">
name:<input type="text" name="username">
file:<input type="file" name="pic" >
<input type="submit" value="submit">
</form>
controller
@Controller
public class FileUpLoad { @Autowired
private ServletContext servletContext; @RequestMapping("/upload")
public ModelAndView upload(User user,MultipartFile pic) throws IOException{
System.out.println(user);
String fileName = pic.getOriginalFilename();
System.out.println(fileName);
String dir = servletContext.getRealPath("/photo");
Files.copy(pic.getInputStream(),Paths.get(dir, fileName));
return null;
}
}
两个同名pic位置
基本上总结到此结束了.....
springmvc小结(下)的更多相关文章
- springMVC框架下JQuery传递并解析Json数据
springMVC框架下JQuery传递并解析Json数据
- springmvc框架下ajax请求传参数中文乱码解决
springmvc框架下jsp界面通过ajax请求后台数据,传递中文参数到后台显示乱码 解决方法:js代码 运用encodeURI处理两次 /* *掩码处理 */ function maskWord( ...
- (转)springMVC框架下JQuery传递并解析Json数据
springMVC框架下JQuery传递并解析Json数据 json作为一种轻量级的数据交换格式,在前后台数据交换中占据着非常重要的地位.Json的语法非常简单,采用的是键值对表示形式.JSON 可以 ...
- SpringMvc架构下css、js、jpg加载失败问题
SpringMvc架构下css.js.jpg加载失败问题 springMvc搭建成功后,页面出现一些错误,jsp.js等静态资源加载失败.导致页面没有显示任何样式以及 此处原因很简单,是因为相对路径在 ...
- 使用Javamelody验证struts-spring框架与springMVC框架下action的訪问效率
在前文中我提到了关于为何要使用springMVC的问题,当中一点是使用springMVC比起原先的struts+spring框架在效率上是有优势的.为了验证这个问题,我做了两个Demo来验证究竟是不是 ...
- 微信被动回复用户消息-文本消息-springmvc环境下自动生成xml
微信被动回复用户消息-文本消息-springmvc环境下自动生成xml springmvc - 大牛! private Object subscribeMessage(Scan scan) { Sca ...
- springmvc模式下的上传和下载
接触了springmvc模式后,对上一次的上传与下载进行优化, 上次请看这里. 此处上传的功能依旧是采用表格上传.文件格式依旧是 <form action="${pageContext ...
- SpringMVC框架下的异常处理
在eclipse的javaEE环境下:导包.... 1. 在 @ExceptionHandler 方法的入参中可以加入 Exception 类型的参数, 该参数即对应发生的异常对象 2. @Excep ...
- SpringMVC框架下的拦截器
在eclipse的javaEE环境下:导包.... web.xml文件中的配置: <?xml version="1.0" encoding="UTF-8" ...
随机推荐
- HttpContext在多线程异步调用中的使用方案
1.在线程调用中,有时候会碰到操作文件之类的功能.对于开发人员来说,他们并不知道网站会被部署在服务器的那个角落里面,因此根本无法确定真实的物理路径(当然可以使用配置文件来配置物理路径),他们唯一知道的 ...
- ASP.NET 4.5.256 尚未在Web服务器上注册。
最近在网上下载的一个原型用VS2012打开报错如下: 解决方法: 打开网址:http://blogs.msdn.com/b/webdev/archive/2014/11/11/dialog-box-m ...
- Heka 的配置文件加载逻辑
Heka 使用的是 TOML 格式的配置文件, 有关 golang 加载 TOML 配置文件的技术请参看: http://www.cnblogs.com/ghj1976/p/4082323.html ...
- 1、springboot之HelloWorld
最基本的,官网copy 创建maven项目 maven中添加 <parent> <groupId>org.springframework.boot</groupId> ...
- What is the relation of theme and it's derived theme.
You know, a theme can derive from other theme in two ways: xx.xxx implicit way and parent="xxx& ...
- Effective C++ .44 typename和class的不同
在C++模板中的类型参数一般可以使用typename和class,两者没有什么不同.但是typename比class多项功能: “任何时候当你想要在template中指涉一个嵌套从属类型名称,就必须在 ...
- 洛谷P1155 双栈排序(贪心)
题意 题目链接 Sol 首先不难想到一种贪心策略:能弹则弹,优先放A 然后xjb写了写发现只有\(40\),原因是存在需要决策的情况 比如 \(A = {10}\) \(B = {8}\) 现在进来一 ...
- js数组方法 改变原数组和不改变原数组的方法整理
改变原数组: pop(): 删除 arrayObject 的最后一个元素,把数组长度减 1,并且返回它删除的元素的值.如果数组已经为空,则 pop() 不 改变数组,并返回 undefined 值 ...
- IOS如何下载旧版本应用APP
前言 文章相对来说比较复杂,特别是查找版本ID对应的步骤,这里推荐使用另一种方案,操作起来更简单. 本文介绍如何使用Workflow及Fiddler下载IOS旧版本APP应用. 实现原理 通过Work ...
- Linux文件系统简介----转载
原文地址:Linux文件系统 文件系统是linux的一个十分基础的知识,同时也是学习linux的必备知识. 本文将站在一个较高的视图来了解linux的文件系统,主要包括了linux磁盘分区和目录.挂载 ...