SpringMVC

SpringMVC:

学习视频:https://www.bilibili.com/video/BV1aE41167Tu/

主要文档:https://www.cnblogs.com/henuliulei/p/14643052.html

学习文档:

https://blog.csdn.net/weixin_44822455/article/details/109124359

https://blog.csdn.net/ysf15609260848/article/details/106643489

 

工作流程

 

组件介绍

 注解介绍

@Component

控制层:@RestController -> @ResponetBody + @Cpntroller

@RequestMapping 

衍生:@PutMapping ,

 @DeleteMapping【@PathValueble() - 取url模板中的变量作为参数】 ,

 @GetMapping , 

@PostMapping

@RequestParam("xx"):获取传入的值给指定参数

@ResponseBody:方法上添加@ResponseBody就可以返回json格式的字符串,告知SpringMVC框架 不进行视图跳转 直接进行数据响应

乱码: @RequestMapping(value = "/selAll",produces = {"text/plain;charset=utf-8","text/html;charset=utf-8"})
@CrossOrigin:跨域请求

服务层:@Service

dao层:@Repository

 

页面跳转

①ModelAndView对象

 如果传有ModelAndView作为形参,MVC框架会帮你注入,那么MVC会将自动给你创建一个ModelAndView对象供你使用

@RequestMapping(value="/quick3")
public ModelAndView save3(ModelAndView modelAndView){
modelAndView.addObject("username","itheima");
modelAndView.setViewName("success");
return modelAndView;
}

②返回字符串形式

 3.model

   public String list(Model model) {
        model.addAttribute("list", list);
        return "souccess";
    }

 

配置

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

  <display-name>Archetype Created Web Application</display-name>

 <!--配置前端控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 读取springmvc -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <!-- 优先级 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <!-- 配置拦截路径url-->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!-- spring上下文监听器 -->
  <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- 加载Spring -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:spring.xml</param-value>
  </context-param>

  <!--配置乱码过滤器-->
  <filter>
    <filter-name>encoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

spring-mvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

    <!--配置注解扫描-->
    <context:component-scan base-package="com.xinyu"/>

    <!--加载mvc驱动:自动注册映射器与适配器-->
    <mvc:annotation-driven />

    <!--不过滤静态资源-->
    <mvc:default-servlet-handler/>

    <!--静态资源映射-->
<!--    <mvc:resources mapping="/js/**" location="/WEB-INF/js/"/>-->

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 视图前缀 -->
        <property name="prefix" value="/WEB-INF/html/"/>
        <!-- 视图后缀 -->
        <property name="suffix" value=".html"/>
    </bean>

    <!--json解析-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=utf-8</value>
                        <value>text/html;charset=utf-8</value>
                    </list>
                </property>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json; charset=UTF-8</value>
                        <value>application/x-www-form-urlencoded; charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--文件上传-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--上传文件总大小-->
        <property name="maxUploadSize" value="5242800"/>
        <!--上传单个文件的大小-->
        <property name="maxUploadSizePerFile" value="5242800"/>
        <!--临时文件路径-->
        <property name="uploadTempDir" value="/fileUpLoad/temp"/>
        <!--上传文件的编码类型-->
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

</beans>

 

功能

文件上传

方法传入参数:MultipartFile , HttpServletRequest

       //MultipartFile为了获取前台的文件
        String srcPath = file.getOriginalFilename();
        if (!"".equals(srcPath)) {
            //HttpServletRequest为了获取后台猫的绝对路径
            String tomcatPath = request.getServletContext().getRealPath("/images");
            //实现文件上传
            //获取上传文件的后缀
            String suffix = srcPath.substring(srcPath.lastIndexOf("."));
            //获取UUID
            UUID uuid = UUID.randomUUID();
            String prefix = uuid.toString().replace("-", "").toUpperCase();
            //完整文件名
            String fileName = prefix + suffix;

            try {
                file.transferTo(new File(tomcatPath, fileName));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            flag = studentService.upIcon(id,"default.jsp");
        }

拦截器

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle 执行");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle 执行");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion 执行");
    }
}

 xml配置

<mvc:interceptors>
    <mvc:interceptor>
        <!--配置拦截器拦截的请求路径-->
        <mvc:mapping path="/**"/>
        <!--配置拦截器不需要拦截的请求路径-->
        <mvc:exclude-mapping path="/"/>
        <!--定义在 <mvc:interceptors> 下,表示拦截器只对指定路径的请求进行拦截-->
        <bean class="net.biancheng.c.interceptor.MyInterceptor"></bean>
    </mvc:interceptor>
</mvc:interceptors>

 

posted @ 2022-10-09 13:29  歆鱼  阅读(16)  评论(0编辑  收藏  举报