springmvc笔记总结

springmvc学习笔记总结

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

一、第一个springmvc程序

1.1在pow文件中引入依赖(spring)

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>5.2.9.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.2.9.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
  <version>5.2.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-catalina -->
<dependency>
  <groupId>org.apache.tomcat</groupId>
  <artifactId>tomcat-catalina</artifactId>
  <version>9.0.40</version>
</dependency>

1.2创建springmvc的配置文件xml
1.2.1注册处理器类
1.2.2创建静态资源访问
1.2.3注册视图解析器

org.springframework.web.servlet.view.InternalResourceViewResolver
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--注册处理器
        bean的id应该以“/”开头
    -->
    <bean id="/some" class="com.yyf.handler.SomeHandler"/>
<!--    静态资源访问-->
    <mvc:default-servlet-handler/>

    <!--注册视图解析器
            功能:将逻辑视图转换为物理视图
            逻辑视图:welcome
            物理视图:/WEB-INF/welcome.jsp
            其实,这个视图解析器就是做了一个机械的字符串拼接
        -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

1.3创建jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
//href中写入在springmvc配置文件中注册的处理器类
<a href="some">请求</a>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
欢迎学习SpringMVC!
<br>
${message}
</body>
</html

1.4创建处理器类
1.4.1处理器类要实现Controller接口
1.4.2除了实现Controller接口还可以用@Controller注解
1.4.3处理器类的返回类型可以为ModelAndView、String、void、Object
其中前三种类型返回的都是视图,Object需要使用ajax请求

package com.yyf.handler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 定义处理器类
public class SomeHandler implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mv = new ModelAndView();
        //设置响应中的模型
        //相当于request.setAttribute("message","Hello SpringMVC!")
        mv.addObject("message","Hello SpringMVC!");
        //设置响应视图
        mv.setViewName("welcome");
        return mv;
    }
}
二、使用注解实现

2.1.1zpringmvc配置文件
使用注解需要添加一个注解驱动

<mvc:annotation-driven/>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--注册组件扫描器-->
    <context:component-scan base-package="com.yyf.handler"/>

    <!--mvc注解驱动-->
    <mvc:annotation-driven/>

    <!--静态资源访问问题-->
    <mvc:default-servlet-handler/>

    <!--注册视图解析器
            功能:将逻辑视图转换为物理视图
            逻辑视图:welcome
            物理视图:/WEB-INF/welcome.jsp
            其实,这个视图解析器就是做了一个机械的字符串拼接
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

2.2.2jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<a href="some">请求</a>
<%--
    ${pageContext.request.contextPath}获取项目路径
--%>
<form action="${pageContext.request.contextPath}/some/fourth" method="post">
    <input type="submit" value="请求">
</form>
</body>
</html>

2.2.3处理器类

package com.yyf.handler;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// 定义处理器类
@Controller
@RequestMapping("/some")    //命名空间
public class SomeHandler {

    @RequestMapping({"/first","/first2"})
    public ModelAndView doFirst(Model model) throws Exception {
        ModelAndView mv = new ModelAndView();
        //设置响应中的模型
        //相当于request.setAttribute("message","Hello SpringMVC!")
        //model.addAttribute("message","Hello SpringMVC!");
        mv.addObject("message","Hello SpringMVC!");
        //设置响应视图
        mv.setViewName("welcome");
        return mv;
    }
    @RequestMapping("/second")
    public ModelAndView doSecond(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mv = new ModelAndView();
        //设置响应中的模型
        mv.addObject("message","执行doSecond方法!");
        //设置响应视图
        mv.setViewName("welcome");
        return mv;
    }
    //@RequestMapping("/third*")  //要求请求路径中的资源名称以third开头
    //@RequestMapping("/*third")  //要求请求路径中的资源名称以third结尾
    //@RequestMapping("/*/third")  //要求命名空间路径和请求路径的资源名称之间必须有一级路径
    @RequestMapping("/**/third")  //要求命名空间路径和请求路径的资源名称之间可以有多级路径
    public ModelAndView doThird(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mv = new ModelAndView();
        //设置响应中的模型
        mv.addObject("message","执行doThird方法!");
        //设置响应视图
        mv.setViewName("welcome");
        return mv;
    }

    // method限制请求方式为post
    @RequestMapping(value = "fourth",method = RequestMethod.POST)
    public ModelAndView doFourth(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mv = new ModelAndView();
        //设置响应中的模型
        mv.addObject("message","执行doFourth方法!");
        //设置响应视图
        mv.setViewName("welcome");
        return mv;
    }
    //@RequestMapping(value = "/fifth",params = "name")   //要求请求中必须携带name参数
    //@RequestMapping(value = "/fifth",params = {"name","age"})   //要求请求中必须携带name和age参数
    //@RequestMapping(value = "/fifth",params = {"!name","age"})   //要求请求中必须不能携带name参数,必须携带age参数
    @RequestMapping(value = "/fifth",params = {"name=zs","age"})   //要求请求中必须携带name和age参数,并且name的属性值必须为zs
    public ModelAndView doFifth(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mv = new ModelAndView();
        //设置响应中的模型
        mv.addObject("message","执行doFifth方法!");
        //设置响应视图
        mv.setViewName("welcome");
        return mv;
    }
}
三、处理器接收的返回的参数类型

3.1.1springmvc配置文件xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--注册组件扫描器-->
    <context:component-scan base-package="com.yyf.handler"/>

    <!--mvc注解驱动-->
    <mvc:annotation-driven/>

    <!--静态资源访问问题-->
    <mvc:default-servlet-handler/>

    <!--注册视图解析器
            功能:将逻辑视图转换为物理视图
            逻辑视图:welcome
            物理视图:/WEB-INF/welcome.jsp
            其实,这个视图解析器就是做了一个机械的字符串拼接
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

3.1.2jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>

<%--
    前台路径:
    以“/”开头的路径参照路径是:当前web服务器的根
    不以“/”开头的路径参照路径是:当前请求路径的资源路径

    后台路径:
    以“/”开头的路径参照路径是:当前web项目的根
    不以“/”开头的路径参照路径是:当前请求路径的资源路径
    特例:sendRedirect()方法时参照路径是:当前web服务器的根
--%>

    <a href="${pageContext.request.contextPath}/some/first">请求1</a>

    <form action="${pageContext.request.contextPath}/some/third" method="post">
        姓名:<input type="text" name="name"><br>
        年龄:<input type="text" name="age"><br>
        <input type="submit" value="提交">
    </form>

</body>
</html>

3.1.3实体类

package com.yyf.beans;
public class Student {
    private String name;
    private int age;

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

3.1.4控制器类

package com.yyf.handler;

import com.yyf.beans.Student;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

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

// 定义处理器类
@Controller
@RequestMapping("/some")    //命名空间
public class SomeHandler {

    @RequestMapping("/first")
    public ModelAndView doFirst(Map<String,Object> map) throws Exception {
        //相当于request.setAttribute("message","处理器方法参数为Map")
        map.put("message","处理器方法参数为Map");
        ModelAndView mv = new ModelAndView();
        mv.setViewName("welcome");
        return mv;
    }
    //处理器方法参数名称必须与请求参数名称相同
    @RequestMapping("/second")
    public ModelAndView doSecond(String name,int age,Map<String,Object> map) throws Exception {
        System.out.println(name);
        System.out.println(age);
        map.put("name",name);
        map.put("age",age);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("welcome");
        return mv;
    }
    // @RequestParam用于参数校正
    @RequestMapping("/third")
    public ModelAndView doThird(@RequestParam("name") String sname, @RequestParam("age") int sage, Map<String,Object> map) throws Exception {
        //相当于request.setAttribute("message","处理器方法参数为Map")
        System.out.println(sname);
        System.out.println(sage);
        map.put("name",sname);
        map.put("age",sage);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("welcome");
        return mv;
    }
    // Map可以整体接收参数,但不会自动放到request域,接收到的值都是String,不会自动进行类型的转换
    @RequestMapping("/fourth")
    public ModelAndView doFourth(@RequestParam Map<String,Object> map,Model model) throws Exception {
        String name = (String) map.get("name");
        String age = (String) map.get("age");
        model.addAttribute("name",name);
        model.addAttribute("age",age);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("welcome");
        return mv;
    }
    // 使用自定义类型对象对请求参数进行整体接收,自定义类型的对象属性名和请求参数名称一致
    // 系统会自动将对象放入request域
    // 使用请求参数逐个接收,系统不会将请求参数自动放入request域
    @RequestMapping("/fifth")
    public ModelAndView doFifth(Student student) throws Exception {
        System.out.println(student);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("welcome");
        return mv;
    }
}

3.2、控制类返回的String类型

3.2.1配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--注册组件扫描器-->
    <context:component-scan base-package="com.yyf.handler"/>

    <!--mvc注解驱动-->
    <mvc:annotation-driven/>

    <!--静态资源访问问题-->
    <mvc:default-servlet-handler/>

    <!--注册视图解析器
            功能:将逻辑视图转换为物理视图
            逻辑视图:welcome
            物理视图:/WEB-INF/welcome.jsp
            其实,这个视图解析器就是做了一个机械的字符串拼接
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

3.2.2jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>

<%--
    前台路径:
    以“/”开头的路径参照路径是:当前web服务器的根
    不以“/”开头的路径参照路径是:当前请求路径的资源路径

    后台路径:
    以“/”开头的路径参照路径是:当前web项目的根
    不以“/”开头的路径参照路径是:当前请求路径的资源路径
    特例:sendRedirect()方法时参照路径是:当前web服务器的根
--%>

    <a href="${pageContext.request.contextPath}/some/first">请求1</a><br>
    <a href="${pageContext.request.contextPath}/some/second">请求2</a><br>
    <a href="${pageContext.request.contextPath}/some/third">请求3</a>
</body>
</html>

3.2.3控制器类

package com.yyf.handler;

import com.yyf.beans.Student;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

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

// 定义处理器类
@Controller
@RequestMapping("/some")    //命名空间
public class SomeHandler {

    @RequestMapping("/first")
    public String doFirst() throws Exception {
        //返回物理视图
        return "forward:/WEB-INF/welcome.jsp";
    }
    @RequestMapping("/second")
    public String doSecond() throws Exception {
        // 返回逻辑视图
        return "welcome";
    }
    @RequestMapping("/third")
    public String doThird() throws Exception {
        //重定向
        return "redirect:http://www.baidu.com";
    }
}
3.3、控制类返回void类型
注:后台路径使用sendRedirect()方法时参照路径为:当前服务器的根
// 定义处理器类
@Controller
@RequestMapping("/some")    //命名空间
public class SomeHandler {

    @RequestMapping("/first")
    public void doFirst(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //请求转发
        request.getRequestDispatcher("WEB-INF/welcome.jsp").forward(request,response);
    }

    @RequestMapping("/third")
    public void doThird() throws Exception {
        //请求重定向
        response.sendRedirect(request.getContextPath()+"welcome.jsp");
    }
}
3.4、控制类返回Object类型(ajax请求)

3.4.1引入依赖,配置主配置文件xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--注册组件扫描器-->
    <context:component-scan base-package="com.yyf.handler"/>

    <!--mvc注解驱动-->
    <mvc:annotation-driven/>

    <!--静态资源访问问题-->
    <mvc:default-servlet-handler/>

    <!--注册视图解析器
            功能:将逻辑视图转换为物理视图
            逻辑视图:welcome
            物理视图:/WEB-INF/welcome.jsp
            其实,这个视图解析器就是做了一个机械的字符串拼接
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

3.4.2请求页面jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
   <head>
       <title>ajax</title>
       //使用ajax请求需要引入jquery框架,1:直接引用链接2:下载引入
<%--       <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>--%>
       <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js"></script>
       <script type="text/javascript">
           $(function () {
               $("button").click(function () {
                 $.ajax({
                     type:"POST",
                     url:"${pageContext.request.contextPath}/some/first",
                     data:{
                         name:"张三",
                         age:"18"
                     },
                     success:function (data) {
                         alert(data);
                     }
                 });
               });
           });
       </script>
   </head>
<body>

<button>ajax请求</button>

</body>
</html>

3.4.3控制类

package com.yyf.handler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
// 定义处理器类
@Controller
@RequestMapping("/some")    //命名空间
public class SomeHandler {
**//当返回字符串汉字时,需要配置produces参数**
    @RequestMapping(value = "/first",produces = {"text/html;charset=UTF-8","application/json;"})
    @ResponseBody//表示当前参数值通过响应体响应
    public String doFirst(String name,String age) throws Exception {
        System.out.println(name+":"+age);
        //返回物理视图
        return name;
    }
}

3.4.3使用json返回double类型数据
在这里插入图片描述
引入json和java的转换器jackson依赖

 <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.12.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.12.1</version>
    </dependency>
      <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
          <version>2.12.1</version>
      </dependency>

请求页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
   <head>
       <title>ajax</title>
<%--       <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>--%>
       <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js"></script>
       <script type="text/javascript">
           $(function () {
               $("button").click(function () {
                 $.ajax({
                     type:"POST",
                     url:"${pageContext.request.contextPath}/some/second",
                     data:{
                         name:"张三",
                         age:"18"
                     },
                     success:function (data) {
                         alert(data);
                     }
                 });
               });
           });
       </script>
   </head>
<body>

<button>ajax请求</button>

</body>
</html>

控制类

 @RequestMapping(value = "/second")
    @ResponseBody//表示当前参数值通过响应体响应
    public Double dosecond(String name,String age) throws Exception {
        System.out.println(name+":"+age);
        //返回物理视图
        return 123.321;
    }

3.4.4使用json返回自定义类型数据
请求页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
   <head>
       <title>ajax</title>
<%--       <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>--%>
       <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js"></script>
       <script type="text/javascript">
           $(function () {
               $("button").click(function () {
                 $.ajax({
                     type:"POST",
                     url:"${pageContext.request.contextPath}/some/third",
                     data:{
                         name:"张三",
                         age:"18"
                     },
                     success:function (data) {
                         alert(data.name+":"+data.age);
                     }
                 });
               });
           });
       </script>
   </head>
<body>

<button>ajax请求</button>

</body>
</html>

控制类

 @RequestMapping(value = "/third")
    @ResponseBody//表示当前参数值通过响应体响应
    public Student dothird(Student student) throws Exception {
        System.out.println(student);
        Student student1 = new Student("李四",20);
        //返回物理视图
        return student1;
    }
返回自定义类型数据时不需要在RequestMapping中配置produces参数
因为调用的是json的转换器,返回String调用的是springmvc的转换器
四、异常处理器

4.1请求页面

<form action="${pageContext.request.contextPath}/some/first" method="post">
    姓名:<input type="text" name="name"><br>
    年龄:<input type="text" name="age"><br>
    <input type="submit" value="提交">
</form>

4.2主配置文件


```java
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--注册组件扫描器-->
    <context:component-scan base-package="com.yyf.handler"/>

    <!--mvc注解驱动-->
    <mvc:annotation-driven/>

    <!--静态资源访问问题-->
    <mvc:default-servlet-handler/>
    <!--   注册异常解析器-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="defaultErrorView" value="/error/error.jsp"></property>
        <property name="exceptionAttribute" value="ex"></property>
        <property name="exceptionMappings">
            <props>
                <prop key="NameException">/error/NameError.jsp</prop>
                <prop key="AgeException">/error/AgeError.jsp</prop>
            </props>
        </property>
    </bean>

</beans>

4.3控制类

package com.yyf.handler;
import com.yyf.beans.Student;
import com.yyf.exception.AgeException;
import com.yyf.exception.NameException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

// 定义处理器类
@Controller
@RequestMapping("/some")    //命名空间
public class SomeHandler {

    @RequestMapping(value = "/first",produces = {"text/html;charset=UTF-8","application/json;"})
    @ResponseBody//表示当前参数值通过响应体响应
    public String doFirst(String name,int age) throws Exception {
//        int a = 1/0;调用默认错误页面error.jsp
        if(!"aynu".equals(name)){
            throw new NameException("姓名错误");
        }
        if(age<0||age>150){
            throw new AgeException("年龄有误");
        }
        return "forword:/WEB-INF/welcome.jsp";
    }
}

4.4错误页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
服务器内部错误,请稍候访问!${ex}
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
姓名有误!
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
年龄有误!
</body>
</html>
五、文件上传和下载

5.0springmvc主配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	<!-- 定义组件扫描器,指定需要扫描的包 -->
	<context:component-scan base-package="com.itheima.controller" />
	<!--配置注解驱动  -->
	<mvc:annotation-driven />
	<!-- 定义视图解析器 -->
	<bean id="viewResolver" class=
    "org.springframework.web.servlet.view.InternalResourceViewResolver">
	     <!-- 设置前缀 -->
	     <property name="prefix" value="/WEB-INF/jsp/" />
	     <!-- 设置后缀 -->
	     <property name="suffix" value=".jsp" />
	</bean>
	<!-- 配置文件上传解析器 MultipartResolver -->
	<bean id="multipartResolver" class=
   "org.springframework.web.multipart.commons.CommonsMultipartResolver">
          <!-- 设置请求编码格式-->
          <property name="defaultEncoding" value="UTF-8" />
	</bean>
</beans> 

5.1文件上传的jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
<script>
// 判断是否填写上传人并已选择上传文件
function check(){
    var name = document.getElementById("name").value;
    var file = document.getElementById("file").value;
    if(name==""){
        alert("填写上传人");
        return false;
    }
    if(file.length==0||file==""){
        alert("请选择上传文件");
        return false;
    }
    return true;
}
</script>
</head>
<body>
    <form action="${pageContext.request.contextPath }/fileUpload" method="post" enctype="multipart/form-data" onsubmit="return check()">
	上传人:<input id="name" type="text" name="name" /><br />
	请选择文件:<input id="file" type="file" name="uploadfile" 
                                                   multiple="multiple" /><br />
		       <input type="submit" value="上传" />
	</form>
</body>
</html>

5.2文件上传的控制类

/**
	 * 执行文件上传
	 */
	@RequestMapping("/fileUpload")
	public String handleFormUpload(@RequestParam("name") String name,
								   @RequestParam("uploadfile") List<MultipartFile> uploadfile, HttpServletRequest request) {
		// 判断所上传文件是否存在
		if (!uploadfile.isEmpty() && uploadfile.size() > 0) {
			//循环输出上传的文件
			for (MultipartFile file : uploadfile) {
				// 获取上传文件的原始名称
				String originalFilename = file.getOriginalFilename();
				// 设置上传文件的保存地址目录
				String dirPath = request.getServletContext().getRealPath("/upload/");
				File filePath = new File(dirPath);
				// 如果保存文件的地址不存在,就先创建目录
				if (!filePath.exists()) {
					filePath.mkdirs();
				}
				// 使用UUID重新命名上传的文件名称(上传人_uuid_原始文件名称)
				String newFilename = name+ "_"+UUID.randomUUID() + 
                                                   "_"+originalFilename;
				try {
					// 使用MultipartFile接口的方法完成文件上传到指定位置
					file.transferTo(new File(dirPath + newFilename));
				} catch (Exception e) {
					e.printStackTrace();
                       return"error";
				}
			}
			// 跳转到成功页面
			return "success";
		}else{
			return"error";
		}
	}

5.3文件下载的jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
<%@page import="java.net.URLEncoder"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
     "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>下载页面</title>
</head>
<body>
	<%-- <a href="${pageContext.request.contextPath }/download?filename=1.jpg">
    	文件下载 
	</a> --%>
	
	<a href="${pageContext.request.contextPath }/download?filename=<%=URLEncoder.encode("壁纸.jpg", "UTF-8")%>">
		中文名称文件下载 
	</a>
</body>
</html>

5.4文件下载的控制类

@RequestMapping("/download")
	public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,
	                                           String filename) throws Exception{
	    // 指定要下载的文件所在路径
	    String path = request.getServletContext().getRealPath("/upload/");
	    // 创建该文件对象
	    File file = new File(path+File.separator+filename);
	    // 对文件名编码,防止中文文件乱码
	    filename = this.getFilename(request, filename);
	    // 设置响应头
	    HttpHeaders headers = new HttpHeaders();
	    // 通知浏览器以下载的方式打开文件
	    headers.setContentDispositionFormData("attachment", filename);
	    // 定义以流的形式下载返回文件数据
	    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	    // 使用Sring MVC框架的ResponseEntity对象封装返回下载数据
	   return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
	                                           headers,HttpStatus.OK);
	}
	/**
	 * 根据浏览器的不同进行编码设置,返回编码后的文件名
	 */
	public String getFilename(HttpServletRequest request,
	                                            String filename) throws Exception { 
	    // IE不同版本User-Agent中出现的关键词
	    String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};  
	    // 获取请求头代理信息
	    String userAgent = request.getHeader("User-Agent");  
	    for (String keyWord : IEBrowserKeyWords) { 
	         if (userAgent.contains(keyWord)) { 
	              //IE内核浏览器,统一为UTF-8编码显示
	              return URLEncoder.encode(filename, "UTF-8");
	         }
	    }  
	    //火狐等其它浏览器统一为ISO-8859-1编码显示
	    return new String(filename.getBytes("UTF-8"), "ISO-8859-1");  
	}  
六、拦截器

6.1spingmvc主配置文件

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/login/*"/>
            <bean class="com.wcc.page.LoginInterceptor">
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>

6.2拦截器类的实现

package com.wcc.page;

import com.wcc.beans.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         String url = request.getRequestURI();
         if(url.indexOf("/index")>=0){
             return true;
         }
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(user!=null){
            return true;
        }
        request.setAttribute("msg","你还没有登录,请先登录");
        request.getRequestDispatcher("/index.jsp").forward(request,response);
        return false;
    }

    @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 {

    }
}
七、SSM整合

7.1引入spring、springmvc、mybatis的依赖jar包

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.9.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>5.2.9.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.2.9.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>5.2.9.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jcl</artifactId>
      <version>5.2.9.RELEASE</version>
    </dependency>
       <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.2.9.RELEASE</version>
    </dependency>
  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.2.9.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.9.RELEASE</version>
    </dependency>
      <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>5.2.9.RELEASE</version>
    </dependency>
     <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.9.RELEASE</version>
    </dependency>
        <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.2.9.RELEASE</version>
    </dependency>
     <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.2.9.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
<dependency>
    <groupId>aopalliance</groupId>
    <artifactId>aopalliance</artifactId>
    <version>1.0</version>
</dependency>
     <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.13.2</version>
    </dependency>

7.2配置文件
spring主配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--加载jdbc属性文件-->
    <context:property-placeholder location="jdbc.properties"/>
    <!--注册DataSource数据源:Spring内置的-->
    <bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--注册sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <!--mybatis的主配置文件加载-->
        <property name="configLocation" value="mybatis.xml"/>
    </bean>

   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
       <property name="basePackage" value="com.wcc.dao"/>
   </bean>

    <!--注册Service层对象-->
    <bean id="studentService" class="com.wcc.service.IStudentServiceImpl">
        <property name="studentDao" ref="IStudentDao"/>
    </bean>
</beans>

springmvc主配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--注册组件扫描器-->
    <context:component-scan base-package="com.wcc.handler"/>
    <!--mvc注解驱动-->
    <mvc:annotation-driven/>
    <!--静态资源访问问题-->
    <mvc:default-servlet-handler/>
    <!--注册视图解析器
            功能:将逻辑视图转换为物理视图
            逻辑视图:welcome
            物理视图:/WEB-INF/welcome.jsp
            其实,这个视图解析器就是做了一个机械的字符串拼接
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp1/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

mybatis文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!--给实体类定义别名-->
    <typeAliases>
        <package name="com.wcc.beans"/>
    </typeAliases>
 <mappers>
        <package name="com.wcc.dao"/>
  </mappers>
</configuration>

jdbc.porperties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///dorm
jdbc.username=root
jdbc.password=123456

log2j文件

<?xml version="1.0" encoding="UTF-8"?>

<configuration status="OFF">
	<appenders>
		<Console name="myConsole" target="SYSTEM_OUT">
			<PatternLayout pattern="[%-5p] %m%n" />
		</Console>
	</appenders>
	
	<loggers>
		<logger name="com.wcc.dao" level="trace" additivity="false">
			<appender-ref ref="myConsole" />
		</logger>
		<!--<root level="debug">
			<appender-ref ref="myConsole" />
		</root>-->
	</loggers>
	
</configuration>

完结…

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值