SpringMVC后续4

文件上传下载

导入maven

XML 复制代码
<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.2</version>
    </dependency>

配置MultipartResolver

XML 复制代码
<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置上传文件的最大尺寸为5MB -->
    <property name="maxUploadSize" >
        <value>5242880</value>
    </property>
</bean>

创建表单

java 复制代码
<form action="uploadFile" method="post" enctype="multipart/form-data">
    文件:<input type="file" name="file"><br>
    <input type="submit" value="上传">
</form>

创建Controller

java 复制代码
@RequestMapping("uploadFile")
    public String uploadFile(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request){

        //文件上传的位置   服务器路径
    String path = request.getSession().getServletContext().getRealPath("resources/upload");
    //System.out.println(path);
    if(!file.isEmpty()){
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path, file.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return "index";
    }

配置文件问题

静态资源问题

方式一:修改前端控制器 不推荐 web.xml

XML 复制代码
<servlet>
  <servlet-name>SpringMVC</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>SpringMVC</servlet-name>
  <url-pattern>*.do</url-pattern>
</servlet-mapping>

方式二:追加默认放行的资源 不推荐 (有多少写多少)

XML 复制代码
<servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.js</url-pattern>
</servlet-mapping>

方式三:修改SpringMVC-servlet.xml文件

追加mvc的命名空间

XML 复制代码
xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd
                        //mvc驱动
                        //mapping:映射路径
                        //location:真实路径
                         <mvc:annotation-driven/>
    <mvc:resources mapping="/resources/**" location="/resources/"/>
XML 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/context
                        http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <context:annotation-config/>
    <context:component-scan base-package="com.hwq"></context:component-scan>

    <mvc:annotation-driven/>
    <mvc:resources mapping="/resources/**" location="/resources/"/>

<!--    视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

异常处理

局部异常

作用于当前控制器

java 复制代码
@ExceptionHandler({Exception.class})
public String excpetion(Exception a){
    System.out.println("抛出异常");
    a.printStackTrace();
    return "redirect:error.jsp";
    //return "error";
}

全局异常

作用于整个项目

XML 复制代码
<!-- 异常解析器 -->
	  <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
	  		<property name="exceptionMappings">
	  			<props>
	  				<prop key="java.lang.Exception">redirect:error.jsp</prop>
	  			</props>
	  		</property>
	  </bean>

拦截器

第一步:创建类,继承拦截器适配器类或实现拦截器接口

第二步:重写方法

java 复制代码
public class MyInterceptor implements HandlerInterceptor {
    /*
    登录拦截

    false表示拦截,不向下执行
    true表示放行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器执行了");
        //判断是否合法    登录路径   session有数据
        //request.getRequestURI().equals("/login");
        //request.getSession().getAttribute("user");

        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("拦截器执行结束了");
    }
}

第三步:配置拦截器

XML 复制代码
<!--    拦截器配置-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/*"/>
            <bean id="myInterceptor" class="com.hwq.interceptor.MyInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
相关推荐
FYKJ_2010几秒前
springboot手工蜀绣在线销售系统60947-计算机课程设计、毕业设计
java·spring boot·后端·python·mysql·spark·课程设计
Mortalbreeze2 分钟前
MySQL 基础篇(五):数据操作基础 —— CRUD
linux·服务器·数据库·mysql
vx_Biye_Design3 分钟前
springboot老年人用药智能管理系统38605-计算机课程设计、毕业设计
java·spring boot·后端·python·django·课程设计·express
QQ_21696290966 分钟前
基于C#(Asp.net)电竞陪玩信息管理系统的设计与实现
java·大数据·spring boot·微信小程序·c#·云计算·asp.net
vx_Biye_Design9 分钟前
springbootNBA数据分析系统平台42434-计算机课程设计、毕业设计
java·vue.js·spring boot·python·django·课程设计·express
Q26433650239 分钟前
【有源码】基于springboot的知识产权管理系统-知识产权咨询问答管理系统-知识产权价值评估管理系统
java·spring boot·mysql·spring·毕业设计·javaweb·课程设计
geovindu2 小时前
css: Timeline scribble
前端·css·iphone
ai小陈8 小时前
GPU服务器租用存储验收:检查点写入与磁盘吞吐实战
运维·服务器·人工智能·ai·ssh·gpu算力
leikooo9 小时前
用餐厅和盘子理解栈和堆
java·数据结构·链表·rust
Ivanqhz10 小时前
激活函数在 Transformer 中的作用及各种变体简述
java·linux·数据库·人工智能·深度学习