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

 

image.png

 

5. 创建项目及入门程序

image.png

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

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

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

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

 

2.新建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
http://www.springframework.org/schema/context/spring-context.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">


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

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

</beans>
  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<String, User> userMap;

    public UserMap(Map<String, User> userMap) {
        this.userMap = userMap;
    }

    public UserMap() {
    }

    public Map<String, User> getUserMap() {
        return userMap;
    }

    public void setUserMap(Map<String, User> 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 中
<?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
http://www.springframework.org/schema/context/spring-context.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">


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

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

    <!--处理响应乱码-->
    <mvc:annotation-driven>
        <!-- 消息转换器 转换响应格式 为UTF-8 -->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/html;charset=UTF8"></property>
            </bean>

            <!--配置fastjson-->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json</value>
                        <value>application/json;charset=UTF-8</value>
                        <value>application/atom+xml</value>
                        <value>application/x-www-form-urlencoded</value>
                        <value>application/octet-stream</value>
                        <value>application/pdf</value>
                        <value>application/rss+xml</value>
                        <value>application/xhtml+xml</value>
                        <value>application/xml</value>
                        <value>image/gif</value>
                        <value>image/jpeg</value>
                        <value>image/png</value>
                        <value>text/event-stream</value>
                        <value>text/html</value>
                        <value>text/markdown</value>
                        <value>text/plain</value>
                        <value>text/xml</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

</beans>
  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
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>4.0.1</version>
  <scope>provided</scope>
</dependency>
  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 "你好啊";
  }

image.png

 

9. REST 架构

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

 

其他

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

  <!--配置编码过滤器-->
  <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 生效路由-->
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

 

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<User> 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<Integer, User> userMap;

    static {
        System.out.println("UserDAOImpl static");
        userMap = new HashMap<Integer, User>();
        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<User> 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<User> 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<User> 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<User> 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. 增加依赖

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.5</version>
</dependency>

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.3</version>
</dependency>

2. 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
http://www.springframework.org/schema/context/spring-context.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">


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

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

    <!--上传组件-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="#{1024*1024}"/>
    </bean>

    <!--处理响应乱码-->
    <mvc:annotation-driven>
        <!-- 消息转换器 转换响应格式 为UTF-8 -->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/html;charset=UTF8"></property>
            </bean>

            <!--配置fastjson-->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json</value>
                        <value>application/json;charset=UTF-8</value>
                        <value>application/atom+xml</value>
                        <value>application/x-www-form-urlencoded</value>
                        <value>application/octet-stream</value>
                        <value>application/pdf</value>
                        <value>application/rss+xml</value>
                        <value>application/xhtml+xml</value>
                        <value>application/xml</value>
                        <value>image/gif</value>
                        <value>image/jpeg</value>
                        <value>image/png</value>
                        <value>text/event-stream</value>
                        <value>text/html</value>
                        <value>text/markdown</value>
                        <value>text/plain</value>
                        <value>text/xml</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

</beans>

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

}

image.png

 

文件下载

@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 的整合

image.png

 

1. 增加依赖

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springSSM</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>springSSM Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!-- SpringMVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>
        <!-- Spring JDBC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>
        <!-- Spring AOP -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>
        <!--aspect-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>
        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
            <scope>provided</scope>
        </dependency>

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>

        <!-- mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.20</version>
        </dependency>

        <!--jackjson-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.9.3</version>
        </dependency>

        <!--servlet-api-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>

        <!--<dependency>-->
        <!--  <groupId>com.alibaba</groupId>-->
        <!--  <artifactId>fastjson</artifactId>-->
        <!--  <version></version>-->
        <!--</dependency>-->

    </dependencies>

    <build>
        <finalName>springSSM</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
</project>

2. 配置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 配置-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <!--编码配置-->
    <filter>
        <filter-name>encodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <!--spring MVC 配置-->
    <servlet>
        <servlet-name>spring</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>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

3. 配置spring 配置

<?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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
">
<context:component-scan base-package="com.liyong.services"/>
    <!--配置链接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/book?serverTimezone=GMT"></property>
    </bean>

    <!--交给loc的工厂类-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--datasource-->
        <property name="dataSource" ref="dataSource"></property>
        <!--配置mapper路径-->
        <property name="mapperLocations" value="classpath:com/liyong/dao/*.xml"></property>
        <!--配置mybatis配置文件路径-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>

    <!--扫描自定义的mapper接口-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.liyong.dao"></property>
    </bean>

</beans>

4. 配置springmvc配置

<?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-3.0.xsd
 http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
 http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    <!-- 启动注解驱动 -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!-- 扫描业务代码 -->
    <context:component-scan base-package="com.liyong"></context:component-scan>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

5. 配置mybatis配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- 打印SQL-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <typeAliases>
        <!-- 指定⼀个包名,MyBatis会在包名下搜索需要的JavaBean-->
        <package name="com.liyong.entity"/>
    </typeAliases>
</configuration>

 

6. 编写entity 接口 和实现类

image.png

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

image.png

8. 编写services接口和实现类

image.png

9. 编写controller

image.png

 

 

其他

 

解决响应乱码

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

  <!--处理响应乱码-->
  <mvc:annotation-driven>
    <!-- 消息转换器 -->
    <mvc:message-converters register-defaults="true">
      <bean
        class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes" value="text/html;charset=UTF8"></property>
      </bean>
    </mvc:message-converters>
  </mvc:annotation-driven>

 

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

 

 

 

 

 

 
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页