一、高级参数绑定
在jsp页面返回给前端控制器的数据中,能否携带非简单参数呢?当然是可以的.现在我们来举例.
1返回数组
1.1修改jsp页面
<td><input name="ids" value="${item.id}" type="checkbox"></td>
1.2在controller类中通过三种方式获取传递的数组
a. 在方法中添加string[] ids
@RequestMapping("/queryitem.action") public ModelAndView getItemList(String[] ids ) { ModelAndView view = new ModelAndView(); view.setViewName("success"); return view; }
b.在方法中添加Integer ids
@RequestMapping("/queryitem.action") public ModelAndView getItemList(Integer ids ) { ModelAndView view = new ModelAndView(); view.setViewName("success"); return view; }
c.在方法中添加包含类
@RequestMapping("/queryitem.action") public ModelAndView getItemList(Integer ids,QueryVo vo ) { ModelAndView view = new ModelAndView(); view.setViewName("success"); return view; }
// 在QueryVo 类中添加list集合,属性名要和标签名一致
private List<Integer> ids; public List<Integer> getIds() { return ids; } public void setIds(List<Integer> ids) { this.ids = ids; }
二获取参数集合
2.1我们首先尝试在方法参数中添加类
@RequestMapping("/queryitem.action") public ModelAndView getItemList(Integer ids,QueryVo vo,Items items ) { ModelAndView view = new ModelAndView(); view.setViewName("success"); return view; }
可以得到结果,但是如果传递的是一个集合,我们就需要使用包装类了
2.2.1包装类
private List<Items> itemListVo; public List<Items> getItemListVo() { return itemListVo; } public void setItemListVo(List<Items> itemListVo) { this.itemListVo = itemListVo; }
2.2.2 测试代码,得到结果
@RequestMapping("/queryitem.action") public ModelAndView getItemList(Integer[] ids,QueryVo itemListVo,Items items ) { ModelAndView view = new ModelAndView(); List<Items> itemListVo2 = itemListVo.getItemListVo(); for (Items items2 : itemListVo2) { System.out.println(itemListVo2); }
三.Requestmapping
1.限制请求方式
1.1限制只能使用POST方式
@RequestMapping(value="/itemList.action",method=RequestMethod.POST)
1.2限制只能使用GET请求方式
@RequestMapping(value="/itemList.action",method=RequestMethod.GET)
不配置默认post和get请求方式都可以
2.限制请求路径
在类上面加上@RequestMapping(value="/ceshi")访问路径需要加/ceshi才能正常访问
四.controller的返回值
1.返回modelAndView
@RequestMapping(value="/itemList.action") public ModelAndView skipToItemList() { List<Items> list = itemService.getAllItems(); ModelAndView view = new ModelAndView(); view.setViewName("itemList"); view.addObject("itemList", list); return view; }
2.返回string
@RequestMapping(value="/itemList.action") public String skipToItemList(Model model ) { List<Items> list = itemService.getAllItems(); model.addAttribute("itemList", list); return "itemList"; }
3.方法值为void实现页面跳转
//方法的返回值为void实现页面的跳转 @RequestMapping(value="/itemList.action") public void skipToItemList(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { List<Items> list = itemService.getAllItems(); request.setAttribute("itemList", list); request.getRequestDispatcher("/WEB-INF/jsp/itemList.jsp").forward(request, response);//通过最原始的方式来实现页面的跳转 }
4.springMVC当中的请求转发与请求重定向
4.1请求转发 只能请求转发到项目中的资源
@RequestMapping("/updateitem.action") public String editItem(HttpServletRequest request, QueryVo vo) { // ModelAndView view = new ModelAndView(); Items items = vo.getItems(); itemService.updateItemById(items); return "forward:itemList.action"; }
4.2重定向 能够定向到项目内资源和项目外资源
// 修改数据库数据 重定向到 跳转到商品列表也页面 @RequestMapping("/updateitem.action") public String editItem(HttpServletRequest request, QueryVo vo) { // ModelAndView view = new ModelAndView(); Items items = vo.getItems(); itemService.updateItemById(items); // return "forward:itemList.action"; // return "redirect:itemList.action"; return "redirect:https://www.baidu.com/"; }五.springMVC当中的异常处理器
1.自定义我们的异常类,用于获取异常信息
//自定义异常类,获取异常信息 public class MyException extends Exception { private String exceptMsg ; public MyException(String exceptMsg) { super(); this.exceptMsg = exceptMsg; } public String getExceptMsg() { return exceptMsg; } public void setExceptMsg(String exceptMsg) { this.exceptMsg = exceptMsg; } }
2.自定义全局异常处理器
public class CustomerExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView view = new ModelAndView(); if (ex instanceof MyException) { MyException myException=(MyException) ex; String exceptMsg = myException.getExceptMsg(); view.addObject("msg", exceptMsg); }else{ //第三步定义我们的stringWriter StringWriter stringWriter = new StringWriter(); // 第二步,定义我们的printWriter将我们的异常信息往stringWriter 里面打印 PrintWriter writer = new PrintWriter(stringWriter); //第一步将异常信息打印在PrintWriter里面 ex.printStackTrace(writer); // 第四步调用tostring方法获取我们所有的异常信息 String string = stringWriter.toString(); view.addObject("msg", string); } view.setViewName("error"); return view; } }
3.在springmvc.xml中配置全局拦截器(特别注意:其中的id必须是handlerExceptionResolver)
<!-- springMVC当中配置为我们的全局异常处理器 --> <bean id="handlerExceptionResolver" class="cn.itcast.springall.exception.CustomerExceptionResolver"> </bean>
六.SpringMVC当中的图片上传
1导包
<!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
2.修改表单属性
在from表单中添加enctype="multipart/form-data"
3.设置图片访问路径
4.在springxml中配置图片视图解析器
<!-- 配置我们图片上传的解析器 注意这个id就叫做multipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 限制我们图片上传的大小为5M --> <property name="maxUploadSize" value="5242880"></property> </bean>
5.接收图片
@RequestMapping("/updateitem.action") public String editItem(HttpServletRequest request, QueryVo vo, MultipartFile pictureFile) throws IOException { Items items = vo.getItems(); // 获取图片字节流 byte[] bytes = pictureFile.getBytes(); // 获取图片原来的名字 String originalFilename = pictureFile.getOriginalFilename(); // 获取图片名 String name = pictureFile.getName(); System.out.println(bytes); System.out.println(originalFilename); System.out.println(name); // 设置图片新的名字 String newName = UUID.randomUUID() + "." + originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length()); // 调用transferTo 方法表示把我们的文件保存到哪里去 f:\\pic 文件需要重命名 File file = new File("d:\\dev\\temp" + File.separator + newName); pictureFile.transferTo(file); items.setPic(newName); //修改数据库 itemService.updateItemById(items); return "redirect:itemList.action"; }
七.springMVC当中的json数据交互
@RequestBody:将我们页面传递到台的json格式的数据转换成一个对象
@ResponseBody:将我们后台传递到页面的对象,转换成json格式的字符串
1导包(报错请检查仓库中有没有这个数据库)
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.8</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.8</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.8.8</version> </dependency>
2页面引入js
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-2.2.3.min.js"></script>
3开发ajax函数
4开发controller(返回值参数可以是字符串,也可以是类,也可以是包装类集合)
@RequestMapping("/jsonForm.action") @ResponseBody public String ajaxSend(@RequestBody Items items,HttpServletResponse response) throws IOException{ System.out.println(items.getName()); System.out.println(items.getPrice()); //response.getWriter().write("abc"); // List<Items> allItems = itemService.getAllItems(); return "aaa"; }
八.Restful风格的支持
8.1简单的就是网址中不带?及后面的任何参数(例如otems.action?id=3)
8.2把?及其后面的参数添加到网址的url连接中(otems/3)
8.3在web.xml中前端控制器配置拦截资源
<!-- 修改拦截规则 --> <url-pattern>/</url-pattern>
8.4@pathVariable获取参数
8.5在springMVC中配置不需要拦截的资源(如果有js页面就不能使用)因此需要配置不需要拦截的资源
<!-- 配置不需要拦截的资源 --> <!-- 如果web.xml当中配置的是/ 这种方式进行拦截,放过一些不需要拦截的静态资源包括css,js等 location : 表示我们的资源的路径 mapping:表示我们对应该路径下所有的资源全部放过 --> <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
九.SpringMVC拦截器
1.定义
Spring Web MVC 的处理器拦截器类似于Servlet 开发中的过滤器Filter,用于对处理器进行预处理和后处理。
区别: 拦截器不需要依赖servlet容器,过滤器需要依赖于javaWeb的环境
拦截器是spring提供的一种机制,过滤器是javaWeb提供的一种支持
2.设置自定义的拦截器(需要继承HandlerInterceptor)
2.1拦截的位置,
第一个位置.用户请求传递到前端处理器之前
第二个位置.处理器传递给前端控制器之前
第三个位置.jsp页面信息显示在用户电脑之后
2.2具体代码
public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // request.getRequestURI(); //获取请求的url地址路径 String requestURI = request.getRequestURI(); // 放过2个页面,登录页面不能拦截,登录提交页面不能拦截 if(requestURI.contains("userLogin.action") || requestURI.contains("toLoginJsp.action")){ return true; } //获取session中单账号密码 HttpSession session = request.getSession(); Object username = session.getAttribute("username"); Object password = session.getAttribute("password"); //判断是否为空,如果不为空 if (username!=null&&password!=null) { //如果不为空,判断是否正确,如果正确就登录 if (username.toString().equals("laowang")&&password.toString().equals("123456")) { return true; }else{ // 如果不正确就返回登录页面 request.setAttribute("msg", "账号密码错误1"); request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response); return false; } }else{ //如果为空,就在登录页面继续登录 request.setAttribute("msg", "账号密码错误空"); request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response); return false; } } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { } @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { } }
3.在springmvc.xml中配置拦截器
<mvc:interceptor> <mvc:mapping path="/**" /> <bean class="cn.itcast.springall.Interceptor.LoginInterceptor"></bean> </mvc:interceptor>4.进行测试