当前位置: 移动技术网 > IT编程>开发语言>Java > 深入学习SpringMVC

深入学习SpringMVC

2019年07月20日  | 移动技术网IT编程  | 我要评论

  

1.什么是springmvc?

  springmvc是spring框架内置的mvc的实现。springmvc就是一个spring内置的mvc框架。
mvc框架,它解决web开发中常见的问题(参数接收、文件上传、表单验证、国际化等等),而且使用简单,与spring无缝集成。 支持 restful风格的 url 请求 。
采用了松散耦合可插拔组件结构,比其他 mvc 框架更具扩展性和灵活性。

2.springmvc底层实现

  在没有使用springmvc之前我们都是使用的servlet在做web开发。但是使用servlet开发在接受请求数据参数,数据共享,页面跳转等操作相对比较复杂。
springmvc底层就是的servlet,springmvc就是对servlet进行更深层次的封装。

3.springmvc入门示例

  1.导入jar包

  

 

  2.编写controller控制器(与以前servlet类似)
  创建一个类实现controller即可

public class hellocontroller implements controller {

    @override
    public modelandview handlerequest(httpservletrequest request, httpservletresponse response) throws exception {
            
        modelandview mv = new modelandview(); //modelandview对象封装了model数据和view信息

        mv.addobject("username", "张三");// 共享数据

        mv.setviewname("/web-inf/hello.jsp");// 设置跳转页面

        return mv;
    }
}

  3.在springmvc.xml配置 controller

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
    xsi:schemalocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        ">
        <!--配置springmvc控制器
        name : 给当前控制器取的一个名字,相当于servlet中的资源名称,以便浏览器访问,必须以斜杠/开头,
            建议使用 name属性,不要使用id,因为早期版本 id 不支持特殊字符 如 /斜杠
      -->
    <bean name="/hello" class="com.gjs.controller.hellocontroller"/>
</beans>

  4.在web.xml中配置前端控制器关联springmvc.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>springmvc1-入门</display-name>
  <welcome-file-list>
    <welcome-file></welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 配置springmvc框架,web.xml是项目入口,访问项目最先进入 web.xml -->
  
  <!-- 
      配置springmvc的前端控制器(总控)
      配置前端控制器以后,用户浏览器的所有请求全部走springmvc,如果不配(默认走servlet)
       springmvc底层是基于servlet
   -->
   <servlet>
        <servlet-name>mvc</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>
        <!-- 是否在启动时加载控制器
              1:是,在服务器启动以后立即创建对象
              -1:否(默认),用户第一次访问时候才创建-->
        <load-on-startup>1</load-on-startup>
   </servlet>
   
   <servlet-mapping>
           <servlet-name>mvc</servlet-name>
           <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>

  5.配置到tomcat上并启动

  6.结果

  

4.springmvc的全注解开发(一般都用注解不会用xml方式)

  4.1 springmvc中的常用注解

  

  4.2 springmvc使用注解步骤

    1.导入相关jar包

    

     2.在springmvc.xml中配置注解扫描及mvc注解支持

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
    xsi:schemalocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        
        ">
        <!-- 配置要进行注解包扫描的位置 -->
        <context:component-scan base-package="com.gjs"/>
        <!-- 开启mvc注解支持, 同时还支持返回json数据-->
        <mvc:annotation-driven/>
</beans>

    3.在web.xml中配置前端控制器

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>springmvc1-入门</display-name>
  <welcome-file-list>
    <welcome-file></welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 配置springmvc框架,web.xml是项目入口,访问项目最先进入 web.xml -->
  
  <!-- 
      配置springmvc的前端控制器(总控)
      配置前端控制器以后,用户浏览器的所有请求全部走springmvc,如果不配(默认走servlet)
       springmvc底层是基于servlet
   -->
   <servlet>
        <servlet-name>mvc</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>
        <!-- 是否启动时加载,1:是,-1:否-->
        <load-on-startup>1</load-on-startup>
   </servlet>
   
   <servlet-mapping>
           <servlet-name>mvc</servlet-name>
           <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>

    4.controller控制器

package com.gjs.controller;

import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.servlet.modelandview;

@controller // 声明当前类为控制器
public class hellocontroller {

    @requestmapping("hello")
    public modelandview hello() {

        modelandview mv = new modelandview();// modelandview对象封装了model数据和view信息

        mv.addobject("username", "李四");// 共享数据

        mv.setviewname("/web-inf/hello.jsp");// 设置跳转页面

        return mv;
    }

}

5.springmvc执行流程和原理

  5.1springmvc流程:

01、用户发送出请求到前端控制器dispatcherservlet。
02、dispatcherservlet收到请求调用handlermapping(处理器映射器)。
03、handlermapping找到具体的处理器(可查找xml配置或注解配置),生成处理器对象及处理器拦截器(如果有),再一起返回给dispatcherservlet。
04、dispatcherservlet调用handleradapter(处理器适配器)。
05、handleradapter经过适配调用具体的处理器(handler/controller)。
06、controller执行完成返回modelandview对象。
07、handleradapter将controller执行结果modelandview返回给dispatcherservlet。
08、dispatcherservlet将modelandview传给viewreslover(视图解析器)。
09、viewreslover解析后返回具体view(视图)。
10、dispatcherservlet根据view进行渲染视图(即将模型数据填充至视图中)。
11、dispatcherservlet响应用户。

  5.2 涉及组件分析:

1、前端控制器dispatcherservlet(不需要程序员开发),由框架提供,在web.xml中配置。
作用:接收请求,响应结果,相当于转发器,中央处理器。

2、处理器映射器handlermapping(不需要程序员开发),由框架提供。
作用:根据请求的url查找handler(处理器/controller),可以通过xml和注解方式来映射。

3、处理器适配器handleradapter(不需要程序员开发),由框架提供。
作用:按照特定规则(handleradapter要求的规则)去执行handler。

4、处理器handler(也称之为controller,需要工程师开发)
注意:编写handler时按照handleradapter的要求去做,这样适配器才可以去正确执行handler。
作用:接受用户请求信息,调用业务方法处理请求,也称之为后端控制器。

5、视图解析器viewresolver(不需要程序员开发),由框架提供
作用:进行视图解析,把逻辑视图名解析成真正的物理视图。
springmvc框架支持多种view视图技术,包括:jstlview、freemarkerview、pdfview等。

6、视图view(需要工程师开发)
作用:把数据展现给用户的页面
view是一个接口,实现类支持不同的view技术(jsp、freemarker、pdf等)

具体组件的配置相关,请查阅 spring-webmvc-4.3.2.release.jar 包下面 org/springframework/web/servlet/dispatcherservlet.properties 的相关配置

6.对静态资源访问

  按照第3和第4点的配置,会出现静态资源无法访问的情况(如html页面)。原因是在web.xml中配置的前端控制器的映射路径(<url-pattern>)为“/”,而tomcat中对静态资源处理的servlet的的映射路径也是“/”。也就是说,我们配置springmvc中的dispatcherservlet的映射路径覆盖了tomcat默认对静态资源的处理的路径。
  tomcat部分源码:

<servlet>
        <servlet-name>default</servlet-name>
        <servlet-class>org.apache.catalina.servlets.defaultservlet</servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>0</param-value>
        </init-param>
        <init-param>
            <param-name>listings</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

  解决方案:
    方案一:如果springmvc要配置为/,那么就得设置dispatcherservlet对静态资源进行支持。
    在springmvc的配置文件中添加以下代码开启对静态资源的访问

 <mvc:default-servlet-handler/>

    

    方案二:springmvc映射路径不要配置为/ (也不要配置为/* ,/*会匹配所有url)
    实际开发中一般推荐使用 *.后缀 如 *.do *.action 

<servlet-mapping>
           <servlet-name>mvc</servlet-name>
           <url-pattern>*.do</url-pattern>
   </servlet-mapping>

    注:访问时以.do结尾的url访问,配置方法的映射路径时可以不加.do(建议不加)

7.spring请求响应

  7.1.@requestmapping

@requestmapping注解主要用于设置springmvc请求的映射路径
所谓的映射路径,就是匹配请求路径和执行方法关系的路径.

请求路径:http://localhost:8080/springmvc/method1.do
映射路径:@requestmapping(value="/method1") (“value=”可以省略)

@requestmapping 用于贴在控制器的类上或者方法上面
如果是贴在控制器的类上面,那么在访问这个类的方法之前必须先加上类上的对应的名称类似于 项目下面的 模块名称
如果贴在方法上面,就是访问此方法的资源名称

@controller
@requestmapping("/request")  //访问时候必须加上,类似模块名称
public class requestcontroller {
    @requestmapping(value="/method1") //资源名称 
    public void method1() {
    }
}

    访问地址  : http://localhost:8080/springmvc/request/method1.do 

  7.2两种限制

    springmvc支持对请求的限制.如果不满足限制的条件,就不让访问执行方法。这样做,大大提高了执行方法的安全性。
    主要的限制有两种:方法限制(method),参数限制

      1.方法限制: 

       设置请求的method类型(get/post)。如果发送过来的请求与方法设置的method不一样,就不能访问执行方法。

/*
     * @requestmapping 请求映射注解
     * value : 请求的url地址映射,没有其他参数时“value=”可以省略,有其他参数就不能省略
     * method :限定请求方式 get /post  默认没有限制get/post都可以
     * params : 请求参数的限制:  必须有什么参数,必须没有什么参数,参数的值必须是什么
     */
    @requestmapping(value="/login1",method=requestmethod.post)
    public modelandview login(httpservletrequest request,httpservletresponse reponse,httpsession sesion ) {
        string username = request.getparameter("username");
        string password = request.getparameter("password");
        
        system.out.println(username);
        system.out.println(password);
        return null;
        
    }
<%-- el表达式获取上下文路径 : ${pagecontext.request.contextpath} --%>
    <h4>登录页面</h4>
    <form action="${pagecontext.request.contextpath}/request/login1.do"
        method="get">
        账号:<input name="username"><br>
            密码:<input type="password" name="pwd"><br>
        <button type="submit">登录</button>
    </form>

不支持请求方法“get”

    2.参数限制

      限制请求里面必须包括哪些参数,或不包括哪些哪些,参数必须包括哪些值,不包括哪些值

      限制参数格式:

1.参数必须包括:params={"username","password"}
2.参数不能包括:params={"!userid"}
3参数值必须是指定的值:params={"username=zhangsan"})
4.参数值必须不是指定的值:params={"userid!=123"})

/*
     * @requestmapping
     * 请求映射注解
     * value : 请求的url地址映射,没有其他参数时“value=”可以省略,有其他参数就不能省略
     * method :限定请求方式 get /post  默认没有限制get/post都可以
     * params : 请求参数的限制:  必须有什么参数,必须没有什么参数,参数的值必须是什么
     */
    @requestmapping(value="/login2",params={"username","password"})
    public modelandview login(httpservletrequest request,httpservletresponse reponse,httpsession sesion ) {
        string username = request.getparameter("username");
        string password = request.getparameter("password");
        
        system.out.println(username);
        system.out.println(password);
        return null;
        
    }
<%@ page language="java" contenttype="text/html; charset=utf-8"
    pageencoding="utf-8"%>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>登录</title>
</head>
<body>
    <%-- el表达式获取上下文路径 : ${pagecontext.request.contextpath} --%>
    <h4>登录页面</h4>
    <form action="${pagecontext.request.contextpath}/request/login2.do"
        method="post">
        账号:<input name="username"><br>
         密码:<input type="password" name="pwd"><br>
        <button type="submit">登录</button>
    </form>
</body>
</html>

参数条件“username, password”不满足,实际请求参数:username={admin}, pwd={123}

  7.3springmvc方法参数注入

    springmvc的方法默认可以注入 javaweb开发常用的数据共享对象,如:httpservletrequest 、httpservletresponse、httpsession。获取这些共享对象以后,就可以向之前的servlet一样,做任何数据共享以及页面跳转操作

8.数据绑定

  8.1.数据绑定是什么

    springmvc的数据绑定就是将请求带过来的表单数据绑定到执行方法的参数变量。
    实际开发中,springmvc作为表现层框架,肯定会接受前台页面传递过来的参数,springmvc提供了丰富的接受参数的方法

  8.2 接受参数的方法

    1. 使用httpservletrequest对象(c)

  springmvc可以注入httpservletrequest对象,直接使用getparameter()接受参数,但一般不会这种方法,还用这种方法接收参数的话使用springmvc的意义就不大,这种方法了解即可。

<!--  原始方式request.getparameter() -->
    <fieldset>
        <legend> 原始方式request.getparameter()</legend>
        <form action="${pagecontext.request.contextpath}/request/method1.do"
            method="get">
            账号: <input name="username"><br> 
                    年龄: <input name="age"><br>
            <button type="submit">提交</button>
        </form>
    </fieldset>
@requestmapping("/method1")
    public modelandview method1(httpservletrequest request) {
        string username = request.getparameter("username");
        string age = request.getparameter("age");
        
        system.out.println(username);
        system.out.println(age);
        return null;
    }

    2. 方法形参与请求参数同名

    在方法形参上,声明和表单字段名相同的参数名(可以进行自动同名匹配,然后注入)

<fieldset>
    <legend>方法形参与前台参数同名</legend>
    <form action="${pagecontext.request.contextpath}/request/method2.do"
        method="post">
        账号: <input name="username"><br>
            年龄: <input name="age"><br>
        <button type="submit">提交</button>
    </form>
</fieldset>
@requestmapping("/method2")
public modelandview method2(string username, integer age) {
    system.out.println(username);
    system.out.println(age);
    return null;
}

    3.方法形参与请求参数不同名

    方法形参与表单字段名参数名不同是,要使用 @requestparam注解 绑定请求参数到方法参数

<fieldset>
        <legend>方法形参与前台参数不同名</legend>
        <form action="${pagecontext.request.contextpath}/request/method3.do"
            method="post">
            账号: <input name="name"><br> 
                    年龄: <input name="age"><br>
            <button type="submit">提交</button>
        </form>
 </fieldset>
@requestmapping("/method3")
    public modelandview method3(@requestparam("name") string username, integer age) {
        system.out.println(username);
        system.out.println(age);
        return null;
}

    4.接收数组

<fieldset>
        <legend>接收数组或集合</legend>
        <form action="${pagecontext.request.contextpath}/request/method4.do"
            method="post">
            账号: <input name="username"><br> 年龄: <input name="age"><br>
            爱好: <input type="checkbox" name="hobbys" value="java">java <input
                type="checkbox" name="hobbys" value="c">c <input
                type="checkbox" name="hobbys" value="c++">c++<br />
            <button type="submit">提交</button>
        </form>
 </fieldset>
@requestmapping("/method4")
    public modelandview method4(string username, integer age, string[] hobbys) {
        system.out.println(username);
        system.out.println(age);
        system.out.println(arrays.tostring(hobbys));
        return null;
 }

  如果后台接收的属性名与前台不一致需要在数组前面加上@requestparam注解

    5.接收对象

  在实际开发中经常需要把接收的参数封装到javabaen对象中。springmvc提供了直接接收javabaen对象的方式,直接把javabaen对象作为方法的形参,从前台接收到的参数就会自动映射注入到对象中,但必须保证javabaen对象的属性名与从前台接收到的参数名一致,否则就无法映射

package com.gjs.pojo;

import java.util.arrays;

public class user {
    private string username;
    private string password;
    private string email;
    private string phone;
    private string[] hobby;
    public string getusername() {
        return username;
    }
    public void setusername(string username) {
        this.username = username;
    }
    public string getpassword() {
        return password;
    }
    public void setpassword(string password) {
        this.password = password;
    }
    public string getemail() {
        return email;
    }
    public void setemail(string email) {
        this.email = email;
    }
    public string getphone() {
        return phone;
    }
    public void setphone(string phone) {
        this.phone = phone;
    }
    public string[] gethobby() {
        return hobby;
    }
    public void sethobby(string[] hobby) {
        this.hobby = hobby;
    }
    public user() {
        super();
    }
    public user(string username, string password, string email, string phone, string[] hobby) {
        super();
        this.username = username;
        this.password = password;
        this.email = email;
        this.phone = phone;
        this.hobby = hobby;
    }
    @override
    public string tostring() {
        return "user [username=" + username + ", password=" + password + ", email=" + email + ", phone=" + phone
                + ", hobby=" + arrays.tostring(hobby) + "]";
    }
    
}
<fieldset>
        <legend>接受对象,表单参数名必须和后台pojo对象对应的属性名相同</legend>
        <form action="${pagecontext.request.contextpath}/request/method5.do"
            method="get">
            账号: <input name="username"><br> 
            密码: <input    type="password" name="password"><br> 
            邮箱: <input    name="email"><br> 
            电话: <input name="phone"><br>
            爱好:<input type="checkbox" name="hobby" value="java">java
            <input type="checkbox" name="hobby" value="c">c 
            <input type="checkbox" name="hobby" value="c++">c++<br />
            <button type="submit">提交</button>
        </form>
</fieldset>
    //接受对象,直接在方法的参数上面注入pojo对象,pojo对象的属性和表单的参数名必须一样
    @requestmapping("/method5")
    public modelandview method5(user user) {
        system.out.println(user);
        return null;
    }

    6.接受参数封装成map集合

  有的时候我们需要接收多个参数,但又不想使用对象接收,这时可以用map集合接收。只需要把map集合作为方法参数注入然后在map参数前面加上@requestparam 注解即可, springmvc在接受表单参数时候回自动创建一个map集合, 并且把表单的参数名作为map的key,参数值作为map的value。使用map集合可以接受任意个数的参数,但需要注意map只能接受单个值的参数,接收数组类型的参数只会接收第一个元素

    <fieldset>
        <legend>接受参数封装成map集合</legend>
        <form action="${pagecontext.request.contextpath}/request/method6.do" method="post">
            账号: <input name="username"><br>
            密码: <input name="password"><br>
            邮箱: <input name="email"><br>
            电话: <input name="phone"><br>
            爱好:<input type="checkbox" name="hobby" value="java">java
            <input type="checkbox" name="hobby" value="c">c 
            <input type="checkbox" name="hobby" value="c++">c++<br />
            <button type="submit">提交</button>
        </form>
    </fieldset>
    @requestmapping("/method6")
    public modelandview method6(@requestparam map<string, object> paramsmap) {
        system.out.println(paramsmap);
        return null;
    }

  7.restful风格支持

  restful介绍:

  rest(英文:representational state transfer,简称rest)描述了一个架构样式的网络系统,比如 web 应用程序。它首次出现在 2000 年 roy fielding 的博士论文中,他是 http 规范的主要编写者之一。在目前主流的三种web服务交互方案中,rest相比于soap(simple object access protocol,简单对象访问协议)以及xml-rpc更加简单明了,rest都倾向于用更加简单轻量的方法设计和实现。值得注意的是rest并没有一个明确的标准,而更像是一种设计的风格。
  restful一种软件架构风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

  参数传递方法 get

例如:根据商品id查询对应的商品信息(京东网站)
如果按照我们web开发应该是将商品id通过get方法跟在地址后面
普通方式 https://item.jd.com?product_id=100000287117 京东不支持
但是京东不是使用的此种方式,使用的 restful风格
restful风格 : https://item.jd.com/100000287117.html

  示例代码:

    @pathvariable用于将请求url中的模板变量(动态参数)映射到功能处理方法的参数上。

// restful风格
@requestmapping(value = "/method7/{product_id}.html")
public modelandview method7(@pathvariable("product_id") integer product_id) {
system.out.println(product_id);//1231323123
return null;
}

  访问地址:localhost:8080/springmvc/request/method7/1231323123.html
     注:.html 的url会被tomcat当做静态资源处理了,所以配置springmvc的前端控制器时映射路径要陪 / ,然后再配置开启对静态资源的访问 <mvc:default-servlet-handler/>

  使用restful优势

1.可以让页面伪静态,页面访问感觉像在访问静态html页面,实际上访问时动态页面(伪静态)
2.方便搜索引擎的seo优化(html页面在搜索引擎搜索结果比较靠前)

 

9.请求中文乱码问题

  springmvc默认接受的参数是iso-8859-1编码参数,单字节,不支持中文。spring提供了一个过滤器 org.springframework.web.filter.characterencodingfilter 可以让开发者自定义请求参数的字符编码。
  在web.xml中配置过滤器

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

  如果是get方式还需要修改tomcat的配置:修改tomcat/conf/server.xml,在<connector> 标签中添加属性usebodyencodingforuri="true"(tomcat 8之后版本可不改,默认就是utf-8)
  usebodyencodingforuri="true":是否设置用request的字符集对url提交的数据和表单中get方式提交的数据进行重新编码

10.响应传值方式

  10.1使用原始servlet的请求和响应对象进行页面跳转和数据共享

    @requestmapping("method1")
    public void method1(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
        //数据共享
        request.setattribute("username", "张三");
        
        //请求转发
        //request.getrequestdispatcher("/web-inf/response.jsp").forward(request, response);
        
        //url重定向(可以跨域访问)
        response.sendredirect("http://www.baidu.com");
    }

  10.2返回modelandview类型进行页面跳转和数据共享

    modelandview :模型和视图。spring提供此对象可以集中管理共享数据操作和设置跳转视图操作。但 modelandview 只能使用请求转发。

    @requestmapping("method2")
    public modelandview method2() {
        modelandview mv = new modelandview();
        mv.addobject("username", "李四");    //数据共享
        mv.setviewname("/web-inf/response.jsp");//设置视图地址
        return mv;
    }

  10.3 通过model方式-设置共享数据

    直接将需要共享的数据封装到model对象,方法返回值(string字符串)为需要跳转的地址。 默认使用请求转发

    @requestmapping("method3")
    public string method3(model m) {
        m.addattribute("username", "王五");    //数据共享
        return "/web-inf/response.jsp";        //返回视图地址
    }

  10.4 配置视图解析器

  视图解析器的配置

<!-- 配置springmvc的视图解析器 -->
    <bean class="org.springframework.web.servlet.view.internalresourceviewresolver">
        
        <!-- 配置视图前缀 -->
        <property name="prefix" value="/web-inf/"/>
        
        <!-- 配置视图后缀 -->
        <property name="suffix" value=".jsp"/>
    
    </bean>

  配置视图解析器后的代码

    controller方法返回字符串表示逻辑视图名,通过视图解析器解析为物理视图地址。
    此时默认的物理视图地址为:视图前缀+逻辑视图名称+视图后缀

    @requestmapping("method2")
    public modelandview method2() {
        modelandview mv = new modelandview();
        mv.addobject("username", "李四");        //数据共享
        //配置视图解析器之前
        //mv.setviewname("/web-inf/response.jsp");//设置视图地址
        //配置视图解析器之后:配置一个逻辑视图名称
        mv.setviewname("response");
        return mv;
    }
    
    
    @requestmapping("method3")
    public string method3(model m) {
        m.addattribute("username", "王五");    //数据共享
        //配置视图解析器之前
        //return "/web-inf/response.jsp";        //返回视图地址
        //配置视图解析器之后:返回一个逻辑视图名称
        return "response";
    }

  10.5 自定义请求转发和重定向跳转的页面

如果直接使用视图解析器的配置开发,那么必须保证视图解析器前缀目录下面有对应的页面文件才能跳转,否则报错。
默认页面跳转也只能使用请求转发跳转,不能使用重定向 需要解决问题: 除了使用视图解析器对应规则的开发,用户还得自定义跳转方式,和自定义跳转页面 方案:
使用视图解析器的 请求转发和重定向配置,可以打破默认的规则
spring源码:

public static final string redirect_url_prefix = "redirect:"; 
public static final string forward_url_prefix = "forward:";

重定向:redirect:
请求转发:forward:

示例代码:

    // 自定义请求转发页面跳转的地址 : forward: 跳转的地址
    @requestmapping("method4")
    public string method4(model m) {
        m.addattribute("username", "赵六");
        return "forward:/web-inf/response.jsp";    
    }
    
    // 自定义重定向页面跳转的地址 redirect: 跳转的地址
    @requestmapping("method5")
    public string method5(model m) {
        return "redirect:http://www.baidu.com";    
    }

  10.6 返回对象进行页面跳转和数据共享

  返回对象默认使用就是请求转发,跳转的页面规则 :视图解析器前缀 + 模块名+@requestmapping的值 + 后缀。返回的对象即共享的数据,共享的名称默认为对象类型的首字母小写。可以使用@modelattribute("设置共享模型的属性名称")

    @requestmapping("method6")
    @modelattribute("userkey") //设置共享模型的属性名称
    public user method6() {
        user user = new user("马七","123", "10000@qq.com", "1", null);
        return user;
    }

  

  10.7 转换json数据

在web开发中,前台页面经常会发送ajax请求从后台请求数据,ajax请求给前台的数据一般都是json 数据。
springmvc支持自动将对象转换json格式的数据响应给客户端
springmvc默认使用的是 jackson 作为对象转json的工具

先导入jackson的jar包
下载地址:https://mvnrepository.com/search?q=jackson

      

    使用@responsebody注解方法的返回值会以字符串的形式返回,springmvc会自己调用jackson 把对象转换成json字符串

@requestmapping("/getobjectbyjson")
    @responsebody //将方法的返回值以字符串的形式返回
    public user getobjectbyjson() {
        user user = new user();
        user.setusername("小明");
        user.setpassword("123");
        user.setphone("135xxxx");
        user.setemail("xiaoming@qq.com");
        return user;
    } 

    @requestmapping("/getlisttbyjson")
    @responsebody 
    public list<user> getlistbyjson() {
        
        list<user> users = new arraylist<>();
        for (int i = 0; i < 10; i++) {
            user user = new user();
            user.setusername("小明 : "+i);
            user.setpassword("123 :"+i);
            user.setphone("135xxxx :"+i);
            user.setemail( "xiaoming@qq.com");
            users.add(user);
        }
        
        return users;
    }

11. 文件上传

  在web开发中一般都会有文件上传的操作
  一般在javaweb开发中文件上传使用的 apache组织的commons fileupload组件
  springmvc中使用 multipartfile file对象接受上传文件,必须保证 后台参数的名称和表单提交的文件的名称一致
  文件上传必须条件
    1.表单必须post
    2.表单必须有 file 文件域
    3.表单的 enctype="multipart/form-data"

  11.1 单个文件上传    

    步骤:
    1.导入相关jar包

    

 

     

    2.在springmvc.xml中配置上传解析器
    property的value用来设置上传文件的最大尺寸,其他配置为固定配置

<!-- 配置文件上传解析器:bean的名字是固定的,底层使用的名称注入 -->
<bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver">
<!-- 设置上传文件的最大尺寸为1mb -->
<property name="maxuploadsize" value="#{1024 * 1024}"></property>
</bean>

    3.jsp代码

<fieldset>
        <legend>单个文件上传</legend>
        <form action="${pagecontext.request.contextpath}/upload.do" method="post" enctype="multipart/form-data">
            姓名: <input name="username"><br>
            头像: <input type="file" name="headimg"><br>
            <button type="submit">提交</button>
        </form>
    </fieldset>
<fieldset>

    4.后台代码
    springmvc中使用 multipartfile对象接受上传文件,必须保证 后台方法multipartfile 参数的名称和表单提交的文件的名称一致

 

     //springmvc中使用  multipartfile对象接受上传文件,必须保证 后台参数的名称和表单提交的文件的名称一致
        @requestmapping("/upload")
        public string singleupload(multipartfile headimg,@requestparam("username")string username) throws ioexception {
             
            system.out.println(headimg.getname());//获取上传文件的表单参数名称 
            
                    system.out.println(headimg.getcontenttype());//mime类型:如html的mime类型为text/html,用于确定文件属于哪一类型的
            system.out.println(headimg.getsize());//文件大小
            system.out.println(headimg.getoriginalfilename());//获取上传文件的完整名称
            //获取上传文件对应的输入流
            //inputstream in = headimg.getinputstream();
            
            //创建一个磁盘目录(文件夹)用于保存文件
            file destfile= new file("d:/upload");
            if(!destfile.exists()) {    //判断文件夹是否存在
                destfile.mkdir();
            }
            //使用uuid作为文件随机名称
            string filename = uuid.randomuuid().tostring().replaceall("-", "");
            //使用filenameutils获取上传文件名的后缀
            string extension = filenameutils.getextension(headimg.getoriginalfilename());// jpg , png 等等
            //创建新的文件名称
            string newfilename = filename + "."+extension;
             
            //创建要保存文件的file对象
            file file = new file(destfile, newfilename);
            //保存文件到本地磁盘
            headimg.transferto(file);
            
            return "redirect:/upload.jsp";
        }

  11.2 多文件上传

  <fieldset>
        <legend>多个文件上传</legend>
        <form name="files" action="${pagecontext.request.contextpath}/uploads.do" method="post" enctype="multipart/form-data">
            文件1: <input type="file" name="headimgs"><br>
            文件2: <input type="file" name="headimgs"><br>
            文件3: <input type="file" name="headimgs"><br>
            <button type="submit">提交</button>
        </form>
    </fieldset>
        @requestmapping("/uploads")
        public string singleuploads(multipartfile[] headimgs) throws  ioexception {
            //创建一个磁盘目录(文件夹)用于保存文件
            file destfile= new file("d:/upload");
            if(!destfile.exists()) {    //判断文件夹是否存在
                destfile.mkdir();
            }
            
            if(headimgs!=null) {
                for (multipartfile headimg : headimgs) {
                    //使用uuid作为文件随机名称
                    string filename = uuid.randomuuid().tostring().replaceall("-", "");
                    //使用filenameutils获取上传文件名的后缀
                    string extension = filenameutils.getextension(headimg.getoriginalfilename());// jpg , png 等等
                    //拼接新的文件名称
                    string newfilename = filename + "."+extension;
                    
                    //创建要保存文件的file对象
                    file file = new file(destfile, newfilename);
                    
                    //保存文件到本地磁盘
                    headimg.transferto(file);
                    
                    
                }
            }
            return "redirect:/upload.jsp";
        
        }

12.文件下载

  文件下载,springmvc并没有做过多的封装,还是使用原来的下载方式
  下载文件思路:
    1. 接受需要下载文件名称,根据文件名称,找到磁盘对应的文件,读取到内存中形成一个输入流
    2. 将输入流通过响应对象(httpservletresponse)响应给浏览器(下载)

  @requestmapping("/download")
    public void download(string filename,httpservletresponse response) throws ioexception {
            
        //通过接受到的文件名从磁盘中读取对应文件
        fileinputstream input = new fileinputstream("d:/"+filename);
            
        //获取响应对象的输出流
        servletoutputstream output = response.getoutputstream();
            
        //将文件名的编码转为iso-8859-1编码(响应头编码),否则传给浏览器的文件名中文会乱码
        byte[] bytes = filename.getbytes("utf-8");
        filename= new string(bytes, "iso-8859-1");
            
        //响应内容以附件的形式响应给浏览器,并设置文件名
        response.setheader("content-disposition", "attachment;filename="+filename);
            
        //响应文件给浏览器
        ioutils.copy(input, output);
            
    }

13.springmvc的拦截器

  拦截器 (interceptor):spring mvc 的拦截器类似于servlet 开发中的过滤器filter,用于对controller进行预处理和后处理。拦截器只会拦截控制器请求,不会拦截jsp页面。
  使用springmvc拦截器步骤:
    1.定义拦截器类,实现接口 org.springframework.web.servlet.handlerinterceptor
    2.在applicationcontext.xml中配置拦截器

  13.1 定义拦截器

    拦截器方法的执行时机:
      1.prehandle:控制器方法执行之前执行,返回结果为true表示放行,如果返回为false,表示拦截(可以做权限拦截,登录检查拦截).
      2.posthandle:控制器方法执行后,视图渲染之前执行(可以加入统一的响应信息).
      3.aftercompletion:视图渲染之后执行(处理controller异常信息,记录操作日志,清理资源等)

/**
 * 验证登录拦截器
 */
public class checklogininterceptor implements handlerinterceptor{

    /*
     * 控制器方法执行之前执行
     * 返回结果为true表示放行,如果返回为false,表示拦截(可以做权限拦截,登录检查拦截).
     */
    @override
    public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler)
            throws exception {
        //获取session中的user对象
        user user = (user)request.getsession().getattribute("user");
        
        if(user==null) {    //user==null表示为登录
            //重定向跳转到登录页面 login.jsp
            response.sendredirect(request.getcontextpath()+"/login.jsp");
            return false;    //拦截请求
        }
        return true;        //放行
    }

    @override
    public void posthandle(httpservletrequest request, httpservletresponse response, object handler,
            modelandview modelandview) throws exception {
        // todo auto-generated method stub
    }

    @override
    public void aftercompletion(httpservletrequest request, httpservletresponse response, object handler, exception ex)
            throws exception {
        // todo auto-generated method stub
    }
}

  13.2 配置拦截器

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
    xsi:schemalocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        ">
    <!-- 开启springmvc注解驱动 -->
    <mvc:annotation-driven/>
    
    <!-- 配置拦截器 -->
    <mvc:interceptors>
        <!-- 配置登录检查拦截器 -->
        <mvc:interceptor>
            <!-- 拦截的地址(只会拦截 控制器请求,不会拦截jsp页面)
                /*:只能拦截一级, 如:login.do
                /**:可以拦截多级,如:a/b/c/d/login.do
             -->
            <mvc:mapping path="/**"/>
            
            <!-- 排除拦截的地址,多个地址使用逗号隔开 -->
            <mvc:exclude-mapping path="/user/login.do"/>
            
            <!-- 自定义的拦截器 -->
            <bean class="com.gjs.ssm.interceptor.checklogininterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

14. 使用poi组件导出excel文件

  14.1 导入jar包

    

  14.2 示例代码

// 导出用户信息
@requestmapping("/exprot")
public void export(httpservletresponse response) {
//创建poi的数据对象 工作集
hssfworkbook book = new hssfworkbook();
//创建sheet
hssfsheet sheet = book.createsheet();
//创建行(索引从0开始,表示第一行)
hssfrow titlerow = sheet.createrow(0);
//使用行创建列并设置数据(索引从0开始,表示第一列)
titlerow.createcell(0).setcellvalue("编号");
titlerow.createcell(1).setcellvalue("姓名");
titlerow.createcell(2).setcellvalue("邮箱");
titlerow.createcell(3).setcellvalue("电话");
list<user> users = service.list();
//循环集合,每一条数据创建一行,并把对应的值设置列中
for (int i = 0; i < users.size(); i++) {
user user = users.get(i);
//创建行
hssfrow row = sheet.createrow(i+1);
//创建列,并将学生信息设置到对应列中
row.createcell(0).setcellvalue(user.getid());
row.createcell(1).setcellvalue(user.getname());
row.createcell(2).setcellvalue(user.getemail());
row.createcell(3).setcellvalue(user.getphone());
}
try {
//设置响应头,响应的内容是为附件形式
response.addheader("content-disposition",
"attachment;filename=" + new string("学生信息.xlsx".getbytes(), "iso-8859-1"));
book.write(response.getoutputstream());
} catch (exception e) {
e.printstacktrace();
}
}

15. springmvc 控制器 controller的生命周期

spring 容器创建的对象默认是单例对象。可以通过@scope注解来设置
springmvc对象 controller的对象的创建有三种情况:
  默认:单例,仅在服务器启动时创建,并一直存在
  request : 在用户的一次请求中生效(用户每次请求都会创建controller对象)多例
  session : controller对象在一次会话中创建一个对象

如果控制器中有成员变量 设置或者赋值操作,必须使用 request 返回

   

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网