响应数据和结果视图
1. 返回值分类
- 返回字符串
@RequestMapping(path ="/testString")
public String testString(Model model){
System.out.println("方法执行了");
// 模拟从数据库中查询的数据
User user=new User();
user.setUsername("胡歌");
user.setPassword("123456");
user.setAge(20);
model.addAttribute("user",user);
return "success";
}
public class User {
private String username;
private String password;
private Integer age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}
success.jsp
<body>
<h1>查询成功</h1>
//获取查询到的数据
${user.username}
${user.password}
${user.age}
</body>
- 返回值是void
. 如果控制器的方法返回值编写成void,执行程序报404的异常,默认查找JSP页面没有找到。
我们 可以使用请求转发或者重定向跳转到指定的页面,还可以直接响应数据。
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request,HttpServletResponse response) throws Exception {
System.out.println("方法执行了");
//请求转发,视图解析器不会进行解析
//所以路径必须完整,
//request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
//重定向
// response.sendRedirect(request.getContextPath()+"/index.jsp");
//解决直接响应中文乱码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//直接进行响应
response.getWriter().write("你好");
return;
}
3 返回值是ModelAndView对象
@RequestMapping("/testModeAndView")
public ModelAndView testModeAndView(){
//创建一个ModelAndView对象
ModelAndView mv=new ModelAndView();
System.out.println("方法执行了");
// 模拟从数据库中查询所有的用户信息
User user=new User();
user.setUsername("胡歌");
user.setPassword("123456");
user.setAge(20);
//把user对象存储到mv对象中,也会把user对象存入到request对象中
mv.addObject("user",user);
//跳转到哪个页面
mv.setViewName("success");
return mv;
}
SpringMVC框架提供的转发和重定向
//请求转发
@RequestMapping("/testForward")
public String testForward(){
return "forward:WEB-INF/pages/success.jsp";
}
//重定向
@RequestMapping("/testRedirect")
public String testRedirect(){
return "redirect:/success.jsp";
}
SpringMVC方式文件上传
@RequestMapping(value="/fileupload")
public String fileupload2(HttpServletRequest request, MultipartFile upload) throws Exception {
System.out.println("SpringMVC方式的文件上传...");
// 先获取到要上传的文件目录
String path = request.getSession().getServletContext().getRealPath("/uploads");
// 创建File对象,一会向该路径下上传文件
File file = new File(path);
// 判断路径是否存在,如果不存在,创建该路径
if(!file.exists()) { file.mkdirs(); }
// 获取到上传文件的名称
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
// 把文件的名称唯一化
filename = uuid+"_"+filename;
//上传文件
upload.transferTo(new File(file,filename));
return "success"; }
}
<body>
<h1>文件上传</h1>
<form action="/user/fileupload" method="post" enctype="multipart/form-data">
文件上传:<input type="file" name="upload"><br>
<input type="submit" value="上传">
</form>
</body>
注意:
表单上传文件的name的名字,必须与方法的参数的名字名字一样
SpringMVC的异常处理
异常处理思路
- Controller调用service,service调用dao,异常都是向上抛出的,最终有DispatcherServlet找异常处理器进
行异常的处理。
SpringMVC的异常处理
public class SysException extends Exception{
static final long serialVersionUID = 4055945147128016300L;
// 异常提示信息
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SysException(String message) {
this.message = message;
}
}
自定义异常处理器
public class SysExceptionResolver implements HandlerExceptionResolver{
/*** 跳转到具体的错误页面的方法 */
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
ex.printStackTrace();
SysException e = null;
// 获取到异常对象
if(ex instanceof SysException) {
e = (SysException) ex;
}
else {
e = new SysException("请联系管理员");
}
ModelAndView mv = new ModelAndView();
// 存入错误的提示信息
mv.addObject("message", e.getMessage());
// 跳转的Jsp页面 mv.setViewName("error");
return mv; }
}
. 配置异常处理器
<!-- 配置异常处理器 -->
<bean id="sysExceptionResolver"class="cn.itcast.exception.SysExceptionResolver"/>