SpringMvc简单实用-框架三

SpringMvc是什么?

SpringMvc是一个表现层框架

后面框架整合的时候是先通过springmvc,spring

底层是Servlet,处理请求的机制是一个核心控制器

springmvc是一个基于servlet的mvc框架

执行流程

  1. request请求发送过来
  2. 请求查找handler
  3. 由处理器映射器handlermappering 进行处理这个请求,
    能够知道发送过来的请求让controller中哪个方法来帮你执行
    通过请求路径来匹配
    采用适配器的模式,
  4. 请求适配器执行 handleradapter 去执行hadnler(handler也叫做Controller)
  5. 去执行,返回返回结果
  6. controller(handler)执行并返回 ModleAndView 对象给 DispatcherServlet
  7. DispatcherServlet 让viewResolver 来进行视图解析
  8. viewResolver 解析完毕后返回一个View对象
  9. 视图渲染,将结果交给request域,然后相应客户端请求

Springmvc组件

在SpringMvc各个组件:
处理器映射器
处理器适配器
视图解析器配
成为Springmvc的三大组件

<mvc:annotation-driven>
注解在xml中配置可以 开启springmvc的框架注解支持

SpringMvc环境配置

springmvc.xml环境配置

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

    <!-- 开启注解扫描 -->
    <context:component-scan base-package="cn.itcast"/>

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

    <!--配置自定义类型转换器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="cn.itcast.utils.StringToDateConverter"/>
            </set>
        </property>
    </bean>


    <!-- 开启SpringMVC框架注解的支持 -->
    <mvc:annotation-driven conversion-service="conversionService"/>

</beans>

web.xml配置

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

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

  <!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
    
  <!--设置配置文件的路径-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
    
  <context-param>
    <param-name/>
    <param-value/>
  </context-param>

  <!--配置前端控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载springmvc.xml配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--启动服务器,创建该servlet-->
    <load-on-startup>1</load-on-startup>
  </servlet>
    
    <!--引用前端控制器,并配置他的作用范围-->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!--解决中文乱码的过滤器-->
  <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>
  
</web-app>

请求参数的绑定

springmvc可以利用反射的机制进行参数的绑定

将你请求中的参数,自定映射到方法@RequestMapper的方法字段中

    /**
     * 请求参数绑定入门
     * @return
     */
    @RequestMapping("/testParam")
    public String testParam(String username,String password){
        System.out.println("执行了...");
        System.out.println("用户名:"+username);
        System.out.println("密码:"+password);
        return "success";
    }

    <a href="anno/testRequestParam?name=哈哈">RequestParam</a>

请求对象的绑定

注意! 名称必须一致,它是通过调用set方法来进行赋值的。

public class Account implements Serializable{
    private String username;
    private String password;
    private Double money;    
    get set.....
}

/**
     * 请求参数绑定把数据封装到JavaBean的类中
     * @return
     */
    @RequestMapping("/saveAccount")
    public String saveAccount(Account account){
        System.out.println("执行了...");
        System.out.println(account);
        return "success";
    }
    <!--把数据封装Account类中-->
    <form action="param/saveAccount" method="post">
        姓名:<input type="text" name="username" /><br/>
        密码:<input type="text" name="password" /><br/>
        金额:<input type="text" name="money" /><br/>
        <input type="submit" value="提交" />
    </form>

请求对象中引用对象的绑定

//java bean
public class Account implements Serializable{

    private String username;
    private String password;
    private Double money;

   	private User user;
}

public class User implements Serializable{
    private String uname;
    private Integer age;
}
    /**
     * 请求参数绑定把数据封装到JavaBean的类中
     * @return
     */
    @RequestMapping("/saveAccount")
    public String saveAccount(Account account){
        System.out.println("执行了...");
        System.out.println(account);
        return "success";
    }
  jsp页面
  <!--把数据封装Account类中-->
    <form action="param/saveAccount" method="post">
        姓名:<input type="text" name="username" /><br/>
        密码:<input type="text" name="password" /><br/>
        金额:<input type="text" name="money" /><br/>
        用户姓名:<input type="text" name="user.uname" /><br/>
        用户年龄:<input type="text" name="user.age" /><br/>
        <input type="submit" value="提交" />
    </form>

集合类型的绑定

//java bean
public class Account implements Serializable{

    private String username;
    private String password;
    private Double money;

   // private User user;

    private List<User> list;
    private Map<String,User> map;
}

public class User implements Serializable{
    private String uname;
    private Integer age;
}
    /**
     * 请求参数绑定把数据封装到JavaBean的类中
     * @return
     */
    @RequestMapping("/saveAccount")
    public String saveAccount(Account account){
        System.out.println("执行了...");
        System.out.println(account);
        return "success";
    }
<!--jsp 页面-->
    <form action="param/saveAccount" method="post">
        姓名:<input type="text" name="username" /><br/>
        密码:<input type="text" name="password" /><br/>
        金额:<input type="text" name="money" /><br/>
		<!--指定list的下标位置-->
        用户姓名:<input type="text" name="list[0].uname" /><br/>
        用户年龄:<input type="text" name="list[0].age" /><br/>
		<!--指定map的key是one,v是-->
        用户姓名:<input type="text" name="map['one'].uname" /><br/>
        用户年龄:<input type="text" name="map['one'].age" /><br/>
        <input type="submit" value="提交" />
    </form>

SpringMvc过滤器,解决post请求乱码问题

前端多滤器,设置他们的字符编码

post方法会乱码,get方式不会乱码

在web.xml中配置全局过滤器,配置时过滤器位置放在servlet位置前面

<web-app>
  <display-name>Archetype Created Web Application</display-name>
    
  <!--配置解决中文乱码的过滤器-->
  <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>dispatcherServlet</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>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

类型转换器

Springmvc会对一些简单属性进行转换 如 input输入age是22 自动转换成Integer,但是复杂类型需要自己来实现转换

//java bean
public class User implements Serializable{

    private String uname;
    private Integer age;

    private Date date;
}
    /**
     * 使用了自定义类型转换器
     * @param user
     * @return
     */
    @RequestMapping("/saveUser")
    public String saveUser(User user){
        System.out.println("执行了...");
        System.out.println(user);
        return "success";
    }
<!--jsp 页面-->
    <form action="param/saveUser" method="post">
        用户姓名:<input type="text" name="uname" /><br/>
        用户年龄:<input type="text" name="age" /><br/>
        用户生日:<input type="text" name="date" /><br/>
        <input type="submit" value="提交" />
    </form>

自定义类型转换器编写

  1. 需要实现converter接口,定义泛型<String,Date>

    左边类型是原始类型,右边类型是转换类型

/**
 * 把字符串转换日期
 */
public class StringToDateConverter implements Converter<String,Date>{

    /**
     * String source    传入进来字符串
     * @param source    
     * @return
     */
    public Date convert(String source) {
        // 判断
        if(source == null){
            throw new RuntimeException("请您传入数据");
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        try {
            // 把字符串转换日期
            return df.parse(source);
        } catch (Exception e) {
            throw new RuntimeException("数据类型转换出现错误");
        }
    }

}
  1. 在springmvc.xml中注册类型转换器
    <!--配置自定义类型转换器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="cn.itcast.utils.StringToDateConverter"/>
            </set>
        </property>
    </bean>

    <!-- 开启SpringMVC框架注解的支持 -->
    <mvc:annotation-driven conversion-service="conversionService"/>

调用Servlet原生API

在Springmvc中获取到原来servlet的内置对象request,response,session和servletcontext

/**
 * 原生的API
 * @return
 */
@RequestMapping("/testServlet")
public String testServlet(HttpServletRequest request, HttpServletResponse response){
    System.out.println("执行了...");
    System.out.println(request);

    HttpSession session = request.getSession();
    System.out.println(session);

    ServletContext servletContext = session.getServletContext();
    System.out.println(servletContext);

    System.out.println(response);
    return "success";
}
<a href="param/testServlet">Servlet原生的API</a>

SpringMvc常用注解

@Controller

@Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象。分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了@RequestMapping 注解。

@Controller 只是定义了一个控制器类,而使用@RequestMapping 注解的方法才是真正处理请求的处理器。

@RequestMapping

时间里请求URL和处理请求方法之间的关系

属性:

value,path 这两个作用是一样的,都是指定访问请求路径

method 指定他的请求方式,指定Post就只能Post请求

@RequestMapping(value="/username",params ={username},method=RequestMethod.PUT)

params 指定他的参数,调用时必须传入这个名称的参数才能调用

@RequestMapping(value="/username",params ={username})
指定了调用时必须有username这个字段

@RequestMapping(value="/username",params ={username=heihei})
指定了调用时必须有username这个字段,并且字段的值只能是heihei

headers 指定限制请求消息头的条件

@RequestMapper(value="/username",params ={username=heihei},headers={"Accept"})

@RequestParam

把请求指定名称的参数给控制器中的形参赋值,用于参数名称和你方法参数名称不匹配的情况。

属性

value 请求参数中的名称

required 请求参数中是否必须提供此参数,默认true,表示必须提供,不提供就报错

例子:

@Controller
@RequestMapping("/anno")
public class AnnoController {

    @RequestMapping("/testRequestParam")
    public String testRequestParam(@RequestParam(name="name") String username){
        System.out.println("执行了...");
        System.out.println(username);
        return "success";
    }
}
//在这里默认使用了required,默认是true,前端必须只能传name字段的值,字段name变成uname都会报错
//jsp
    <a href="anno/testRequestParam?name=哈哈">RequestParam</a>

@RequestBody

用于获取请求体内容,直接使用得到 key=value&key=value 结构的数据,可以直接名称调用,也可以直接封装到对象中

get方法不适用(get请求都封装到了地址栏上,没有请求体)

属性:

required 是否必须有请求体,默认是true。true的时候get方法会报错,取值为false,get请求得到的是null

例子:

    <form action="anno/testRequestBody" method="post">
        用户姓名:<input type="text" name="username" /><br/>
        用户年龄:<input type="text" name="age" /><br/>
        <input type="submit" value="提交" />
    </form>
    /**
     * 获取到请求体的内容
     * @return
     */
    @RequestMapping("/testRequestBody")
    public String testRequestBody(@RequestBody String body){
        System.out.println("执行了...");
        System.out.println(body);
        return "success";
    }

图片

@ResponseBody

和RequestBody作用相反,用来响应客户端请求,返回指定类型

@PathVariable

拥有绑定url中的占位符,例如url中 /delete/{id} 这个{id} 就是url占位符

url支持占位符是spring3.0之后加入的,是SpringMvc支持rest分隔url的一个重要标志

Restful编程风格

请求地址一样,但是能够根据请求方式的不同(get,put,post)来执行不同的方法

属性:

value 用于指定url占位符的名称

required 是否必须提供占位符

例子:

    <a href="anno/testPathVariable/10">testPathVariable</a>
    /**
     * PathVariable注解
     * @return
     */
    @RequestMapping(value="/testPathVariable/{sid}")
    public String testPathVariable(@PathVariable(name="sid") String id){
        System.out.println("执行了...");
        System.out.println(id);
        return "success";
    }

@HiddentHttpMethodFilter

了解即可,是为了模拟不同的发送请求方式

浏览器的form表单只支持get和post请求,而Delelte,put等method并不支持,Spring3.0添加了一个过滤器,可以将浏览器请求去改为指定的请求方式,发送给我们的控制器方法,使得支持get,post,put与delete请求

使用方法:

  1. 在web.xml中配置过滤器
  2. 请求法师必须使用post请求
  3. 按照要求提供_method请求参数,该参数的取值就是我们需要的请求方式

@RequestHeader

开发中不怎么用

用于 获取请求消息头的值

属性:

value 提供消息头名称

required 是否必须有此消息头

例子:

    <a href="anno/testRequestHeader">RequestHeader</a>
    /**
     * 获取请求头的值
     * @param header
     * @return
     */
    @RequestMapping(value="/testRequestHeader")
    public String testRequestHeader(@RequestHeader(value="Accept") String header, HttpServletRequest request,HttpServletResponse response) throws IOException {
        System.out.println("执行了...");
        System.out.println(header);
        // return "success";
        // response.sendRedirect(request.getContextPath()+"/anno/testCookieValue");
        return "redirect:/param.jsp";
    }

图片

@Cookie

把指定cookie名称传入控制器方法参数

属性:

value 指定cookie名称

required 是否必须由此cookie

例子:

    <a href="anno/testCookieValue">CookieValue</a>
    /**
     * 获取Cookie的值
     * @return
     */
    @RequestMapping(value="/testCookieValue")
    public String testCookieValue(@CookieValue(value="JSESSIONID") String cookieValue){
        System.out.println("执行了...");
        System.out.println(cookieValue);
        return "success";
    }

@MouelAttribute

该注解SpringMVC4.3版本之后加入的,可以用于修饰方法和参数

出现在方法上,在控制前方法执行之前,先执行。可以修饰没有返回值的方法,也可以修饰具有返回值的方法

属性:

Value 用于获取数据的key,key可以是pojo的属性名称,也可以是map结构的key

应用场景:

但表单提交不是完整的实体类数据时,保证没有提交数据的字段使用数据库对象原来的数据

例子:

没有返回值的类型

    /** 没有返回值的类型   参数中使用@ModelAttribute 指定key来获取值
     * ModelAttribute注解
     * @return
     */
    @RequestMapping(value="/testModelAttribute")
    public String testModelAttribute(@ModelAttribute("abc") User user){
        System.out.println("testModelAttribute执行了...");
        System.out.println(user);
        return "success";
    }


///没有返回值的类型,值需要添加一个Map集合
    @ModelAttribute
    public void showUser(String uname, Map<String,User> map){
        System.out.println("showUser执行了...");
        // 通过用户查询数据库(模拟)
        User user = new User();
        user.setUname(uname);
        user.setAge(20);
        user.setDate(new Date());
        map.put("abc",user);
    }

有返回值的类型

    /**有返回值的类型   
     * ModelAttribute注解
     * @return
     */
    @RequestMapping(value="/testModelAttribute")
    public String testModelAttribute(User user){
        System.out.println("testModelAttribute执行了...");
        System.out.println(user);
        return "success";
    }   


/**  有返回值的类型
     * 该方法会先执行
     */
    @ModelAttribute
    public User showUser(String uname){
        System.out.println("showUser执行了...");
        // 通过用户查询数据库(模拟)
        User user = new User();
        user.setUname(uname);
        user.setAge(20);
        user.setDate(new Date());
        return user;
    }

@SessoinAttribute

只能作用在类上,没听太懂,视频182

多次执行控制器方法将的参数共享

属性:

value 属性的名称

type 属性的类型

例子:

import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;


@Controller
@RequestMapping("/anno")
@SessionAttributes(value={"msg"})   // 把 msg=美美 存入到session域对中
public class AnnoController {
    /**
     * SessionAttributes的注解
     * @return
     */
    @RequestMapping(value="/testSessionAttributes")
    public String testSessionAttributes(Model model){
        System.out.println("testSessionAttributes...");
        // 底层会存储到request域对象中
        model.addAttribute("msg","美美");
        return "success";
    }

    /**
     * 获取值
     * @param modelMap
     * @return
     */
    @RequestMapping(value="/getSessionAttributes")
    public String getSessionAttributes(ModelMap modelMap){
        System.out.println("getSessionAttributes...");
        String msg = (String) modelMap.get("msg");
        System.out.println(msg);
        return "success";
    }

    /**
     * 清除
     * @param status
     * @return
     */
    @RequestMapping(value="/delSessionAttributes")
    public String delSessionAttributes(SessionStatus status){
        System.out.println("getSessionAttributes...");
        status.setComplete();
        return "success";
    }
    
}
<a href="anno/testSessionAttributes">testSessionAttributes</a>


success.jsp:

<body>

    <h3>入门成功</h3>

    ${ msg }

    ${sessionScope}

</body>

SpringMvc响应方式

根据返回值分类

1、字符串

字符串类型的返回值 前端控制器会按照返回值跳转到对应的jsp页面

2、void

SpringMvc提供的转发和重定向

没有返回值的时候,它默认是按照RequestMapping的value去寻找.jsp页面

在跳转的时候通过request 进行转发,response进行重定向

    /**
     * 是void
     * 请求转发一次请求,不用编写项目的名称
     * 重定向是两次请求,需要编写项目名称
     */
    @RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("testVoid方法执行了...");
         // 编写请求转发的程序
         request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);

         // 重定向   是重新发了个请求  web-inf是直接进不去的
		//request.getContextPath()  获取项目名称
        response.sendRedirect(request.getContextPath()+"/index.jsp");

        // 设置中文乱码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 直接会进行响应浏览器
        response.getWriter().print("你好");

        return;
    }


    /**
     * 使用关键字的方式进行转发或者重定向
     * @return
     */
    @RequestMapping("/testForwardOrRedirect")
    public String testForwardOrRedirect(){
        System.out.println("testForwardOrRedirect方法执行了...");

        // 请求的转发
        // return "forward:/WEB-INF/pages/success.jsp";

        // 重定向
        return "redirect:/index.jsp";
    }

前端控制器配置拦截资源

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

    <!-- 开启注解扫描 -->
    <context:component-scan base-package="cn.itcast"/>

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

    <!--前端控制器,哪些静态资源不拦截-->
    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/images/" mapping="/images/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>

    <!-- 开启SpringMVC框架注解的支持 -->
    <mvc:annotation-driven />

</beans>

ModelAndView对象

这个对象底层用的modelMap对象,是request范围的

    /**
     * 返回ModelAndView
     * @return
     */
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
        // 创建ModelAndView对象
        ModelAndView mv = new ModelAndView();
        System.out.println("testModelAndView方法执行了...");
        // 模拟从数据库中查询出User对象
        User user = new User();
        user.setUsername("小凤");
        user.setPassword("456");
        user.setAge(30);

        // 把user对象存储到mv对象中,也会把user对象存入到request对象
        mv.addObject("user",user);

        // 跳转到哪个页面
        mv.setViewName("success");

        return mv;
    }
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/5/1
  Time: 1:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <h3>执行成功</h3>

    ${user.username}
    ${user.password}

</body>
</html>

ajax请求响应json数据

    <script>
        // 页面加载,绑定单击事件
        $(function(){
            $("#btn").click(function(){
                // alert("hello btn");
                // 发送ajax请求
                $.ajax({
                    // 编写json格式,设置属性和值
                    url:"user/testAjax",
                    contentType:"application/json;charset=UTF-8",
                    data:'{"username":"hehe","password":"123","age":30}',
                    dataType:"json",
                    type:"post",
                    success:function(data){
                        // data服务器端响应的json的数据,进行解析
                        alert(data);
                        alert(data.username);
                        alert(data.password);
                        alert(data.age);
                    }
                });

            });
        });

    </script>
    /**
     * 模拟异步请求响应
     */
    @RequestMapping("/testAjax")
    public @ResponseBody User testAjax(@RequestBody String body){
        System.out.println("testAjax方法执行了...");
        System.out.println(body);
    }

//控制台会输出 :
{"username":"hehe","password":"123","age":30}

Json字符串封装到 Java Bean中

Json字符串转换成对象、对象转换成Json字符串 都是spring给我们转换,我们只需要导入 jackson 的包

   <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.0</version>
    </dependency>

使用 ResponseBody 和 RequestBody 注解来进行转换

//java bean
    public class User implements Serializable{

    private String username;
    private String password;
    private Integer age;
    }

    /**
     * 模拟异步请求响应
     * responseBody 相应的  将bean转换成 json字符串
     * responseBody返回的类型跟你ajax设置的datetype相关
     * requestBody 接受的
     */
    @RequestMapping("/testAjax")
    public @ResponseBody User testAjax(@RequestBody User user){
        System.out.println("testAjax方法执行了...");
        // 客户端发送ajax的请求,传的是json字符串,后端把json字符串封装到user对象中
        System.out.println(user);
        // 做响应,模拟查询数据库
        user.setUsername("haha");
        user.setAge(40);
        // 做响应
        return user;
    }

//控制台会输出 :
{"username":"hehe","password":"123","age":30}

SpringMvc异常处理

  1. 编写自定义异常类(做提示信息的)

  2. 编写异常处理器

  3. 配置异常处理器(跳转到提示页面)

/**
 * 自定义异常类
 */
public class SysException extends Exception{

    // 存储提示信息的
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public SysException(String message) {
        this.message = message;
    }

}
/**
 * 异常处理器    需要实现handlerExceptionResolver接口,处理异常
 */
public class SysExceptionResolver implements HandlerExceptionResolver{

    /**
     * 处理异常业务逻辑
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @return
     */
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 获取到异常对象
        SysException e = null;
        if(ex instanceof SysException){
            e = (SysException)ex;
        }else{
            e = new SysException("系统正在维护....");
        }
        // 创建ModelAndView对象
        ModelAndView mv = new ModelAndView();
        //request范围的值kv入参
        mv.addObject("errorMsg",e.getMessage());
        //使用modelandview  进行页面的跳转
        mv.setViewName("error");
        return mv;
    }
}
<!--发生error跳转的页面-->
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/5/5
  Time: 22:28
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    ${errorMsg}

</body>
</html>
//在xml文件中配置这个  异常处理器
<bean id="sysExceptionResolver" class="cn.itcast.exception.SysExceptionResolver"/>

SpringMvc拦截器配置

编写拦截器步骤:

  1. 编写拦截器类,实现MandlerIntercepter接口

  2. 配置拦截器

/**
 * 自定义拦截器
 */
public class MyInterceptor1 implements HandlerInterceptor{

    /**
     * 预处理,controller方法执行前
     * return true 放行,执行下一个拦截器,如果没有,执行controller中的方法
     * return false不放行  就不会执行controller中的方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor1执行了...前1111");
        // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);
        return true;
    }

    /**
     * 后处理方法,controller方法执行后,success.jsp执行之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor1执行了...后1111");
        // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);
    }

    /**
     * success.jsp页面执行后,该方法会执行  可用于释放资源
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor1执行了...最后1111");
    }

}
在SpringMvc.xml中配置这个拦截器

 <!--配置拦截器-->
    <mvc:interceptors>
        <!--配置拦截器-->
        <mvc:interceptor>
            <!--要拦截的具体的方法-->
            <mvc:mapping path="/user/*"/>
            <!--不要拦截的方法
            <mvc:exclude-mapping path=""/>
            -->
            <!--配置拦截器对象-->
            <bean class="cn.itcast.controller.cn.itcast.interceptor.MyInterceptor1" />
        </mvc:interceptor>

        <!--配置第二个拦截器-->
        <mvc:interceptor>
            <!--要拦截的具体的方法-->
            <mvc:mapping path="/**"/>
            <!--不要拦截的方法
            <mvc:exclude-mapping path=""/>
            -->
            <!--配置拦截器对象-->
            <bean class="cn.itcast.controller.cn.itcast.interceptor.MyInterceptor2" />
        </mvc:interceptor>
    </mvc:interceptors>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值