• springmvc3:ajax请求,文件上传下载,拦截器,异常处理,注解配置mvc


    一.框架与代码

    1.ajax

    ①ajax访问

    在这里插入图片描述

    ②具体代码

    • 发送ajax请求
    <script type="text/javascript" th:src="@{/js/vue.js}">script>
    <script type="text/javascript" th:src="@{/js/axios.min.js}">script>
    <script type="text/javascript">
    var vue = new Vue({
    el:"#app",
    methods:{
    testRequestBody(){
    axios.post(
    "/SpringMVC/test/RequestBody/json",
    {username:"admin",password:"123456"}
    ).then(response=>{
    console.log(response.data);
    });
    }
    }
    });
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 服务器利用RequestBody转换json字符串
    //将json格式的数据转换为map集合
    @RequestMapping("/test/RequestBody/json")
    public void testRequestBody(@RequestBody Map<String, Object> map,
    HttpServletResponse response) throws IOException {
    System.out.println(map);
    //{username=admin, password=123456}
    response.getWriter().print("hello,axios");
    }
    //将json格式的数据转换为实体类对象
    @RequestMapping("/test/RequestBody/json")
    public void testRequestBody(@RequestBody User user, HttpServletResponse
    response) throws IOException {
    System.out.println(user);
    //User{id=null, username='admin', password='123456', age=null,
    gender='null'}
    response.getWriter().print("hello,axios");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 服务器利用responseBody返回响应的数据
    //响应浏览器list集合
    @RequestMapping("/test/ResponseBody/json")
    @ResponseBody
    public List<User> testResponseBody(){
    User user1 = new User(1001,"admin1","123456",23,"男");
    User user2 = new User(1002,"admin2","123456",23,"男");
    User user3 = new User(1003,"admin3","123456",23,"男");
    List<User> list = Arrays.asList(user1, user2, user3);
    return list;
    }
    //响应浏览器map集合
    @RequestMapping("/test/ResponseBody/json")
    @ResponseBody
    public Map<String, Object> testResponseBody(){
    User user1 = new User(1001,"admin1","123456",23,"男");
    User user2 = new User(1002,"admin2","123456",23,"男");
    User user3 = new User(1003,"admin3","123456",23,"男");
    Map<String, Object> map = new HashMap<>();
    map.put("1001", user1);
    map.put("1002", user2);
    map.put("1003", user3);
    return map;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • responsebody返回数据的转换格式
      • 实体类–>json对象
      • map–>json对象
      • list–>json数组

    2.文件上传与下载

    ①框架

    在这里插入图片描述

    ②使用

    • 下载功能
    @RequestMapping("/testDown")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws
    IOException {
    //获取ServletContext对象
    ServletContext servletContext = session.getServletContext();
    //获取服务器中文件的真实路径
    String realPath = servletContext.getRealPath("/static/img/1.jpg");
    //创建输入流
    InputStream is = new FileInputStream(realPath);
    //创建字节数组
    byte[] bytes = new byte[is.available()];
    //将流读到字节数组中
    is.read(bytes);
    //创建HttpHeaders对象设置响应头信息
    MultiValueMap<String, String> headers = new HttpHeaders();
    //设置要下载方式以及下载文件的名字
    headers.add("Content-Disposition", "attachment;filename=1.jpg");
    //设置响应状态码
    HttpStatus statusCode = HttpStatus.OK;
    //创建ResponseEntity对象
    ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers,
    statusCode);
    //关闭输入流
    is.close();
    return responseEntity;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 上传功能
    
    <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    @RequestMapping("/testUp")
    public String testUp(MultipartFile photo, HttpSession session) throws
    IOException {
    //获取上传的文件的文件名
    String fileName = photo.getOriginalFilename();
    //处理文件重名问题
    String hzName = fileName.substring(fileName.lastIndexOf("."));
    fileName = UUID.randomUUID().toString() + hzName;
    //获取服务器中photo目录的路径
    ServletContext servletContext = session.getServletContext();
    String photoPath = servletContext.getRealPath("photo");
    File file = new File(photoPath);
    if(!file.exists()){
    file.mkdir();
    }
    String finalPath = photoPath + File.separator + fileName;
    //实现上传功能
    photo.transferTo(new File(finalPath));
    return "success";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    3.拦截器

    ①框架

    在这里插入图片描述

    ②代码

    <bean class="com.atguigu.interceptor.FirstInterceptor">bean>
    <ref bean="firstInterceptor">ref>
    
    <mvc:interceptor>
    	<mvc:mapping path="/**"/>
    		<mvc:exclude-mapping path="/testRequestEntity"/>
    	<ref bean="firstInterceptor">ref>
    mvc:interceptor>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    public class FirstInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            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 {
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    4.异常处理

    ①框架

    在这里插入图片描述

    ②代码

    <bean
    class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
    <props>
    
    <prop key="java.lang.ArithmeticException">errorprop>
    props>
    property>
    
    <property name="exceptionAttribute" value="ex">property>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    //@ControllerAdvice将当前类标识为异常处理的组件
    @ControllerAdvice
    public class ExceptionController {
    //@ExceptionHandler用于设置所标识方法处理的异常
    @ExceptionHandler(ArithmeticException.class)
    //ex表示当前请求处理中出现的异常对象
    public String handleArithmeticException(Exception ex, Model model){
    model.addAttribute("ex", ex);
    return "error";
    }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    5.基于注解的Springmvc

    ①为什么可以配置基于注解的Springmvc

    • servlet环境中,首先会有servlet容器
    • serlvet容器会自动发现 继承了AbstractAnnotationConfigDispatcherServletInitializer的类来配置servlet的上下文

    ②配置代码(部分)

    • 配置web.xml
    public class WebInit extends
    AbstractAnnotationConfigDispatcherServletInitializer {
    /**
    * 指定spring的配置类
    * @return
    */
    @Override
    protected Class[] getRootConfigClasses() {
    return new Class[]{SpringConfig.class};
    }
    /**
    * 指定SpringMVC的配置类
    * @return
    */
    @Override
    protected Class[] getServletConfigClasses() {
    return new Class[]{WebConfig.class};
    }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 配置springmvc.xml
    @Configuration
    //扫描组件
    @ComponentScan("com.atguigu.mvc.controller")
    //开启MVC注解驱动
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {
    //使用默认的servlet处理静态资源
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer
    configurer) {
    configurer.enable();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
  • 相关阅读:
    高阶面试-mongodb
    1、Flutter使用总结(RichText、Container)
    如何平衡三维模型的顶层合并构建的文件大小与质量关系
    计算机组成原理知识点总结——第七章输入/输出系统
    ML XGBoost详细原理及公式推导讲解+面试必考知识点
    【网络编程】传输层——UDP协议
    vuex(store) 之 namespace(命名空间)、mapState、mapGetters等
    Google 向中国开发者开放数百份 TensorFlow 资源
    【日常记录】Connection reset
    从事软件开发工作的一些感悟
  • 原文地址:https://blog.csdn.net/qq_44724899/article/details/127764952