栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springmvc(配置和无配置)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springmvc(配置和无配置)

通过idea创建一个springweb项目后要使用mvc首先要在pom.xml导入相关的依赖

  
      org.springframework
      spring-jdbc
      5.3.10
    
第一步

在web-inf目录下进行第一步配置,先说一下,这个配置文件的模板是在汤姆毛配置文件里面截取的

 截取替换原本的web.xml内容后进行相关配置,配置核心映射文件要用到resources文件夹下面的配置文件,下一步配置





  
    springmvc
    org.springframework.web.servlet.DispatcherServlet

    
      contextConfigLocation
      classpath:springmvc.xml
    
  
  


  springmvc
  /





  
    nmdwsm
    org.springframework.web.filter.CharacterEncodingFilter

    
      encoding
      utf-8
    
  

  
    nmdwsm
    /*
  

第二步

在resources下面创建配置文件如springmvc.xml,然后进行相关的配置,我这个是直接搬运模板写的,所以有些用不到的也写进去了,配置标签的意思写在注释上面了



    
    
    
    
    
    

    
    
        
        
    

第三步

创建一个测试类,来进行请求转发到这个自带的jsp文件

package com.entor.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
//该类用作请求处理类
@org.springframework.stereotype.Controller
@RequestMapping("/hello")
public class Controller {

//    处理请求地址,如果类上也有相同注解,请求地址需要先拼接类上的地址
//    方法返回逻辑视图名称,通过配置文件的视图解释器,知道对应的视图进行展示
//    根据查找规则,前缀加上视图名称再加上后缀,此方法犯规对应的视图文件是
//    /index.jsp
    @PostMapping("")
    @RequestMapping(value = "index",method = {RequestMethod.GET,RequestMethod.POST})
    public String index(){
        System.out.println("hellow gay");
        return "index";
    }

}

上面的第一个注释表示请求的类型和括号里面可以填拦截的访问url,第二个同样是相同的功能,但是可以同时拦截get和post请求

spring进行多个参数的接收,首先创建好一个实体类,之后通过实体类的字段和前台传来的字段进行映射,这里如果学过servlet会很容易理解,map的功能和request.serAttribute的功能差不多,另外前台传来的参数全部是字符串,所以要对时间类型进行相关处理

//客户端传递多个参数可以封装成对象,
    @PostMapping("/param4")
    public String zz4(User user, Map map) throws UnsupportedEncodingException {
        System.out.println("param4");
        map.put("user", user);
        return "show";
    }

//定义处理日期的规则,参数绑定

    @InitBinder
    public void zz5(WebDataBinder binder){

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");


        CustomDateEditor customDateEditor = new CustomDateEditor(format, true);
//        指定对象和规则
        binder.registerCustomEditor(Data.class,customDateEditor);


    }

这个是通过绑定的方式对时间对象进行处理,还有可以通过注解的方式对日期对象进行处理,这里通过对象映射获取前台传递来的参数,学过mybatis的都知道,这些框架可以通过set方法吧获取的变量映射到实体类对应的属性中

  @JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")//格式化日期类型格式
    private Date birthday;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Timestamp createTime;

文件上传相关,首先是依赖

  
    
      org.springframework
      spring-webmvc
      5.3.9
    
    
      javax.servlet
      javax.servlet-api
      4.0.1
    
    
      jstl
      jstl
      1.2
    
    
      org.projectlombok
      lombok
      1.18.16
    
    
      com.alibaba
      fastjson
      1.2.76
    
    
    
      com.fasterxml.jackson.core
      jackson-databind
      2.11.3
    
    
    
      org.apache.commons
      commons-lang3
      3.11
    
    
    
      cn.hutool
      hutool-all
      5.3.9
    
    
    
      commons-fileupload
      commons-fileupload
      1.4
    
    
      junit
      junit
      4.11
      test
    
  

然后是配置文件,在resources中

    
    
        
        
        
        
        
        
    

前台

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    文件上传


    
文件:

文件1:
文件2:
文件3:

后台

package com.entor.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
public class UploadController {

    @PostMapping(value = "/uploadFile",produces = "application/json;charset=utf-8")
    public String uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
        String realPath = request.getServletContext().getRealPath("/upload/");
        File f = new File(realPath);
        if(!f.exists()){
            f.mkdir();
        }
        String fileName = file.getOriginalFilename();
        String contentType = file.getContentType();
        long size = file.getSize();
        System.out.println("文件名称:"+fileName);
        System.out.println("文件类型:"+contentType);
        System.out.println("文件大小:"+size);
        //文件上传
        file.transferTo(new File(realPath,fileName));
        return "上传成功";
    }

    @PostMapping(value = "/uploadFiles",produces = "application/json;charset=utf-8")
    public String uploadFiles(MultipartFile[] file, HttpServletRequest request) throws IOException {
        String realPath = request.getServletContext().getRealPath("/upload/");
        File f = new File(realPath);
        if(!f.exists()){
            f.mkdir();
        }
        for(MultipartFile file1:file){
            String fileName = file1.getOriginalFilename();
            String contentType = file1.getContentType();
            long size = file1.getSize();
            System.out.println("文件名称:"+fileName);
            System.out.println("文件类型:"+contentType);
            System.out.println("文件大小:"+size);
            //文件上传
            file1.transferTo(new File(realPath,fileName));
        }
        return "上传成功";
    }
}

拦截器

package com.entor.interceptor;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class TestInterceptorPro implements HandlerInterceptor {

    //  你这瓜保熟吗?在业务处理器处理请求之前被调用。
//  预处理,可以进行编码、安全控制、权限校验等处理,返回true和false
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("保熟");
        return true;
    }

    //爱要不要咋地
//在业务处理器处理请求执行完成后,生成视图之前执行。
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("咋地");

        Map model = modelAndView.getModel();

        System.out.println(model.get("msg"));

        model.put("msg2","postHandle");

        modelAndView.setViewName("nmdwsm");

    }

    //萨日朗
//在DispatcherServlet完全处理完请求后被调用
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("跑路");

    }
}

测试

package com.entor.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class TestSequence {


    @RequestMapping(value = "/handle", method = {RequestMethod.POST, RequestMethod.GET})
    public String index(Model model){

        model.addAttribute("msg","nmdwsm");


        return "index";

    }




}

前台

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/9/26 0026
  Time: 上午 11:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


${msg}
${msg2}

多个拦截器的执行顺序

划重点,无参配置,

package com.entor.config;


import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;


@Configuration
@EnableWebMvc//相当于
@ComponentScan(basePackages = "com.entor.controller")
public class SpringMvcConfig implements WebMvcConfigurer {


    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {

        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setPrefix("/");
        internalResourceViewResolver.setSuffix(".jsp");

        registry.viewResolver(internalResourceViewResolver);

    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {

    }
}

配置web.xml的无参类

package com.entor.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

//web.xml配置类
public class WebConfig implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();

//加载springmvc配置类
        context.register(SpringMvcConfig.class);
//配置内置参数
        DispatcherServlet servlet = new DispatcherServlet(context);

        ServletRegistration.Dynamic springmvc = servletContext.addServlet("springmvc", servlet);
//配置url
        springmvc.addMapping("/");


    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/285636.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号