再下一城 - SpringMVC框架笔记(二)
发布日期:2021-05-11 00:06:06 浏览次数:21 分类:精选文章

本文共 4846 字,大约阅读时间需要 16 分钟。

SpringMVC框架技术实战指南

第一天:响应数据与视图

返回值类型分类

1. 返回值是字符串

  • 逻辑视图名解析:通过返回字符串指定逻辑视图名(如success),视图解析器会将其解析为物理视图地址(如/WEB-INF/pages/success.jsp)。
  • 示例代码
    @Controller
    @RequestMapping(path = "/user")
    public class UserController {
    @RequestMapping(path = "/returnString")
    public String returnString(Model model) {
    System.out.println("returnString方法执行了...");
    User user = new User();
    user.setUsername("张三");
    user.setPassword("123");
    user.setAge(20);
    model.addAttribute("user1", user);
    return "success";
    }
    }
  • 对应页面/WEB-INF/pages/success.jsp

2. 返回值是void

  • 默认跳转:若返回void,默认跳转到方法名对应的JSP页面(如/returnVoid.jsp)。
  • 手动跳转:可通过request.getRequestDispatcherresponse.sendRedirect实现。
  • 示例代码
    @Controller
    @RequestMapping(path = "/returnVoid")
    public class UserController {
    @RequestMapping(path = "/returnVoid")
    public void returnVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
    System.out.println("returnVoid方法执行了...");
    request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request, response);
    response.sendRedirect(request.getContextPath() + "index.jsp");
    response.setContentType("text/html;charset=UTF-8");
    response.getWriter().print("你好");
    }
    }

3. 返回值是ModelAndView

  • 功能说明:可用于传递模型数据和调整视图。
  • 示例代码
    @Controller
    @RequestMapping(path = "/returnModelAndView")
    public class UserController {
    @RequestMapping("returnModelAndView")
    public ModelAndView returnModelAndView() {
    System.out.println("returnModelAndView方法执行了...");
    ModelAndView mv = new ModelAndView();
    User user = new User();
    user.setUsername("李四");
    user.setPassword("345");
    user.setAge(28);
    mv.addObject("user1", user);
    mv.setViewName("success");
    return mv;
    }
    }

第二天:文件上传实现

文件上传基础

1. 前提条件

  • 表单属性
    • enctype="multipart/form-data"
    • method="post"
    • 包含<input type="file">标签
  • 服务器端依赖
    • commons-fileuploadcommons-io jar包

2. 安装依赖

commons-fileupload
commons-fileupload
1.3.1
commons-io
commons-io
2.4

传统文件上传

1. jsp页面

选择文件:

2. Controller逻辑

@RequestMapping("/fileUpload2")
public class UserController {
@RequestMapping("/fileUpload2")
public String fileUpload2(HttpServletRequest request, MultipartFile upload) throws Exception {
System.out.println("文件上传处理...");
String path = request.getServletContext().getRealPath("/uploads/");
if (!new File(path).exists()) {
new File(path).mkdirs();
}
String fileName = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "");
fileName = uuid + "_" + fileName;
upload.transferTo(new File(path, fileName));
return "success";
}
}

异常处理

自定义异常类

package cn.itcast.exception;
public class SysException extends Exception {
private String message;
public SysException(String message) {
this.message = message;
}
@Override
public String getMessage() {
return message;
}
}

异常处理器配置

  • 异常处理器
package cn.itcast.exception.resolver;
import cn.itcast.exception.SysException;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SysExceptionResolver implements org.springframework.web.servlet.HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
SysException exception = null;
if (e instanceof SysException) {
exception = (SysException) e;
} else {
exception = new SysException("服务器正在维护中...");
}
ModelAndView mv = new ModelAndView();
mv.addObject("errorMsg", exception.getMessage());
mv.setViewName("error");
return mv;
}
}

异常使用示例

@RequestMapping("/testException")
public String testException() throws SysException {
System.out.println("执行testException方法");
try {
int x = 10 / 0;
} catch (Exception e) {
throw new SysException("系统异常:数据加载失败");
}
return "success";
}

拦截器实现

自定义拦截器

package cn.itcast.interceptor;
public class MyInterceptor1 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("MyInterceptor1的preHandle方法执行了...");
return true;
}
}

拦截器配置

拦截器执行顺序

执行顺序:preHandle → Controller → postHandle → success.jsp → afterCompletion

上一篇:再下一城 - SpringMVC框架笔记(三) SSM整合
下一篇:Typora有用技巧

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2025年04月24日 00时43分34秒