Spring MVC学习笔记和SSH的整合

1. Spring MVC

Spring MVC 是目前主流的实现MVC设计模式的企业级开发框架,Spring框架的一个子模块,无需整合,开发起来更加便捷。

 

2. 什么是MVC

  • Controller
  • Model
  • View

 

3. SpringMVC的核心组件

  • DispatcherServler 前置控制器,相当于总调度。
  • Handler 处理器,相当于Servler或Action。
  • HandlerMapping 相当于路由交换。
  • handlerIntercepetor 处理器拦截器。
  • HandlerExecutionChain 处理器执行链。
  • HandlerAdapter 处理适配器
  • ModelAndView装载了模型数据和视图信息。
  • ViewResouler 视图解析器。

 

4. Spring MVC 的工作流程。

客户端请求被DispatcherServlet 接收

根据HandlerMapping 映射到 Handler。

生成Handler 和HandlerInterceptor。

Handler 和HandletInterceptor 。。

 

Spring MVC学习笔记和SSH的整合_第1张图片

 

5. 创建项目及入门程序

Spring MVC学习笔记和SSH的整合_第2张图片

1. 配置web.xml 的servlet接收请求




    Archetype Created Web Application

    
        dispatcherServlet
        org.springframework.web.servlet.DispatcherServlet

        
            contextConfigLocation
            classpath:springmvc.xml
        
    

    
        dispatcherServlet
        /
    


 

2.新建springmvc.xml 配置文件






    

    
    
        
        
        
        
    

  1. 新建handler
package com.liyong.controller;

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

// 注册为handler
@Controller
@RequestMapping("/hello")
public class HelloController {

    // url 映射
    @RequestMapping(path = "/index")
    public String sayHello() {
        System.out.println("执行了index");
        return "index";
    }
}

 

6. Spring 注解

 

  • @Controller 在类定义处添加,结合spring 的loc自动扫描使用。
  • @RequestMapping 该注解将url请求和业务方法进行映射,在类和方法前都可以添加。
    • value 指定url 的实际地址,也是requestMapping的默认值
    • method 指定请求的method 类型。
    • params 指定请求中必须包含某些参数,否则无法访问
@RequestMapping(path = "/params", params = {"name", "id"})
@ResponseBody
public String params(@RequestParam("name") String name, @RequestParam("id") Integer id) {
    System.out.println(name);
    System.out.println(id);
    return "name" + name + " id" + id;
}

// 接收对象。
// 默认接收中文 会乱码,需要增加filter
@RequestMapping(value = "/submit", method = RequestMethod.POST)
@ResponseBody
public String submit(User user) {
    return "name:" + user.getName() + " id:" + user.getId();
}

 

    • @CookieValue 获取cookie 值
@RequestMapping("/getCookie")
@ResponseBody
public String index2(@CookieValue(value = "JSESSIONID") String test1) {
    return test1;
}
  • @RequestParam("name") 注解在形参上,代表当前形参和params 对应。
    • requried 是否必传
    • value 参数名 代表参数key
    • defaultValue 默认值
  • @RequestBody 代表这个请求是返回响应对象而非视图解析器
  • @PathVariable 表示获取路径参数
  • @RestController 表示处理器会把返回数据直接返回给客户端,不经过视图响应,注解在类上。
  • @RequestBody 打在参数上,获取json数据
  • @GetMpapping 表示get请求
  • @PostMapping 表示post请求
  • @PutMapping 表示put 请求
  • @DeleteMapping 表示delete 请求

 

7. Spring MVC数据绑定

 

数据绑定:在后端业务方法中直接获取客户端HTTP请求中的参数,将请求参数映射到业务方法的形参中,springMVC 的数据绑定是由HandlerAdaptter 来完成的。

 

基本数据类型

@RequestMapping("/baseType")
@ResponseBody
public String baseType(int id){
    return id + "";
}

包装类

包装类可以接受null。

@RequestMapping("packageType")
@ResponseBody
public String packageType(Integer id){
    return id + "";
}

List (content-type 为 x-www-urlencoded)

  1. 增加entity 类,必须具备构造方法和set 方法。
package com.liyong.entity;

public class User {
  private Integer id;
  private String name;

  public User() {
  }

  public User(Integer id, String name) {
    this.id = id;
    this.name = name;
  }

  public Integer getId() {
    return id;
  }

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

  public String getName() {
    return name;
  }

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

  @Override
  public String toString() {
    return "User{" +
      "id=" + id +
      ", name='" + name + '\'' +
      '}';
  }
}
  1. 增加方法入参
@RequestMapping(value = "/list", method = RequestMethod.POST)
@ResponseBody
public String postList(UserList userList) {
    return userList.toString();
}

Map(content-type 为 x-www-urlencoded)

  1. 封装mapentity类
package com.liyong.entity;

import java.util.Map;

public class UserMap {
    private Map userMap;

    public UserMap(Map userMap) {
        this.userMap = userMap;
    }

    public UserMap() {
    }

    public Map getUserMap() {
        return userMap;
    }

    public void setUserMap(Map userMap) {
        this.userMap = userMap;
    }

    @Override
    public String toString() {
        return "UserMap{" +
                "userMap=" + userMap +
                '}';
    }
}
  1. 编写handler处理逻辑
@RequestMapping(value = "/map", method = RequestMethod.POST)
@ResponseBody
public String postMap(UserMap userMap) {
    return userMap.getUserMap().toString();
}

 

JSON:java默认无法直接把json 转换为 java对象

  1. 安装fastjson
  2. 配置再springmvc.xml 中




    
    

    
    
        
        
        
        
    

    
    
        
        
            
                
            

            
            
                
                    
                        application/json
                        application/json;charset=UTF-8
                        application/atom+xml
                        application/x-www-form-urlencoded
                        application/octet-stream
                        application/pdf
                        application/rss+xml
                        application/xhtml+xml
                        application/xml
                        image/gif
                        image/jpeg
                        image/png
                        text/event-stream
                        text/html
                        text/markdown
                        text/plain
                        text/xml
                    
                
            
        
    


  1. 接收json
@RequestMapping(value = "/json", method = RequestMethod.POST)
@ResponseBody
public User postJson(@RequestBody User user) {
    System.out.println(user);
    user.setId(223);
    user.setName("哈哈哈");
    return user;
}

8. Response 响应和Request

  1. 安装servlet

  javax.servlet
  javax.servlet-api
  4.0.1
  provided
  1. 设置content-type 和 增加cookie
 @RequestMapping("/cookiePage")
  @ResponseBody
  public String cookiePage(HttpServletResponse res) {
    res.addCookie(new Cookie("hello", "123"));
    res.setContentType("text/json;charset=UTF-8");
    return "你好啊";
  }

Spring MVC学习笔记和SSH的整合_第3张图片

 

9. REST 架构

  • get 获取资源
  • post 新增资源
  • put 修改资源
  • delete 删除资源

 

其他

增加filter 解决请求中文乱码问题,在web.xml中添加 spring 自带的 filter 做encoding

  
  
    characterEncodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
      encoding
      utf-8
    
  

  
  
    characterEncodingFilter
    /*
  

 

Rest 增删查改

  1. 编写DAO和实现类
package com.liyong.dao;

import com.liyong.entity.User;

import java.util.Collection;
import java.util.List;

public interface UserDAO {
    String create(User user);

    Collection findAllUser();

    User findUserById(Integer id);

    String deleteUserById(Integer id);

    String updateUserById(Integer id, User user);
}

package com.liyong.dao;

import com.liyong.entity.User;
import com.liyong.entity.UserMap;
import org.springframework.stereotype.Repository;

import java.util.*;


@Repository
public class UserDAOImpl implements UserDAO {

    private static Map userMap;

    static {
        System.out.println("UserDAOImpl static");
        userMap = new HashMap();
        userMap.put(1, new User(1, "李先生"));
        userMap.put(2, new User(2, "憨憨刘"));
    }

    @Override
    public String create(User user) {
        userMap.put(userMap.size() + 1, user);
        return "success";
    }

    @Override
    public Collection findAllUser() {
        return userMap.values();
    }

    @Override
    public User findUserById(Integer id) {
        return userMap.get(id);
    }

    @Override
    public String deleteUserById(Integer id) {
        userMap.remove(id);
        return "success";
    }

    @Override
    public String updateUserById(Integer id, User user) {
        userMap.put(id, user);
        return "success";
    }
}

  1. 编写services 和实现类
package com.liyong.services;

import com.liyong.entity.User;

import java.util.Collection;

public interface UserServices {
    String create(User user);

    Collection findAllUser();

    User findUserById(Integer id);

    String deleteUserById(Integer id);

    String updateUserById(Integer id, User user);
}


package com.liyong.services;


import com.liyong.dao.UserDAOImpl;
import com.liyong.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
public class UserServicesImpl implements UserServices {

    @Autowired
    private UserDAOImpl userDAOImpl;

    @Override
    public String create(User user) {
        return userDAOImpl.create(user);
    }

    @Override
    public Collection findAllUser() {
        return userDAOImpl.findAllUser();
    }

    @Override
    public User findUserById(Integer id) {
        return userDAOImpl.findUserById(id);
    }

    @Override
    public String deleteUserById(Integer id) {
        return userDAOImpl.deleteUserById(id);
    }

    @Override
    public String updateUserById(Integer id, User user) {
        return userDAOImpl.updateUserById(id, user);
    }
}
  1. 编写处理器
package com.liyong.controller;

import com.liyong.entity.User;
import com.liyong.services.UserServicesImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@RestController
@RequestMapping("/api/user")
public class UserRESTController {

    @Autowired
    private UserServicesImpl userServices;

    @PostMapping("/createUser")
    public String create(@RequestBody User user) {
        return userServices.create(user);
    }

    @GetMapping("/findAllUser")
    public Collection findAllUser() {
        return userServices.findAllUser();
    }

    @GetMapping("/findUser/{id}")
    public User findUserById(@PathVariable Integer id) {
        return userServices.findUserById(id);
    }

    @DeleteMapping("/deleteUser/{id}")
    public String deleteUserById(@PathVariable Integer id) {
        return userServices.deleteUserById(id);
    }

    @PutMapping("/updateUserById/{id}")
    public String updateUserById(@PathVariable Integer id, @RequestBody User user) {
        return userServices.updateUserById(id, user);
    }
}

 

10. 文件的上传和下载

 

文件上传

底层采用 apache fileupload

 

1. 增加依赖


  commons-io
  commons-io
  2.5



  commons-fileupload
  commons-fileupload
  1.3.3

2. springmvc.xml 中增加上传组件的配置





    
    

    
    
        
        
        
        
    

    
    
        
        
    

    
    
        
        
            
                
            

            
            
                
                    
                        application/json
                        application/json;charset=UTF-8
                        application/atom+xml
                        application/x-www-form-urlencoded
                        application/octet-stream
                        application/pdf
                        application/rss+xml
                        application/xhtml+xml
                        application/xml
                        image/gif
                        image/jpeg
                        image/png
                        text/event-stream
                        text/html
                        text/markdown
                        text/plain
                        text/xml
                    
                
            
        
    


3. 接收文件上传

package com.liyong.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/api/file")
public class FileController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(MultipartFile file, HttpServletRequest req) throws IOException {
        System.out.println(file);
        if (file == null || file.getSize() == 0) {
            return "failed";
        }
        // 获取servlet context 下的file 文件路径
        String servletPath = req.getSession().getServletContext().getRealPath("file");
        // 获取文件名
        String name = file.getOriginalFilename();

        // 新建文件
        File file1 = new File(servletPath, name);
        // 写入到文件
        file.transferTo(file1);

        return "success";
    }

}

Spring MVC学习笔记和SSH的整合_第4张图片

 

文件下载

@RequestMapping("/download")
public String download(HttpServletRequest req, HttpServletResponse res) throws IOException {
    String path = req.getSession().getServletContext().getRealPath("file");
    FileInputStream in = new FileInputStream(path + "\\QQ浏览器截图20200728231741.png");

    res.setHeader("Content-Type", "application/x-msdownload");
    res.setHeader("Content-Disposition", "attachment; filename=123.png");

    ServletOutputStream outputStream = res.getOutputStream();
    outputStream.flush();

    outputStream.flush();
    int aRead = 0;
    byte b[] = new byte[1024];
    while ((aRead = in.read(b)) != -1 & in != null) {
        outputStream.write(b, 0, aRead);
    }
    outputStream.flush();
    in.close();
    outputStream.close();
    return "1";
}

 

 

11. SSM的整合

spring 和spring MVC 和Mybatis 的整合

Spring MVC学习笔记和SSH的整合_第5张图片

 

1. 增加依赖




    4.0.0

    org.example
    springSSM
    1.0-SNAPSHOT
    war

    springSSM Maven Webapp
    
    http://www.example.com

    
        UTF-8
        1.7
        1.7
    

    
        
            junit
            junit
            4.11
            test
        

        
        
            org.springframework
            spring-webmvc
            5.0.11.RELEASE
        
        
        
            org.springframework
            spring-jdbc
            5.0.11.RELEASE
        
        
        
            org.springframework
            spring-aop
            5.0.11.RELEASE
        
        
        
            org.springframework
            spring-aspects
            5.0.11.RELEASE
        
        
        
            mysql
            mysql-connector-java
            8.0.11
        
        
            org.projectlombok
            lombok
            1.18.6
            provided
        

        
        
            org.mybatis
            mybatis
            3.5.6
        

        
        
            org.mybatis
            mybatis-spring
            2.0.5
        

        
            mysql
            mysql-connector-java
            8.0.11
        

        
        
            com.alibaba
            druid
            1.1.20
        

        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.9.9.3
        

        
        
            javax.servlet
            javax.servlet-api
            4.0.1
        

        
        
        
        
        

    

    
        springSSM
        
            
                
                    maven-clean-plugin
                    3.1.0
                
                
                
                    maven-resources-plugin
                    3.0.2
                
                
                    maven-compiler-plugin
                    3.8.0
                
                
                    maven-surefire-plugin
                    2.22.1
                
                
                    maven-war-plugin
                    3.2.2
                
                
                    maven-install-plugin
                    2.5.2
                
                
                    maven-deploy-plugin
                    2.8.2
                
            
        
        
            
                src/main/java
                
                    **/*.properties
                    **/*.xml
                
                false
            
        
    

2. 配置web.xml




    Archetype Created Web Application

    
    
        contextConfigLocation
        classpath:spring.xml
    
    
        org.springframework.web.context.ContextLoaderListener
    


    
    
        encodingFilter
        
            org.springframework.web.filter.CharacterEncodingFilter
        
        
            encoding
            UTF-8
        
        
            forceEncoding
            true
        
    
    
        encodingFilter
        /*
    


    
    
        spring
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:springmvc.xml
        
        1
    

    
        spring
        /
    


3. 配置spring 配置




    
    
        
        
        
        
    

    
    
        
        
        
        
        
        
    

    
    
        
    

4. 配置springmvc配置



    
    
    
    

    
    
        
        
    

5. 配置mybatis配置




    
        
        
    
    
        
        
    

 

6. 编写entity 接口 和实现类

Spring MVC学习笔记和SSH的整合_第6张图片

7. 编写dao 接口类 和mapper 文件

Spring MVC学习笔记和SSH的整合_第7张图片

8. 编写services接口和实现类

Spring MVC学习笔记和SSH的整合_第8张图片

9. 编写controller

Spring MVC学习笔记和SSH的整合_第9张图片

 

 

其他

 

解决响应乱码

在springmvc.xml 中添加如下代码。

  
  
    
    
      
        
      
    
  

 

RestApi

@RequestMapping("/rest/{id}/{name}")
public String restIndex(@PathVariable("id") Integer id, @PathVariable("name") String name) {
    System.out.println(id);
    System.out.println(name);
    return "index";
}

 

 

 

 

 

 

你可能感兴趣的:(javaweb,java,spring,1024程序员节,java,spring)