springmvc

本文详细介绍了SpringMVC的使用,包括创建第一个SpringMVC项目、RequestMapper的配置、请求参数的多种获取方式、返回值处理、域对象(request、session、servletContext)的应用、文件上传与下载、异常处理以及JSON数据交互。内容全面,适合初学者进阶。
摘要由CSDN通过智能技术生成

1、第一个springmvc

在这里插入图片描述

web

@Controller
public class UserController {
    @RequestMapping("/test01.action")
    public ModelAndView test01(){
        ModelAndView mav = new ModelAndView();
        mav.addObject("k1","v1");
        mav.addObject("k2","v2");
        mav.setViewName("test01");
        return mav;
    }

}

springmvc.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: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/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">
    <!--配置包扫描-->
    <context:component-scan base-package="cn.tedu"/>
    <!--配置注解方式DI-->
    <context:annotation-config/>
    <!--注解方式mvc开关-->
    <mvc:annotation-driven/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

test

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>test01.jsp</title>
</head>
<body>
    this is test01.jsp<br/>
    k1:<%=request.getAttribute("k1")%><br/>
    k2:<%=request.getAttribute("k2")%><br/>
</body>
</html>

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">
    <!--配置前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--指定springmvc配置位置-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

2、RequestMapper的使用

web

package cn.tedu.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@RequestMapping("/my01")
@Controller
public class MyController01 {
    /**
     * @RequestMapping的使用 - headers
     *  String[] headers() default {};
     *  用来限定必须有符合要求的请求头才可以访问
     *      格式1:只指定名称,要求必须具有该名称的请求头
     *      格式2:以"!名称"的方式指定必须不包含指定名称的请求头
     *      格式3:以"名称=值"或"名称!=值"的方式指定必须具有某个请求头,且值必须等于或不等于给定值
     *      http://localhost/SpringMVCDay01_02_Details01_war_exploded/my01/test05.action
     */
    @RequestMapping(value="/test04.action",headers = {"Host","!aaa","bbb=123","ccc!=123"})
    public void test05(){
        System.out.println("my01..test05..");
    }

    /**
     * @RequestMapping的使用 - params
     *  String[] params() default {};
     *  用来限定必须有符合要求的请求参数才可以访问
     *      格式1:只指定名称,要求必须具有该名称的请求参数
     *      格式2:以"!名称"的方式指定必须不包含指定名称的请求参数
     *      格式3:以"名称=值"或"名称!=值"的方式指定必须具有某个请求参数,且值必须等于或不等于给定值
     *      http://localhost/SpringMVCDay01_02_Details01_war_exploded/my01/test04.action
     *      http://localhost/SpringMVCDay01_02_Details01_war_exploded/my01/test04.action?uname=zs
     *      http://localhost/SpringMVCDay01_02_Details01_war_exploded/my01/test04.action?uname=zs&uage=18
     *      http://localhost/SpringMVCDay01_02_Details01_war_exploded/my01/test04.action?uname=zs&uage=18&country=cn
     *      http://localhost/SpringMVCDay01_02_Details01_war_exploded/my01/test04.action?uname=zs&country=cn
     *      http://localhost/SpringMVCDay01_02_Details01_war_exploded/my01/test04.action?uname=zs&country=cn&city=bj
     */
    @RequestMapping(value="/test04.action",params={"uname","!uage","country=cn","city!=bj"} )
    public void test04(){
        System.out.println("my01..test04..");
    }

    /**
     * @RequestMapping的使用 - method
     *  RequestMethod[] method() default {};
     *  用来限定只允许哪些请求方式的请求访问此处理器方法,默认任意请求方式都可以访问
     *  http://localhost/SpringMVCDay01_02_Details01_war_exploded/my01/test03.action
     */
    @RequestMapping(value="/test03.action",method={RequestMethod.GET,RequestMethod.POST} )
    public void test03(){
        System.out.println("my01..test03..");
    }

    /**
     * @RequestMapping的使用 - value属性
     *  @AliasFor("value") String[] path() default {};
     *  可以为当前处理器方法增加访问路径,可以配置多个,也可使用*号通配符进行配合
     *  http://localhost/SpringMVCDay01_02_Details01_war_exploded/my01/test02.action
     *  http://localhost/SpringMVCDay01_02_Details01_war_exploded/my01/test02x.action
     *  http://localhost/SpringMVCDay01_02_Details01_war_exploded/my01/test02zasdf.action
     */
    @RequestMapping({"/test02.action","/test02x.action","/test02z*.action"})
    public void test02(){
        System.out.println("my01..test02..");
    }

    /**
     * @RequestMapping的使用 - 基本使用
     *  可以用方法在 也可以用在类上上
     *      用在方法上是将当前方法变为处理器方法,并绑定到指定路径
     *      用在类上,则是为当前处理器类中所有处理器方法的访问路径增加前缀
     *      http://localhost/SpringMVCDay01_02_Details01_war_exploded/my01/test01.action
     */
    @RequestMapping("/test01.action")
    public void test01(){
        System.out.println("my01..test01..");
    }
}

springmvc.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: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/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">
    <!--配置包扫描-->
    <context:component-scan base-package="cn.tedu"/>
    <!--配置注解方式DI-->
    <context:annotation-config/>
    <!--配置注解方式mvc-->
    <mvc:annotation-driven/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

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">
    <!--配置前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--指定配置文件位置-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

3、控制器可以接受的请求参数

在这里插入图片描述

springmvc.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: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/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">
    <!--配置包扫描-->
    <context:component-scan base-package="cn.tedu"/>
    <!--配置注解方式DI-->
    <context:annotation-config/>
    <!--配置注解方式mvc-->
    <mvc:annotation-driven/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

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">
    <!--配置请求参数乱码过滤器-->
    <filter>
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--配置前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--配置配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

web开发相关对象

web

package cn.tedu.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RequestMapping("/my01")
@Controller
public class MyController01 {

    /**
     * 控制器方法可以接受的参数1 - web开发相关对象
     *  HttpServletRequest 请求对象
     *  HttpServletResponse 响应对象
     *  HttpSession 会话对象
     *  WebRequest 整合了request和session对象方法的对象
     */
    @RequestMapping("/test01.action")
    public void test01(HttpServletRequest request, HttpServletResponse response, HttpSession session, WebRequest wreq) throws IOException {
//        System.out.println(request.getRequestURL());
//        response.getWriter().write("hello springmvc~");
//        System.out.println(session.getId());

//        System.out.println(wreq.getContextPath());
//        System.out.println(wreq.getSessionId());
    }
}

web开发相关流对象

package cn.tedu.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

@RequestMapping("/my02")
@Controller
public class MyController02 {
    /**
     * 控制器方法可以接受的参数2:web开发相关的流对象
     * Reader 等同于request.getReader()
     * InputStream 等同于request.getInputStream()
     * Writer 等同于request.getWriter()
     * OutputStream 等同于request.getOutputStream()
     *
     * 注意,同一个request或response上不能同时获取字节流和字符流,因此在控制器方法中配置时也要注意此问题
     */
    @RequestMapping("/test02.action")
    public void test02(Writer writer) throws IOException {
        writer.write("hellow springmvc!");
    }
    @RequestMapping("/test01.action")
    public void test01(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        ServletInputStream in = request.getInputStream();
//        BufferedReader reader = request.getReader();
//        ServletOutputStream out = response.getOutputStream();
        PrintWriter writer = response.getWriter();
        writer.write("hello Java!");
    }
}

数据模型对象

package cn.tedu.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Controller
@RequestMapping("/my03")
public class MyController03 {

    /**
     * 控制器方法可以接受的参数3:数据模型对象
     *  Model 模型对象
     *  Map 用于存储模型数据的Map
     *  ModelMap 是Model和Map的合体,同时包含了两者的方法
     */
    @RequestMapping("/test04.action")
    public String test04(ModelMap mm){
        mm.put("k1","v1");
        mm.put("k2","v2");
        return "my03test04";
    }
    @RequestMapping("/test03.action")
    public String test03(Map map){
        map.put("k1","v1");
        map.put("k2","v2");
        return "my03test03";
    }
    @RequestMapping("/test02.action")
    public String test02(Model model){
        model.addAttribute("k1","v1");
        model.addAttribute("k2","v2");
        return "my03test02";
    }
    @RequestMapping("/test01.action")
    public ModelAndView test01(){
        ModelAndView mav = new ModelAndView();
        mav.addObject("k1","v1");
        mav.addObject("k2","v2");
        mav.setViewName("my03test01");
        return mav;
    }
}

jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>my03test01.jsp</title>
</head>
<body>
    this is my03test01.jsp<br/>
    <%=request.getAttribute("k1")%><br/>
    <%=request.getAttribute("k2")%><br/>
</body>
</html>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>my03test02.jsp</title>
</head>
<body>
    this is my03test02.jsp<br/>
    <%=request.getAttribute("k1")%><br/>
    <%=request.getAttribute("k2")%><br/>
</body>
</html>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>my03test03.jsp</title>
</head>
<body>
    this is my03test03.jsp<br/>
    <%=request.getAttribute("k1")%><br/>
    <%=request.getAttribute("k2")%><br/>
</body>
</html>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>my03test04.jsp</title>
</head>
<body>
    this is my03test04.jsp<br/>
    <%=request.getAttribute("k1")%><br/>
    <%=request.getAttribute("k2")%><br/>
</body>
</html>

4、获取请求参数

请求参数获取1-4 &解决乱码

package cn.tedu.web;

import cn.tedu.domain.User;
import cn.tedu.domain.User2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@RequestMapping("/my04")
@Controller
public class MyController04 {

    /**
     * 控制器方法可以接受的参数4:请求参数获取
     *  中文乱码的处理
     *      springmvc中提供了请求参数乱码解决过滤器,通过配置该过滤器可以解决请求参数的乱码问题
     *     <!--配置请求参数乱码过滤器-->
     *     <filter>
     *         <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
     *         <url-pattern>/*</url-pattern>
     *     </filter-mapping>
     *
     *      http://localhost/SpringMVCDay01_03_Details02_Parmas_war_exploded/my04test09.jsp
     */
    @RequestMapping("/test09.action")
    public void test09(String uname, String uaddr) {
        System.out.println(uname+"~"+uaddr);
    }

    /**
     * 控制器方法可以接受的参数4:请求参数获取
     *  封装请求参数到bean - 复杂对象处理:
     *      http://localhost/SpringMVCDay01_03_Details02_Parmas_war_exploded/my04/test08.action?uname=zs&uage=18&uaddr=bj&dog.name=wc&dog.age=3
     */
    @RequestMapping("/test08.action")
    public void test08(User2 user2){
        System.out.println(user2);
    }

    /**
     * 控制器方法可以接受的参数4:请求参数获取
     *  封装请求参数到bean:
     *      可以直接在方法参数中使用对象接受请求参数信息
     *      http://localhost/SpringMVCDay01_03_Details02_Parmas_war_exploded/my04/test06.action?uname=zs&uage=18&uaddr=bj
     *      http://localhost/SpringMVCDay01_03_Details02_Parmas_war_exploded/my04/test07.action?uname=zs&uage=18&uaddr=bj
     */
    @RequestMapping("/test07.action")
    public void test07(User user){
        System.out.println(user);
    }
    @RequestMapping("/test06.action")
    public void test06(HttpServletRequest request){
        String uname = request.getParameter("uname");
        int uage = Integer.parseInt(request.getParameter("uage"));
        String uaddr = request.getParameter("uaddr");
        User user = new User();
        user.setUname(uname);
        user.setUage(uage);
        user.setUaddr(uaddr);
        System.out.println(user);
    }

    /**
     * 控制器方法可以接受的参数4:请求参数获取
     *  多个同名请求参数的处理:
     *      用字符串获取,得到的是所有值用逗号拼接的结果
     *      用字符串数组获取,得到的时所有值组成的数组
     *  http://localhost/SpringMVCDay01_03_Details02_Parmas_war_exploded/my04/test04.action?uname=zs&like=zq&like=lq&like=ppq
     *  http://localhost/SpringMVCDay01_03_Details02_Parmas_war_exploded/my04/test05.action?uname=zs&like=zq&like=lq&like=ppq
     */
    @RequestMapping("/test05.action")
    public void test05(String uname,String [] like){
        System.out.println(uname+"~"+ Arrays.asList(like));
    }
    @RequestMapping("/test04.action")
    public void test04(String uname,String like){
        System.out.println(uname+"~"+like);
    }

    /**
     * 控制器方法可以接受的参数4:请求参数获取
     *  手动映射获取请求参数: 在请求参数名和方法参数不一致时,可以通过手动映射获取请求参数
     *  http://localhost/SpringMVCDay01_03_Details02_Parmas_war_exploded/my04/test03.action?uname=zs&uage=18&uaddr=bj
     */
    @RequestMapping("/test03.action")
    public void test03(@RequestParam("uname") String name, @RequestParam("uage") int age, @RequestParam("uaddr") String addr){
        System.out.println(name+"~"+age+"~"+addr);
    }

    /**
     * 控制器方法可以接受的参数4:请求参数获取
     *  直接获取请求参数:可以直接在控制器方法中接受请求参数
     *  http://localhost/SpringMVCDay01_03_Details02_Parmas_war_exploded/my04/test02.action?uname=zs&uage=18&uaddr=bj
     */
    @RequestMapping("/test02.action")
    public void test02(String uname,int uage,String uaddr){
        System.out.println(uname+"~"+uage+"~"+uaddr);
    }

    /**
     * 控制器方法可以接受的参数4:请求参数获取
     *  传统方式获取: 功过request对象获取请求参数
     *  http://localhost/SpringMVCDay01_03_Details02_Parmas_war_exploded/my04/test01.action?uname=zs&uage=18&uaddr=bj
     */
    @RequestMapping("/test01.action")
    public void test01(HttpServletRequest request){
        String uname = request.getParameter("uname");
        int uage = Integer.parseInt(request.getParameter("uage"));
        String uaddr = request.getParameter("uaddr");
        System.out.println(uname+"~"+uage+"~"+uaddr);
    }
}


day02

请求参数获取5

springmvc.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: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/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">
    <!--配置包扫描-->
    <context:component-scan base-package="cn.tedu"/>
    <!--配置注解方式DI-->
    <context:annotation-config/>
    <!--配置注解方式mvc-->
    <mvc:annotation-driven/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

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">
    <!--配置前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

controller5

@RequestMapping("/my01")
@Controller
public class MyController01 {

    /**
     * 控制器方法可以接受的参数5: 域属性 - session域
     * http://localhost/SpringMVCDay02_01_Details03_Params_war_exploded/my01/test03.action
     */
    @RequestMapping("/test04.action")
    public void test04(@SessionAttribute("sk1") String sk1){
        System.out.println(sk1);
    }
    @RequestMapping("/test03.action")
    public String test03(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("sk1","sv1");
        return "forward:/my01/test04.action";
    }
    /**
     * 控制器方法可以接受的参数5: 域属性 - request域
     * http://localhost/SpringMVCDay02_01_Details03_Params_war_exploded/my01/test01.action
     */
    @RequestMapping("/test02.action")
    public void test02(@RequestAttribute("k1") String k1){
        System.out.println(k1);
    }
    @RequestMapping("/test01.action")
    public String test01(HttpServletRequest request){
        request.setAttribute("k1","v1");
        return "forward:/my01/test02.action";
    }

}

请求参数获取6

@RequestMapping("/my02")
@Controller
public class MyController02 {

    /**
     * 控制器方法可以接受的参数6: Cookie值 - SpringMVC方式
     * http://localhost/SpringMVCDay02_01_Details03_Params_war_exploded/my02/test02.action
     */
    @RequestMapping("/test02.action")
    public void test02(@CookieValue("JSESSIONID") String JSESSIONID){
        System.out.println(JSESSIONID);
    }

    /**
     * 控制器方法可以接受的参数6: Cookie值 - 传统方式
     * http://localhost/SpringMVCDay02_01_Details03_Params_war_exploded/my02/test01.action
     */
    @RequestMapping("/test01.action")
    public void test01(HttpServletRequest request) {
        Cookie[] cs = request.getCookies();
        Cookie findC = null;
        if(cs!=null){
            for(Cookie c : cs){
                if("JSESSIONID".equals(c.getName())){
                    findC = c;
                    break;
                }
            }
        }
        if(findC != null){
            System.out.println(findC.getValue());
        }
    }
}

请求参数获取7

@RequestMapping("/my03")
@Controller
public class MyController03 {
    /**
     * 控制器方法可以接受的参数7: 请求头信息 - SpringMVC方式
     * http://localhost/SpringMVCDay02_01_Details03_Params_war_exploded/my03/test02.action
     */
    @RequestMapping("/test02.action")
    public void test02(@RequestHeader("User-Agent") String ua){
        System.out.println(ua);
    }
    /**
     * 控制器方法可以接受的参数7: 请求头信息 - 传统方式
     * http://localhost/SpringMVCDay02_01_Details03_Params_war_exploded/my03/test01.action
     */
    @RequestMapping("/test01.action")
    public void test01(HttpServletRequest request){
        String ua = request.getHeader("User-Agent");
        System.out.println(ua);
    }
}

请求参数获取8

@RequestMapping("/my04")
@Controller
public class MyController04 {
    /**
     * 控制器方法可以接受的参数8: 路径参数的获取
     * http://localhost/SpringMVCDay02_01_Details03_Params_war_exploded/my04/test01/zs/18.action
     * http://localhost/SpringMVCDay02_01_Details03_Params_war_exploded/my04/test01/ls/20.action
     */
    @RequestMapping("/test01/{name}/{age}.action")
    public void test01(@PathVariable("name") String name,@PathVariable("age") int age){
        System.out.println(name+"~"+age);
    }
}

在这里插入图片描述

请求参数获取9

@RequestMapping("/my05")
@Controller
public class MyController05 {
    /**
     * 控制器方法可以接受的参数9: 请求体数据
     * http://localhost/SpringMVCDay02_01_Details03_Params_war_exploded/my05test01.jsp
     */
    @RequestMapping("/test01.action")
    public void test01(@RequestBody String str){
        System.out.println(str);
    }
}

jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>GET提交</h1><hr/>
    <form action="<%=request.getContextPath()%>/my05/test01.action" method="GET" >
        用户名:<input type="text" name="uname"/>
        地址:<input type="text" name="uaddr"/>
        <input type="submit"/>
    </form>
    <h1>POST提交</h1><hr/>
    <form action="<%=request.getContextPath()%>/my05/test01.action" method="POST" >
        用户名:<input type="text" name="uname"/>
        地址:<input type="text" name="uaddr"/>
        <input type="submit"/>
    </form>
</body>
</html>

在这里插入图片描述

5、返回值

在这里插入图片描述

springmvc.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: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/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">
    <!--配置包扫描-->
    <context:component-scan base-package="cn.tedu"/>
    <!--注解方式DI-->
    <context:annotation-config/>
    <!--注解方式MVC-->
    <mvc:annotation-driven/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

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">
    <!--配置前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

user

package cn.tedu.domain;

import java.util.Arrays;

public class User {
    private int id;
    private String name;
    private int age;
    private String [] addrs;

    public User() {
    }

    public User(int id, String name, int age, String[] addrs) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.addrs = addrs;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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;
    }

    public String[] getAddrs() {
        return addrs;
    }

    public void setAddrs(String[] addrs) {
        this.addrs = addrs;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", addrs=" + Arrays.toString(addrs) +
                '}';
    }
}

web

package cn.tedu.web;

import cn.tedu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@RequestMapping("/my01")
@Controller
public class MyController01 {

    /**
     * 处理器方法返回的返回值5 - 其他返回值
     * 返回值将会被存入Model中,键为返回值类型名首字母转小写
     * 使用默认的视图名作为视图名称来使用
     * 默认视图名称 是 当前处理器方法访问路径去后缀
     *      /my01/test08.action ---> my01/test08
     * http://localhost/SpringMVCDay02_03_Details04_ReturnType_war_exploded/my01/test08.action
     */
    @RequestMapping("/test08.action")
    public User test08(){
        User user = new User(4,"ls",22,new String[]{"bj","sh","gz"});
        return user;
    }

    /**
     * 处理器方法返回的返回值4 - 被@ResponseBody修饰的方法
     * 被@ResponseBody注解修饰的方法,返回的任何内容都会被当做响应数据直接发送给浏览器
     * 如果返回的时字符串,则直接输出,如果返回的是一个bean对象,则将bean转为json发送给浏览器
     * http://localhost/SpringMVCDay02_03_Details04_ReturnType_war_exploded/my01/test06.action
     * http://localhost/SpringMVCDay02_03_Details04_ReturnType_war_exploded/my01/test07.action
     */
    @ResponseBody
    @RequestMapping("/test07.action")
    public User test07(){
        User user = new User(3,"zs",18,new String[]{"bj","sh","gz"});
        return user;
    }
    @ResponseBody
    @RequestMapping("/test06.action")
    public String test06(){
        return "aaabbbccc";
    }

    /**
     * 处理器方法可以返回的返回值3 - void
     * 如果返回void,则使用默认视图名称作为视图名称来使用
     * 默认视图名称 是 当前处理器方法访问路径去后缀
     *  /my01/test05.action ---> my01/test05
     * http://localhost/SpringMVCDay02_03_Details04_ReturnType_war_exploded/my01/test05.action
     */
    @RequestMapping("/test05.action")
    public void test05(){
    }

    /**
     * 处理器方法可以返回的返回值2-3 - redirect:开头的字符串
     * 返回redirect:开头的字符串,将会实现重定向到对应路径,且书写路径时不需要拼接应用名,springmvc自动拼接
     * http://localhost/SpringMVCDay02_03_Details04_ReturnType_war_exploded/my01/test04.action
     */
    @RequestMapping("/test04.action")
    public String test04(){
        return "redirect:/index.jsp";
    }
    /**
     * 处理器方法可以返回的返回值2-2 - forward:开头的字符串
     * 返回forward:开头的字符串,将会实现请求转发到对应路径
     * http://localhost/SpringMVCDay02_03_Details04_ReturnType_war_exploded/my01/test03.action
     */
    @RequestMapping("/test03.action")
    public String test03(){
        return "forward:/index.jsp";
    }
    /**
     * 处理器方法可以返回的返回值2-1 - 普通字符串
     * 返回普通字符串,字符串会做为视图名称来使用
     * http://localhost/SpringMVCDay02_03_Details04_ReturnType_war_exploded/my01/test02.action
     */
    @RequestMapping("/test02.action")
    public String test02(Model model){
        model.addAttribute("k1","v1");
        model.addAttribute("k2","v2");
        return "my01test02";
    }
    /**
     * 处理器方法可以返回的返回值1 - ModelAndView
     * http://localhost/SpringMVCDay02_03_Details04_ReturnType_war_exploded/my01/test01.action
     */
    @RequestMapping("/test01.action")
    public ModelAndView test01(){
        ModelAndView mav = new ModelAndView();
        mav.addObject("k1","v1");
        mav.addObject("k2","v2");
        mav.setViewName("my01test01");
        return mav;
    }
}

my01test01.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>my01test01.jsp</title>
</head>
<body>
    this is my01test01.jsp<br/>
    k1:<%=request.getAttribute("k1")%><br/>
    k2:<%=request.getAttribute("k2")%><br/>
</body>
</html>

my01test02.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>my01test02.jsp</title>
</head>
<body>
    this is my01test02.jsp<br/>
    k1:<%=request.getAttribute("k1")%><br/>
    k2:<%=request.getAttribute("k2")%><br/>
</body>
</html>

test08.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>my01test08.jsp</title>
</head>
<body>
    this is my01test08.jsp<br/>
    <%=request.getAttribute("user")%>
</body>
</html>

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

6、域

在这里插入图片描述

request

springmvc.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: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/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">
    <!--配置包扫描-->
    <context:component-scan base-package="cn.tedu"/>
    <!--注解方式DI-->
    <context:annotation-config/>
    <!--注解方式MVC-->
    <mvc:annotation-driven/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

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">
    <!--配置前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

web

/**
 * 专题1:域的使用 - request域
 */
@RequestMapping("/my01")
@Controller
public class MyController01 {
    /**
     * request域的使用 - 从request域获取数据 - SpringMVC方式
     * http://localhost/SpringMVCDay02_03_Other01_war_exploded/my01/test05.action
     */
    @RequestMapping("/test06.action")
    public void test06(@RequestAttribute("k1") String k1){
        System.out.println(k1);
    }
    @RequestMapping("/test05.action")
    public String test05(HttpServletRequest request){
        request.setAttribute("k1","v1");
        return "forward:/my01/test06.action";
    }

    /**
     * request域的使用 - 从request域获取数据 - 传统方式
     * http://localhost/SpringMVCDay02_03_Other01_war_exploded/my01/test03.action
     */
    @RequestMapping("/test04.action")
    public void test04(HttpServletRequest request){
        String k1 = (String) request.getAttribute("k1");
        System.out.println(k1);
    }
    @RequestMapping("/test03.action")
    public String test03(HttpServletRequest request){
        request.setAttribute("k1","v1");
        return "forward:/my01/test04.action";
    }

    /**
     * request域的使用 - 向reuqest域写入数据 - springMVC方式
     * 向Model中写入的数据,默认就是写入到request域中
     * http://localhost/SpringMVCDay02_03_Other01_war_exploded/my01/test02.action
     */
    @RequestMapping("/test02.action")
    public String test02(Model model){
        model.addAttribute("k1","v1");
        model.addAttribute("k2","v2");
        return "my01test02";
    }

    /**
     * request域的使用 - 向reuqest域写入数据 - 传统方式
     * http://localhost/SpringMVCDay02_03_Other01_war_exploded/my01/test01.action
     */
    @RequestMapping("/test01.action")
    public String test01(HttpServletRequest request){
        request.setAttribute("k1","v1");
        request.setAttribute("k2","v2");
        return "my01test01";
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>my01test01.jsp</title>
</head>
<body>
  this is my01test01.jsp<br/>
  k1:<%=request.getAttribute("k1")%>
  k2:<%=request.getAttribute("k2")%>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>my01test02.jsp</title>
</head>
<body>
  this is my01test02.jsp<br/>
  k1:<%=request.getAttribute("k1")%>
  k2:<%=request.getAttribute("k2")%>
</body>
</html>

session

/**
 * 专题1:域的使用 - session域
 */
@SessionAttributes({"sk1","sk2"})
@RequestMapping("/my02")
@Controller
public class MyController02 {

    /**
     * session域的使用 - 从session域中获取数据 - SpringMVC方式
     * http://localhost/SpringMVCDay02_03_Other01_war_exploded/my02/test04.action
     */
    @RequestMapping("/test04.action")
    public void test04(@SessionAttribute("sk1") String sk1,@SessionAttribute("sk2") String sk2){
        System.out.println(sk1);
        System.out.println(sk2);
    }

    /**
     * session域的使用 - 从session域中获取数据 - 传统方式
     * http://localhost/SpringMVCDay02_03_Other01_war_exploded/my02/test03.action
     */
    @RequestMapping("/test03.action")
    public void test03(HttpSession session){
        String sk1 = (String) session.getAttribute("sk1");
        String sk2 = (String) session.getAttribute("sk2");
        System.out.println(sk1);
        System.out.println(sk2);
    }

    /**
     * session域的使用 - 向session域中写入数据 - SpringMVC方式
     * 将数据写入Model,同时将这些数据的名字配在类的@SessionAttributes注解中
     * 则这些属性,除了写入request域之外,还会拷贝一份到session域中
     *
     * http://localhost/SpringMVCDay02_03_Other01_war_exploded/my02/test02.action
     * @return
     */
    @RequestMapping("/test02.action")
    public String test02(Model model){
        model.addAttribute("sk1","sv1");
        model.addAttribute("sk2","sv2");
        return "my02test02";
    }

    /**
     * session域的使用 - 向session域中写入数据 - 传统方式
     * http://localhost/SpringMVCDay02_03_Other01_war_exploded/my02/test01.action
     */
    @RequestMapping("/test01.action")
    public String test01(HttpSession session){
        session.setAttribute("sk1","sv1");
        session.setAttribute("sk2","sv2");
        return "my02test01";
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>my02test01.jsp</title>
</head>
<body>
  this is my02test01.jsp<br/>
  <%=session.getAttribute("sk1")%>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>my02test02.jsp</title>
</head>
<body>
    this is my02test02.jsp
    <br/>
    request域:
    <%=request.getAttribute("sk1")%>
    <%=request.getAttribute("sk2")%>
    <br/>
    session域:
    <%=session.getAttribute("sk1")%>
    <%=session.getAttribute("sk2")%>
    <br/>
</body>
</html>

servletContext

/**
 * 专题1:域的使用 - ServletContext域
 */
@RequestMapping("/my03")
@Controller
public class MyController03 {

    /**
     * SpringMVC中没有提供便捷方式操作ServletContext域中的属性
     * 只能通过传统方式进行操作
     */
    @RequestMapping("/test02.action")
    public void test02(HttpServletRequest request){
        ServletContext sc = request.getServletContext();
        String sck1 = (String) sc.getAttribute("sck1");
        String sck2 = (String) sc.getAttribute("sck2");
        System.out.println(sck1);
        System.out.println(sck2);
    }
    @RequestMapping("/test01.action")
    public void test01(HttpServletRequest request){
        ServletContext sc = request.getServletContext();
        sc.setAttribute("sck1","scv1");
        sc.setAttribute("sck2","scv2");
    }
}

刷新

/**
 * 三种资源跳转方式的实现
 *  传统方式仍然可以使用,同时提供了便捷的springmvc方式
 */
@RequestMapping("/my04")
@Controller
public class MyController04 {
    /**
     * SpringMVC 实现定时刷新
     * springMVC没有提供便捷方法,只能手动实现定时刷新
     */
    @RequestMapping("/test03.action")
    public void test03(HttpServletRequest request,HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("注册成功!");
        response.setHeader("refresh","3;url="+request.getContextPath()+"/index.jsp");
    }
    /**
     * SpringMVC方式实现请求重定向
     */
    @RequestMapping("/test02.action")
    public String test02(){
        return "redirect:/index.jsp";
    }
    /**
     * SpringMVC方式实现请求转发
     */
    @RequestMapping("/test01.action")
    public String test01(){
        return "forward:/index.jsp";
    }
}

7、文件

在这里插入图片描述

配置文件上传工具
Controller中使用参数

spirngmvc.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: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/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">
    <!--配置包扫描-->
    <context:component-scan base-package="cn.tedu"/>
    <!--注解方式DI-->
    <context:annotation-config/>
    <!--注解方式MVC-->
    <mvc:annotation-driven/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--配置文件上传工具-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
    </bean>
</beans>

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">
    <!--配置前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

web

@RequestMapping("/my01")
@Controller
public class MyController01 {
    @RequestMapping("/test01.action")
    public void test01(String uname, String uaddr, MultipartFile fx) throws IOException {
        System.out.println(uname +"~"+ uaddr);
        fx.transferTo(new File("D://fs/"+fx.getOriginalFilename()));
    }
}

jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>文件上传表单</title>
    </head>
    <body>
        <!--
            文件上传项必须有name属性
            请求方式必须是POST
            必须配置 enctype="multipart/form-data"
        -->
        <form action="<%=request.getContextPath()%>/my01/test01.action"
              method="post" enctype="multipart/form-data">
            用户名:<input type="text" name="uname"/>
            地址:<input type="text" name="uaddr"/>
            选择文件:<input type="file" name="fx"/>
            <input type="submit"/>
        </form>
    </body>
</html>

8、异常

在这里插入图片描述

springmvc.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: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/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">
    <!--配置包扫描-->
    <context:component-scan base-package="cn.tedu"/>
    <!--注解方式DI-->
    <context:annotation-config/>
    <!--注解方式MVC-->
    <mvc:annotation-driven/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--配置全局错误处理-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.NullPointerException">nullerr</prop>
                <prop key="java.io.IOException">ioerr</prop>
                <prop key="java.lang.Throwable">gerr</prop>
            </props>
        </property>
    </bean>
</beans>

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">
    <!--配置前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

web

/**
 * 全局错误处理器
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public ModelAndView exceptionHandler(Exception e){
        System.out.println("##记录日志:"+e);
        ModelAndView mav = new ModelAndView();
        mav.addObject("e",e);
        mav.setViewName("gerr");
        return mav;
    }
}

@RequestMapping("/my01")
@Controller
public class MyController01 {

    /**
     * 异常处理方法,在当前处理器类中的处理器方法抛出异常时
     * 会触发此处理方法,可以在此处理方法中处理异常,并转到友好错误提示页面
     * @return
     */
    @ExceptionHandler
    public ModelAndView exceptionHandler(Exception e){
        System.out.println("##记录日志:"+e);
        ModelAndView mav = new ModelAndView();
        mav.addObject("e",e);
        mav.setViewName("my01err");
        return mav;
    }

    @RequestMapping("/test01.action")
    public void test01(){
        int i = 1/0;
    }
}
@Controller
@RequestMapping("/my02")
public class MyController02 {
    @RequestMapping("/test01.action")
    public void test01(){
        int i = 1/0;
    }
    @RequestMapping("/test02.action")
    public void test02(){
        throw new NullPointerException();
    }
    @RequestMapping("/test03.action")
    public void test03() throws IOException {
        throw new IOException();
    }
}

jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>gerr.jsp</title>
</head>
<body>
    全局错误提示:您访问的页面已蒙圈,你先瞅瞅别的去吧!
    <%=request.getAttribute("e")%>
</body>
</html>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>ioerr</title>
</head>
<body>
    ioerr....
</body>
</html>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>my01err</title>
</head>
<body>
    my01err..服务器出错了哦~~~~~~请之后再试...
    <%=request.getAttribute("e")%>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>nullerr</title>
</head>
<body>
    nullerr...
</body>
</html>

9、json

在这里插入图片描述

springmvc.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: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/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">
    <!--配置包扫描-->
    <context:component-scan base-package="cn.tedu"/>
    <!--注解方式DI-->
    <context:annotation-config/>
    <!--注解方式MVC-->
    <mvc:annotation-driven/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
<?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">
    <!--配置前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

user

package cn.tedu.domain;

import java.util.List;

public class User {
    private int id;
    private String name;
    private int age;
    private List<String> addrs;

    public User() {
    }

    public User(int id, String name, int age, List<String> addrs) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.addrs = addrs;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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;
    }

    public List<String> getAddrs() {
        return addrs;
    }

    public void setAddrs(List<String> addrs) {
        this.addrs = addrs;
    }

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

web

@RequestMapping("/my01")
@Controller
public class MyController01 {

    /**
     * 接受json数据
     * 当浏览器发送json格式过来时,可以直接通过@RequestBody获取实体内容中的json数据
     * 如果是用字符串类型接受,得到的是json字符串
     * 如果是用对象接受,则springMVC会自动将json转换为对象传入 - 前提是,json和对象类 属性名、属性类型要对应的上
     */
    @RequestMapping("/test02.action")
    public void test02(@RequestBody User user){
        System.out.println(user);
    }

    /**
     * 发送json数据
     *  返回一个对象并配置@ResponseBoby,将使SpringMVC将对象转为json发送给浏览器
     *  可以在@RequestMapping中配置produces = "application/json;charset=utf-8"解决可能的中文乱码
     */
    @ResponseBody
    @RequestMapping(value = "/test01.action",produces = "application/json;charset=utf-8")
    public User test01(HttpServletResponse response){
        //..调用Service..调用Dao..返回了结果对象
        User user = new User(3,"张三",18, Arrays.asList("bj","sh","gz"));
        //将查到的数据通过json格式发送给浏览器
        return user;
    }
}

jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>my02test02.jsp</title>
    <script type="application/javascript" src="<%=request.getContextPath()%>/js/jquery-1.4.2.js"></script>
    <script type="application/javascript">
        function regist(){
            var mydata = {"id":99,"name":"ls","age":88,"addr":["bj","sh","gz"]};
            $.ajax({
                type:"POST", 		//必须以POST方式提交,必须大写
                url:"http://localhost/SpringMVCDay02_06_Other04_Json_war_exploded/my01/test02.action",
                dataType:"json",
                contentType:"application/json",    	//已json格式处理
                data:JSON.stringify(mydata),	//将js对象转换为json串
                success:function(data){
                    alert("success"+data);
                }
            });
        }
    </script>
</head>
<body>
    <button onclick="regist()" >注册</button>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值