SpringMVC第二讲

SpringMVC day02笔记
课前事项
[了解]今日课程内容
SpringMVC中Controller方法(Handler方法)返回值类型【掌握】
ModelAndView……
@ModelAttribute和@SessionAttributes【了解】
SpringMVC对Restful风格url的支持【掌握】
于我们而言,就是传参风格的一种变化
JSON数据交互【掌握】
SpringMVC的文件上传【应用】
方式一:上传到本地服务器
方式二:跨服务器上传
SpringMVC的异常处理【应用】
SpringMVC的全局异常处理机制

[掌握]Controller方法(Handler)的返回值
返回ModelAndView
返回字符串(直接返回逻辑视图名字符串,数据使用Model或者ModelMap封装)
ModelAndView = model + view(逻辑视图名)
/**Controller方法返回String使用Model

  • Model是接口
  • @param model
  • @return
    */
    @RequestMapping(“gotoResultReturnStrModel”)
    public String gotoResultReturnStrModel(Model model) {
    model.addAttribute(“nowDate”,new Date() + “—>>>model”);
    return “result”;
    }

/**Controller方法返回String使用ModelMap

  • ModelMap是接口Model的实现
  • 注意:Model没有get方法,ModelMap方法有get方法,所以你要取值就声明ModelMap使用
  • @param model
  • @return
    */
    @RequestMapping(“gotoResultReturnStrModelMap”)
    public String gotoResultReturnStrModelMap(ModelMap model) {
    model.addAttribute(“nowDate”,new Date() + “—>>>modelMap”);
    return “result”;
    }

返回void(了解)
直接使用HttpServletRequest对象转发请求
直接使用HttpServletResponse对象重定向请求
直接使用HttpServletResponse输出结果
/**Controller方法返回void

  • 使用request进行请求转发
  • @param model
  • @return
    */
    @RequestMapping(“gotoResultReturnVoid”)
    public void gotoResultReturnVoid(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.getRequestDispatcher("/WEB-INF/jsp/result.jsp").forward(request,response);
    }

/**Controller方法返回void

  • 使用response重定向
  • @param model
  • @return
    */
    @RequestMapping(“gotoResultReturnVoidRedirect”)
    public void gotoResultReturnVoidRedirect(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.sendRedirect(“gotoResult.action”);
    }

/**Controller方法返回void

  • 使用response直接输出字符串
  • @param model
  • @return
    */
    @RequestMapping(“gotoResultReturnVoidWrite”)
    public void gotoResultReturnVoidWrite(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.getWriter().write(“Hello SpringMVC!”);
    }

转发和重定向(返回字符串形式)
/**Controller方法返回void

  • 使用request进行请求转发
  • @param model
  • @return
    */
    @RequestMapping(“gotoResultReturnVoid2”)
    public String gotoResultReturnVoid2(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //request.getRequestDispatcher("/WEB-INF/jsp/result.jsp").forward(request,response);
    return “forward:/WEB-INF/jsp/result.jsp”;
    }

/**Controller方法返回void

  • 使用response重定向
  • @param model
  • @return
    */
    @RequestMapping(“gotoResultReturnVoidRedirect2”)
    public String gotoResultReturnVoidRedirect2(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //response.sendRedirect(“gotoResult.action”);
    return “redirect:gotoResult.action”;
    }

[应用]@ModelAttribute@SessionAttributes
@ModelAttribute
场景有限
@SessionAttributes

/**

  • 第一个handler:发起一个请求,后端把请求参数写入session
  • 第二个handler:发起一个请求,取出session当中存入的数据
  • 第三个handler:发起一个请求,清空session
    */
    @RequestMapping(“setSessionValue”)
    public String setSessionValue(Model model) {
    model.addAttribute(“field1”,“value1”);
    model.addAttribute(“nowDate”,new Date() + “—>>>该请求向session写入数据”);
    return “result”;
    }

@RequestMapping(“getSessionValue”)
public String getSessionValue(ModelMap model) {
model.addAttribute(“nowDate”,new Date() + “—>>>从session取出数据:” + model.get(“field1”));
return “result”;
}

/*
SessionStatus提供setComplete方法用于清空session中通过@SessionAttributes
共享的数据
*/
@RequestMapping(“clearSession”)
public String clearSession(Model model,SessionStatus sessionStatus) {
sessionStatus.setComplete();
model.addAttribute(“nowDate”,new Date() + “—>>>清空@SessionAttributes共享的数据”);
return “result”;
}

[应用]SpringMVC对Restful风格URL的支持
直观而言,是传参风格的一种变化,原来参数跟在?后面,现在参数在url路径中

什么是RESTful?
RESTful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种url设计风格。基于这个风格设计的软件可以更简洁,更有层次。

资源:互联网所有的事物都可以被抽象为资源 url(只要互联网上的事物可以用一个url来表示,那么它就是一个资源)
资源操作:使用POST、DELETE、PUT、GET不同方法对同一资源(同一url)进行操作。
分别对应 添加、 删除、修改、查询

Http主要的请求方式
get 主要是想做select
post 主要是想做insert
put 主要是想做update
delete 主要是想做delete
以上是http协议的标准请求方式,当然你用post请求也完全可以完成crud操作(因为归根结底无非就是把参数传递到后台对应处理即可)

传统方式操作资源
操作啥 (原来url)?操作谁(传入的参数)
url中先定义动作,然后传递的参数表明这个动作操作的是哪个对象(数据)
先定位动作,然后定位对象
http://localhost:8080/springmvc02/user/queryUserById.action?id=1 查询
http://localhost:8080/springmvc02/ user /saveUser.action 新增
http://localhost:8080/springmvc02/ user /updateUser.action 更新
http://localhost:8080/springmvc02/ user /deleteUserById.action?id=1 删除

使用RESTful操作资源
先定义对象
http://localhost:8080/springmvc02/user/1操作的对象) 查询,GET
http://localhost:8080/springmvc02/ user 新增,POST
http://localhost:8080/springmvc02/ user 更新,PUT
http://localhost:8080/springmvc02/ user /1 删除,DELETE
HiddentHttpMethodFilter过滤器
作用:由于浏览器 form 表单只支持 GET 与 POST 请求,而DELETE、PUT 等 method 并不支持,Spring3.0之后添加了一个过滤器,可以将浏览器请求改为指定的请求方式,发送给我们的控制器方法,使得支持 GET、POST、PUT 与DELETE 请求。
第一步:在web.xml中配置该过滤器

methodFilter org.springframework.web.filter.HiddenHttpMethodFilter methodFilter /*

第二步:请求方式必须使用post请求
第三步:增加请求参数_method,该参数的取值就是我们需要的请求方式

SpringMVC对Restful风格url的支持

测试用例Use_case11:SpringMVC对Restful风格url的支持

<%-- 点击测试--%> rest_get测试

第四步:后台接收

@RequestMapping(value = “{id}”,method = RequestMethod.GET)
public String queryUserById1(@PathVariable(“id”) Integer id, Model model) {
System.out.println("======查询:" + id);
model.addAttribute(“nowDate”,new Date());
return “redirect:/default/gotoResult.action”;
}
@RequestMapping(value = “{id}”,method = RequestMethod.DELETE)
public String queryUserById2(@PathVariable(“id”) Integer id,Model model) {
System.out.println("======删除:" + id);
model.addAttribute(“nowDate”,new Date());
return “redirect:/default/gotoResult.action”;
}
@RequestMapping(value = “”,method = RequestMethod.POST)
public String queryUserById3(User user,Model model) {
System.out.println("======新增:" + user);
model.addAttribute(“nowDate”,new Date());
return “redirect:/default/gotoResult.action”;
}
@RequestMapping(value = “”,method = RequestMethod.PUT)
public String queryUserById4(User user,Model model) {
System.out.println("======更新:" + user);
model.addAttribute(“nowDate”,new Date());
return “redirect:/default/gotoResult.action”;
}

[应用]Json数据交互
Json数据是咱们企业级开发数据交互经常使用的一种方式,它比较轻量级,格式比较清晰(系统间接口调用/前后端调用,json数据格式都广为使用)
Json数据交互:前端传递json字符串到后台,后台如何能够自动转换为pojo对象;后台return 对象,能否前端直接接收到json格式的字符串
@RequestBody注解
作用:用于获取请求体(按照http协议进行一个完整的封装,往往都是由请求头+请求体等组成)内容,不适用于Get请求方式,只能使用post请求方式

更多的是用于将JSON字符串转换为POJO对象
引入json相关jar坐标

com.fasterxml.jackson.core
jackson-core
2.9.0


com.fasterxml.jackson.core
jackson-databind
2.9.0


com.fasterxml.jackson.core
jackson-annotations
2.9.0

前端ajax传递json字符串(post)到后台,后台直接接收为对象
@ResponseBody注解
作用:该注解用于将Controller的方法返回的对象转换为json字符串返回给客户端
代码
@RequestMapping(“sendJsonStr”)
public @ResponseBody User sendJsonStr(@RequestBody User user) {
user.setAddress(“上海”);
System.out.println("-------------->>>>sendJsonStr:" + user);
return user;
}
$(function () {
$("#ajaxBtn").bind(“click”,function () {
KaTeX parse error: Expected '}', got 'EOF' at end of input: … url:"{pageContext.request.contextPath}/user/sendJsonStr.action",
type:“post”,
data:’{“id”:1,“username”:“zhangsan”}’,
contentType:“application/json;charset=utf-8”,
dataType:“json”,
success:function (data) {
alert(data);
alert(data.address);
console.log(data);
}
})
})
})

[应用]SpringMVC实现文件上传

前提条件

引入坐标

commons-fileupload
commons-fileupload
1.3.1

编写Handler
@RequestMapping(“testUploadFile”)
public String testUploadFile(MultipartFile uploadFile, HttpServletRequest request) throws IOException {
// 文件原名,如xxx.jpg
String originalFilename = uploadFile.getOriginalFilename();
// 获取文件的扩展名,如jpg
String extendName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
String uuid = UUID.randomUUID().toString();
// 新的文件名字
String newName = uuid + “.” + extendName;
String realPath = request.getSession().getServletContext().getRealPath("/uploads");
// 解决文件夹存放文件数量限制,按日期存放
String datePath = new SimpleDateFormat(“yyyy-MM-dd”).format(new Date());
File floder = new File(realPath + “/” + datePath);
if(!floder.exists()) {
floder.mkdirs();
}
uploadFile.transferTo(new File(floder,newName));
return “success”;
}
配置文件上传解析器

跨服务器上传 分服务器的目的

在文件服务器的tomcat配置中加入,允许读写操作
119行

主应用引入jar坐标

com.sun.jersey
jersey-core
1.18.1


com.sun.jersey
jersey-client
1.18.1

Handler处理程序
@RequestMapping(“testUploadFileRemote”)
public String testUploadFileRemote(MultipartFile uploadFile, HttpServletRequest request) throws IOException {
// 文件原名,如xxx.jpg
String originalFilename = uploadFile.getOriginalFilename();
// 获取文件的扩展名,如jpg
String extendName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
String uuid = UUID.randomUUID().toString();
// 新的文件名字
String newName = uuid + “.” + extendName;
String realPath = request.getSession().getServletContext().getRealPath("/uploads");
// 解决文件夹存放文件数量限制,按日期存放
String datePath = new SimpleDateFormat(“yyyy-MM-dd”).format(new Date());
File floder = new File(realPath + “/” + datePath);
if(!floder.exists()) {
floder.mkdirs();
}

Client client = Client.create();
String baseUrl = "http://localhost:8081/fileserver/uploads/";
WebResource webResource = client.resource(baseUrl+newName);
String result = webResource.put(String.class,uploadFile.getBytes());
System.out.println(result);
return "success";

}
注意:文件上传解析器仍然需要配置
[理解]SpringMVC中的异常处理
Controller—>Service—>Dao层,异常统一向上抛出,可以自定义全局异常处理器统一处理异常
异常类型:编译异常、运行时异常;运行时异常、预期异常(自定义异常)
自定义异常
package com.itheima.springmvc.exception;

public class MyException extends Exception {
private String message;

public MyException(String message) {
    this.message = message;
}

@Override
public String getMessage() {
    return message;
}

}
自定义异常处理器
package com.itheima.springmvc.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    String message = null;
    if(ex instanceof MyException) {
        // 自定义异常
        message = ex.getMessage();
    }else {
        // 运行时异常
        message = "系统出现未知异常,请联系管理员";
    }

    // 跳转到一个友好的提示页面
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("exception",message);
    modelAndView.setViewName("exception");
    return modelAndView;
}

}

注册自定义异常处理器

作业
“应用”的部分练习一遍,用的时候知道从哪里找就可以
“掌握”的部分好好练习包括Json数据交互

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值