SpringMVC学习

一、SpringMVC概述

概念: 实现mvc 模式的控制层框架,spring框架下的一个独立子框架(子模块)

二、入门程序

  •    新建maven项目导入springmvc特有的依赖
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
  • 在web.xml中配置用来分发到不同controller的分发servlet
<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>  // 告诉系统springmvc controller的配置文件在哪里
        </init-param>
        <load-on-startup>1</load-on-startup>  // web站点一启动就加载
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>  
        <url-pattern>/</url-pattern>  // 拦截一切路径
    </servlet-mapping>
  •  手动创建springmvc的配置文件    
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
    
    <!--去哪里扫描controller bean-->
    <context:component-scan base-package="com.qf.mvc01.controller"/>

    <!--声明路径和 controller 关系 通过注解 驱动获得-->
    <mvc:annotation-driven></mvc:annotation-driven>
  •  配置视图解析器
<!--配置视图解析器 的bean-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/"/>  // 前缀是/
    <property name="suffix" value=".jsp"/>  // 后缀是.jsp
</bean>

  • 程序
@Controller
public class TestController {

    @RequestMapping("/sayhello")
    public ModelAndView sayHello(String name){
        System.out.println(name + ":hello");
        
        ModelAndView mv = new ModelAndView();
        //  回传给jsp 的数据
        // 相当于 request.setArr
        mv.addObject("msg",name+":hello");
        // 回到哪里去
        // 相当于 request.getDisptach("path").forward
        // 他会加上视图解析器种前缀和后最  /index.jsp
        mv.setViewName("index");
        return mv;
    }
}

三、请求传参

  • request传参
@RequestMapping("/testp01")
public ModelAndView testp01(HttpServletRequest request){
    System.out.println(request.getParameter("name"));
    return null;
}
  • 直接传参
@RequestMapping("/sayhello")
public ModelAndView sayHello(String name){
    System.out.println(name + ":hello");

    return null;
}
  • 直接传参但是页面name 和 参数名字不一样

@RequestMapping("/testp02")
public ModelAndView testp02(@RequestParam("name1") String name){
    System.out.println(name);
    return null;
}
  • 传对象
// 1 创建对象
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class User {

    private String name;
    private Integer age;
}

// 2 jsp 页面上传第对象
3: 直接传对象 <br>
<form action="testp03">
    <input type="text" name="name" >
    <input type="text" name="age" >
    <input type="submit" value="say hello">
</form>

// 3 controller 种接收 对象
@RequestMapping("/testp03")
public ModelAndView testp03(User user){
    System.out.println(user);
    return null;
}
  • 路径传参
<a href="testp04/123">路劲传参1</a>
<a href="testp04/456">路劲传参2</a>

// controller
@RequestMapping("/testp04/{id}")
public ModelAndView testp04(@PathVariable("id") Integer num){
    if(num==123)
     {
       System.out.println("我是1号技师");
     }else if(num==456)
     {
       System.out.println("我是2号技师");
     }
    return null;
}
  • 传参乱码问题

1.post请求

<!--配置乱码过滤器  这个只 会处理post 请求-->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

2.get请求

tomcat8.0 以上不用管了

tomcat8.0 以下: 设置tomcat 的uriencoding=utf-8

<plugin>
 <groupId>org.apache.tomcat.maven</groupId>
 <artifactId>tomcat7-maven-plugin</artifactId>
 <version>2.2</version>
 <configuration>
     <port>8081</port>
     <path>/</path>
     <uriEncoding>utf-8</uriEncoding>
 </configuration>
</plugin>
  • 时间格式传参
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class User {

  private String name;
  private Integer age;
  @DateTimeFormat(pattern = "yyyy-MM-dd")
  private Date birthday;

}

@RequestMapping("/testp06")
public ModelAndView testp06(String name, Integer age,
                      @DateTimeFormat(pattern = "yyyy-MM-dd") Date birthday){
  System.out.println(birthday);
  return null;
}

四、响应

前后端不分离的响应(官方标准写法)

@RequestMapping("/sayhello")
public ModelAndView sayHello(String name){
    System.out.println(name + ":hello");

    ModelAndView mv = new ModelAndView();
    //  回传给jsp 的数据
    // 相当于 request.setArr
    mv.addObject("msg",name+":hello");
    // 回到哪里去
    // 相当于 request.getDisptach("path").forward
    // 他会加上视图解析器种前缀和后最  /index.jsp
    mv.setViewName("index");
    return mv;
}
  • 常用写法
@RequestMapping("/sayhello01")
/**
 * 返回值  要回到的页面(视图解析器的前后缀的一样的生效)
 * map : 往页面上回传的值 放在map 中
 */
public String sayHello01(String name, ModelMap map){
    // 1 打印页面上传来的参数
    System.out.println(name + ":hello");
    // 2 要回传(给页面的值)
    map.put("message",name+": hello");
    // 3 要回到哪里去
    return "index";  // 注意这里,因为我前面配置了视图解析器
}
  • 默认就是转发的新式,下面我门看重定向
@RequestMapping("/sayhello01")
/**
 * 返回值  要回到的页面(视图解析器的前后缀的一样的生效)
 * map : 往页面上回传的值 放在map 中
 */
public String sayHello01(String name, ModelMap map){
    // 1 打印页面上传来的参数
    System.out.println(name + ":hello");
    // 2 要回传(给页面的值)
    map.put("message",name+": hello");
    // 3 要回到哪里去
    // 加上redirect关键字  视图解析器中配置的 前后锥就不起作用了
    return "redirect:/index.jsp";
}

前后端分离写法

  • 导入依赖
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
</dependency>
  • 设置跨域问题
/**
 *  返回异步请求的json数据
 *  前后端不分离的话 controller 的返回值要么ModelAndView 要么时String 
 *  如果是前后端分离的方式 我们的返回值可以是任何对象 springmvc 的框架可以自动把这个对象转成json返回
 */
@CrossOrigin("*")
@RequestMapping("/testjson")
@ResponseBody  //把返回值  在最后变成json 然后写回去
public User testJson(){
    User user = User.builder().age(18)
            .name("zoukx")
            .birthday(new Date()).build();
    return user;
}
  • 写一个前端代码来拿,按F12打开控制台即可看到
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./lib/jquery-1.11.0.js"></script>
</head>
<body>
    <input type="button" value="点我" id="but">
</body>
    <script>
        $("#but").on("click",function()
        {
            var url="http://localhost:8081/kkk"
            $.post(url,null,function(jsondata){
               console.log(jsondata)
            },"json")
        })
    </script>
</html>

五、SpringMVC的工作流程

  1. 用户发送请求到前端控制器DispatcherServlet
  2. DispatcherSevlet收到请求调用HandlerMapping处理器映射
  3. 处理器映射器根据请求url找到具体的服务器,生成处理器对象及拦截器(如果有则生成)一并返回给DispatcherServlet
  4. DispatcherServlet通过HandlerAdapter适配器调用处理器
  5. 执行处理器(Controller,也叫后端控制器
  6. Controller执行完返回ModelandView
  7. HandlerAdapter将Cotroller执行结果返回给DispatcherServlet
  8. DispatcherServlet将ModelandView返回给视图解析器
  9. 视图解析器解析后返回具体的View
  10. DispatcherServlet对View进行渲染视图
  11. DispatcherServlet响应用户
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农小唐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值