学完mybatis,就赶紧来学springMVC了,这是B站的学习视频(B站果然是一个学习网站QWQ)

springMVC入门笔记

介绍

springMVC代替之前学的sturts2框架

缩写

M:model模型–>javaBean

v:view视图–>jsp

c:controller控制器–>servlet

springMVC和Struts2的优劣

共同点:

  • 都是表现层框架,都是基于MVC模型编写的
  • 他们的底层都离不开原始ServletAPI
  • 处理请求的机制都是一个核心控制器

区别:

  • springMVC的入口是Servlet,而Struts2是Filter
  • springMVC是单例的,Strusts多例的,所以springMVC会快一点
  • springMVC对于ajax更友好
  • Struts的OGNL表达式开发效率比springMVC高,但是执行效率没有JSTL高,特别是struts的表单元素

spingMVC的入门案例

需求:用户登录,校验用户,正确则跳转到成功页面

Controller

@Controller
public class HelloController {

  @RequestMapping("/hello")
  public String sayHello() {
    System.out.println("hello springMVC");
    return "success";
  }
}

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.xsd">
  <!--  开启扫描注解-->
  <context:component-scan base-package="cn.itcast.controller"/>
  <!--  开启springMVC注解的支持-->
  <mvc:annotation-driven/>
  <!--  视图解析器-->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/project/"/>
    <property name="suffix" value=".jsp"/>
  </bean>
</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>
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!--      扫描springmvc.xml-->
      <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>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false" %>

<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>hello springMVC</h1>
<a href="/hello">跳转</a>
</body>
</html>

sucess.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>入门成功</h1>
</body>
</html>

结果

大概流程

详细过程

@RequestMapping

可以放在类前面,和方法前,表示访问的__相对地址__

  • value和path一模一样

  • method:请求方式

    • method = {RequestMethod.GET},表示请求必须是get
  • params

    • params={“accountName”},表示请求参数必须有accountName
    • params={“accountName!100”},表示请求参数中money不能是100
  • headers:用于指定限制请求消息头的条件

请求参数的绑定

接收前端传过来的数据

  @RequestMapping(path = "/hello")
  public String sayHello(String username, String password) {
    System.out.println(username + password);
    System.out.println("hello springMVC");
    return "success";
  }
<a href="${pageContext.request.contextPath}/hello?username=root&password=123" >参数绑定</a>

请求参数绑定

实体类封装

<form action="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.username"/><br/>
    年龄:<input type="text" name="user.age"/><br/>
    <input type="submit" value="提交"/>
</form>
@RequestMapping(path = "saveAccount")
  public String saveAccount(Account account) {
    System.out.println(account.toString());
    System.out.println(account.getUser().toString());
    return "success";
  }
public class Account implements Serializable {
  private String username;
  private String password;
  private Double money;
  private User user;
    //Getter和Setter    
public class User implements Serializable {

  private String username;
  private Integer age;
    //Getter和Setter    
  • 测试

中文乱码问题

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

集合封装

<form action="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].username"/><br/>
    年龄:<input type="text" name="list[0].age"/><br/>
    <%--封装到map--%>
    名称:<input type="text" name="map['one'].username"/><br/>
    年龄:<input type="text" name="map['one'].age"/><br/>
    <input type="submit" value="提交"/>

测试

自定义类型转换器

正常的日期类型 ,例如:2020-5-18,springMVC能帮我们转换,但是2020/5/18就必须我手动添加类型转换器

 <!--    配置自定义类型转换器-->
  <bean class="org.springframework.context.support.ConversionServiceFactoryBean"
    id="conversionServiceFactoryBean">
    <property name="converters">
      <set>
        <bean class="cn.itcast.utils.StringToDateConverter"/>
      </set>
    </property>
  </bean>
  <!--    开启springMVC注解的支持-->
  <mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>
</beans>
public class StringToDateConverter implements Converter<String, Date> {

  //字符串转化为日期
  @Override
  public Date convert(String s) {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    try {
      return dateFormat.parse(s);
    } catch (Exception e) {
      throw new RuntimeException("数据类型错误");
    }
  }

}

<form action="${pageContext.request.contextPath}/saveUser" method="post">
    名称:<input type="text" name="username"/><br/>
    年龄:<input type="text" name="age"/><br/>
<%--    自定义类型转换--%>
    日期:<input type="text" name="date"><br/>
    <input type="submit" value="提交"/>
</form>

测试

servlet的原生API获取

  @RequestMapping(path = "/hello")
  public String sayHello(HttpServletRequest request, HttpServletResponse response) {
    System.out.println("hello springMVC");
//    request域对象
    System.out.println(request);
//    session域对象
    System.out.println(request.getSession());
//    servletContext域对象
    System.out.println(request.getSession().getServletContext());
    return "success";
  }

常见注解

@RequestParam

<a href="hello?username=root&password=123">参数绑定</a>
  @RequestMapping(path = "/hello")
  public String sayHello(String name, String password) {
    System.out.println(name + password);
    return "success";
  }

如果参数名称不一致,就接收不找数据,这时候@RequestParam就是来解决这个的

  public String sayHello(@RequestParam(name = "username") String name, String password) {

@RequestBody

获取请求体的数据,get请求不行,因为他是在url中的,并没有在请求体中,在json中运用较多

<form action="${pageContext.request.contextPath}/saveUser" method="post">
    名称:<input type="text" name="username"/><br/>
    年龄:<input type="text" name="age"/><br/>
<%--    自定义类型转换--%>
    日期:<input type="text" name="date"><br/>
    <input type="submit" value="提交"/>
</form>
  @RequestMapping(path = "/saveUser")
  public String saveUser(@RequestBody String body) {
    System.out.println(body);
    return "success";
  }

注意:这里可以不叫body这个名称,如果没有@RequestBody,springMVC就在去前端找name=body的这个标签值封装。

@pathVariable

restful风格

<a href="hello/10">参数绑定</a>
@RequestMapping(path = "/hello/{sid}")
  public String sayHello(@PathVariable(name = "sid") String id) {
    System.out.println(id);
    return "success";
  }

结果:控制台打印了10

@HiddenHttpMethodFilter【了解】

@RequestHeader

用于获取消息请求头

 @RequestMapping(path = "/hello")
  public String sayHello(@RequestHeader(value = "Accept") String header) {
    System.out.println(header);
    return "success";
  }

@CookieValue

获取cookie

  @RequestMapping(path = "/hello")
  public String sayHello(@CookieValue(value = "JSESSIONID") String header) {
    System.out.println(header);
    return "success";
  }

和下面的@ModelAttribute一起测试

@ModelAttribute

被注解的方法会优先执行

  @RequestMapping(path = "/hello")
  public String sayHello(@CookieValue(value = "JSESSIONID") String header) {
    System.out.println(header);
    return "success";
  }

  @ModelAttribute
  public void showUser() {
    System.out.println("我被优先执行了");
  }

测试

应用场景:前端修改用户信息,但是只有username和age,注册时间date不需要你修改,所以前端传来的数据date就为null,这时候就需要先去数据库中查询到相关数据,在进行操作

  @RequestMapping(path = "/saveUser")
  public String saveUser(User user) {
    System.out.println(user);
    return "success";
  }

  @ModelAttribute
  public void showUser(User user) {
    System.out.println("我被优先执行了");
//    查询数据库,找到这条数据,下面模拟场景,找到date
    user.setDate(new Date());
  }

  • 或者存到集合中
  @RequestMapping(path = "/saveUser")
  public String saveUser(@ModelAttribute("one") User user) {
    System.out.println(user);
    return "success";
  }

  @ModelAttribute
  public void showUser(User user, Map<String,User> map){
    System.out.println("我被优先执行了");
//    查询数据库,找到这条数据,下面模拟场景
    user.setDate(new Date());
    map.put("one",user);
  }

@SessionAttribute

@RequestMapping(path = "/hello")
 public String sayHello(Model model) {
   model.addAttribute("msg","丽丽");
   return "success";
 }

注意:model封装了一个request域对象,上面就是在往request中存msg数据

@Controller
@SessionAttributes(value = {"msg"})//又把msg=美美存到session域中
public class HelloController {
${requestScope.get("msg")}
${sessionScope.get("msg")}

从session中取值

 @RequestMapping("/getSessionAttribute")
  public String getSessionAttribute(ModelMap modelMap) {
    System.out.println(modelMap.get("msg"));
    return "success";
  }

结果:控制台输出"丽丽"

从session中删除msg

 @RequestMapping("/getSessionAttribute")
  public String getSessionAttribute(SessionStatus sessionStatus) {
   sessionStatus.setComplete();
    return "success";
  }

响应

响应值为String

@RequestMapping("/testString")
public String testString(Model model) {
  System.out.println("testString");
  User user = new User("小赵", "123", 12);
  model.addAttribute(user);
  return "success";
}
${user.username}
${user.password}
${user.age}测试:

响应值为void

 @RequestMapping("/testString")
  public void testString(Model model) {
    System.out.println("testString");
  }

  • 使用servlet原生API,转发页面
  @RequestMapping("/testString")
  public void testString(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    System.out.println("testString");
//    转发
    request.getRequestDispatcher("/project/success.jsp").forward(request, response);
  }

结果:转发到success.jsp

  • 使用servlet原生API,重定向页面
@RequestMapping("/testString")
  public void testString(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    System.out.println("testString");
//    转发
//    request.getRequestDispatcher("/project/success.jsp").forward(request, response);
      //重定向
    response.sendRedirect(request.getContextPath()+"/project/success.jsp");
    return;
  }

结果:跳转到success.jsp

  • 直接显示到页面
  @RequestMapping("/testString")
  public void testString(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    System.out.println("testString");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    response.getWriter().println("hello");
  }

响应值为ModelAndView

可以帮我们把值存入request域,并且完成跳转功能

@RequestMapping("/testModelAndView")
  public ModelAndView testModelAndView() {
    ModelAndView modelAndView = new ModelAndView();
    User user = new User("小李", "123", 12);
//    把user对象存储到modelAndView对象中,也会把user对象存入到request对象
    modelAndView.addObject("user", user);
    modelAndView.setViewName("success");
    return modelAndView;
  }

转发和重定向

用关键字来进行转发和重定向(无法使用视图解析器)

  • 转发
  @RequestMapping("/testForwardOrRedirect")
  public String testForwardOrRedirect(){
    return "forward:/project/success.jsp";
  }
  • 重定向(底层自动帮你加上根路径了)
  @RequestMapping("/testForwardOrRedirect")
  public String testForwardOrRedirect(){
    return "redirect:/index.jsp";
  }

ResquestBody响应json数据

  <!--  前端控制器,那些静态资源不拦截-->
  <mvc:resources mapping="/js/**" location="/js/"/>
  <script>
      $(function () {
        $("#btn").click(function () {
// 发送ajax请求
          $.ajax({
            url: "user/testAjax",
            contentType: "application/json;charset=UTF-8",
            data: '{"username":"小白","password":"123","age":"12"}',
            dataType: "json",
            type: "post",
            success: function (data) {
              // data服务器响应的json数据,进行解析
              alert(data.username + data.password + data.age);
            }
          });
        });
      });
    </script>
@RequestMapping("/testAjax")
  public @ResponseBody User testAjax(@RequestBody User user) {
    System.out.println("testAjax方法执行了...");
    user.setAge(12);
    user.setUsername("haha");
    user.setPassword("123");
    return user;
  }

文件上传

必要前提

  • 表单的enctype(请求正文的类型)必须是multipart/form-data
  • method属性必须是post
  • 提供一个文件域

maven坐标

传统方式

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.5</version>
    </dependency>
 public String fileupload(HttpServletRequest httpServletRequest) throws Exception {
    System.out.println("文件上传");
    String path = httpServletRequest.getSession().getServletContext().getRealPath("/uploads/");
    System.out.println(path);
    File file = new File(path);
    if (!file.exists()) {
      file.mkdirs();
    }
//    创建解析器工厂对象【DiskFileItemFactory】
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
//    通过解析器工厂创建解析器【ServletFileUpload】
    ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
    List<FileItem> itemList = upload.parseRequest(httpServletRequest);
    for (FileItem item : itemList) {
//      进行判断,当前item对象是否是上传文件项
      if (!item.isFormField()) {
//        说明上传文件项
//        获取上传文件的名称
        String filename = item.getName();
//        完成文件上传
        item.write(new File(path, filename));
//        删除临时文件
        item.delete();
      } else {

      }
    }
    return "success";
  }

springMVC的方式

注意:前端的name标签要和传的参数名称一样

<!--  文件解析器-->
  <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
    <property name="maxUploadSize" value="1024"/>
  </bean>
 @RequestMapping("/fileupload02")
  public String fileupload1(HttpServletRequest httpServletRequest, MultipartFile upload)
      throws Exception {
    String path = httpServletRequest.getSession().getServletContext().getRealPath("/uploads/");
    String filename = upload.getName();
    upload.transferTo(new File(path, filename));
    return "success";
  }

跨服务器文件上传

springMVC的异常处理

异常处理器组件:抛出的异常不会显示给用户,而是用过异常处理器组件给用户一个友好的错误页面

  • 编写自定义异常类
  • 编写异常处理器
  • 配置异常处理器

自定义异常类

public class SysException extends Exception {

  private String message;

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

  public SysException() {

  }

  @Override
  public String getMessage() {
    return message;
  }

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

编写异常处理器

public class SysExceptionResolver implements HandlerExceptionResolver {

  //处理异常
  @Override
  public ModelAndView resolveException(HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse, Object o, Exception e) {
    //获取到异常对象
    SysException sysException = null;
    if (e instanceof SysException) {
      sysException = (SysException) e;
    } else {
      e = new SysException("系统出错");
    }
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("errorMsg", sysException.getMessage());
    modelAndView.setViewName("error");
    return modelAndView;
  }
}

在springMVC配置

  <!--  配置异常处理器-->
  <bean class="cn.itcast.exception.SysExceptionResolver" id="sysExceptionResolver"/>

测试页面

  @RequestMapping("/testException")
  public String testException() throws SysException {
    System.out.println("testException方法执行了");
//    模拟异常
    try {
      System.out.println(1 / 0);
    } catch (Exception e) {
      e.printStackTrace();
//      抛出自定义异常信息
      throw new SysException("出现错误...");
    }
    return "success";
  }

结果

拦截器

和struts的拦截器类似

  • 编写拦截器
  • 配置拦截器

放行

public class MyInterceptor implements HandlerInterceptor {

  //预处理controller方法执行前
  //return true放行,执行下一个拦截器,如果没有,执行controller中的方法
  //return false不放行
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    System.out.println("拦截器执行了..");
    return true;
  }
}
<!--  配置拦截器-->
  <mvc:interceptors>
    <mvc:interceptor>
      <!--      你要拦截器的具体方法-->
      <mvc:mapping path="/user/*"/>
      <!--      你不要拦截器的具体方法-->
      <!--      <mvc:exclude-mapping path=""/>-->
      <!--      配置拦截器-->
      <bean class="cn.itcast.Interceptor.MyInterceptor" id="myInterceptor"/>
    </mvc:interceptor>
  </mvc:interceptors>

结果

不放行

return true改为return false,然后在方法中写转发或者重定向都行,就不会到controller了

后处理

  //后处理方法,在controller方法执行后,success.jsp执行之前  
  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) throws Exception {
    System.out.println("后处理方法执行了...");
  }

完成之后

//success.jsp页面执行后,该方法会执行
  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) throws Exception {
    System.out.println("最后方法执行...");
  }

多个拦截器

public class Interceptor01 implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    System.out.println("拦截器执行了..01");
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) throws Exception {
    System.out.println("后处理方法执行了...01");
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) throws Exception {
    System.out.println("最后方法执行...01");
  }
}

    <mvc:interceptor>
      <!--      你要拦截器的具体方法-->
      <mvc:mapping path="/user/*"/>
      <!--      你不要拦截器的具体方法-->
      <!--      <mvc:exclude-mapping path=""/>-->
      <!--      配置拦截器-->
      <bean class="cn.itcast.Interceptor.MyInterceptor" id="myInterceptor"/>
    </mvc:interceptor>
    <mvc:interceptor>
      <mvc:mapping path="/user/*"/>
      <bean class="cn.itcast.Interceptor.Interceptor01" id="interceptor01"/>
    </mvc:interceptor>

结果

SSM整合

  • spring整合springMVC
  • spring整合mybatis
<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>
    <spring.version>5.0.2.RELEASE</spring.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>5.1.6</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
  </properties>


<dependencies>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.8</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency> <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency> <!-- log end -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>

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:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  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">
<!--  开启注解扫描-->
  <context:component-scan base-package="cn.itcast">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  </context:component-scan>
</beans>

service层

@Service
public class AccountServiceImpl implements AccountService {

  @Override
  public List<Account> findAll() {
    System.out.println("service层:查询所有信息...");
    return null;
  }

  @Override
  public void saveAccount(Account account) {
    System.out.println("service层:添加用户信息...");
  }
}

测试一下,是否成功

  @Test
  public void test01() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
        "applicationContext.xml");
    AccountService accountService = applicationContext
        .getBean("accountServiceImpl", AccountServiceImpl.class);
    accountService.findAll();
  }
}

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.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.xsd">
  <!--  开启注解扫描-->
  <context:component-scan base-package="cn.itcast">
    <context:include-filter type="annotation"
      expression="org.springframework.stereotype.Controller"/>
  </context:component-scan>

  <!--  视图解析器-->
  <bean id="internalResourceViewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/pages/"/>
    <property name="suffix" value=".jsp"/>
  </bean>
  <!--  开启springMVC注解支持-->
  <mvc:annotation-driven />
  <!--  过滤静态资源-->
  <mvc:resources mapping="/css/**" location="/css/"/>
  <mvc:resources mapping="/images/**" location="/images/"/>
  <mvc:resources mapping="/js/**" location="/js/"/>
</beans>
<web-app>
  <!--  配置前端控制器-->
  <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-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-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>
</web-app>
@Controller
@RequestMapping("/account")
public class AccountController {
  @RequestMapping("/testfindAll")
  public String finAll(){
    return "list";
  }
}

测试

spring整合springMVC

在tomcat启动加载spring的配置文件

  <!--  spring的监听器-->
  <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>
@Controller
@RequestMapping("/account")
public class AccountController {
  @Autowired
  private AccountService accountService;
  @RequestMapping("/testfindAll")
  public String finAll(){
    accountService.findAll();
    return "list";
  }

测试:

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">
<!--mybatis的核心配置文件-->
<configuration>
  <!--  引入外部配置文件-->
  <properties resource="db.properties"/>
  <!--  环境设置-->
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url"
          value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper class="cn.itcast.dao.AccountDao"/>
  </mappers>
</configuration>
public interface AccountDao {

  //查找所有信息
  @Select("select * from account")
  List<Account> findAll();

  //保存账户信息
  @Insert("insert into account (name, money) values(#{name},#{money})")
  void saveAccount(Account account);
}
@Test
  public void test02() throws Exception {
    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
    List<Account> list=accountDao.findAll();
    for(Account account:list){
      System.out.println(account.toString());
    }
    sqlSession.close();
    inputStream.close();
  }

spring整合mybatis

  <!--  spring整合mybatis框架-->
  <!--  配置连接池-->
  <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql:///ssm"/>
    <property name="user" value="root"/>
    <property name="password" value="761020zy"/>
  </bean>
  <!--  配置sqlSessionFactory工厂-->
  <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactoryBean">
    <property name="dataSource" ref="comboPooledDataSource"/>
  </bean>
  <!--  配置AccountDao接口所在包-->
  <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="cn.itcast.dao"/>
  </bean>
@Repository
public interface AccountDao {
 @Autowired
  private AccountDao accountDao;

  @Override
  public List<Account> findAll() {
    System.out.println("service层:查询所有信息...");
       return accountDao.findAll();
  }

  @Override
  public void saveAccount(Account account) {
    System.out.println("service层:添加用户信息...");
    accountDao.saveAccount(account);
  }
<c:forEach items="${list}" var="account">
    ${account.id}<br>
    ${account.name}<br>
    ${account.money}<br>
</c:forEach>

spring事务

 <!--  配置事务通知-->
  <tx:advice id="transactionInterceptor" transaction-manager="dataSourceTransactionManager">
    <tx:attributes>
      <tx:method name="find*" read-only="false"/>
    </tx:attributes>
  </tx:advice>
  <!--    配置AOP增强-->
  <aop:config>
    <aop:advisor advice-ref="transactionInterceptor"
      pointcut="execution(* cn.itcast.service.AccountServiceImpl.*(..))"/>
  </aop:config>
@RequestMapping("/save")
  public void save(Account account, HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    accountService.saveAccount(account);
    response.sendRedirect(request.getContextPath() + "/account/findAll");
  }

测试

`

@Repository
public interface AccountDao {
 @Autowired
  private AccountDao accountDao;

  @Override
  public List<Account> findAll() {
    System.out.println("service层:查询所有信息...");
       return accountDao.findAll();
  }

  @Override
  public void saveAccount(Account account) {
    System.out.println("service层:添加用户信息...");
    accountDao.saveAccount(account);
  }
<c:forEach items="${list}" var="account">
    ${account.id}<br>
    ${account.name}<br>
    ${account.money}<br>
</c:forEach>

[外链图片转存中…(img-wBYkDHSw-1589971462497)]

spring事务

 <!--  配置事务通知-->
  <tx:advice id="transactionInterceptor" transaction-manager="dataSourceTransactionManager">
    <tx:attributes>
      <tx:method name="find*" read-only="false"/>
    </tx:attributes>
  </tx:advice>
  <!--    配置AOP增强-->
  <aop:config>
    <aop:advisor advice-ref="transactionInterceptor"
      pointcut="execution(* cn.itcast.service.AccountServiceImpl.*(..))"/>
  </aop:config>
@RequestMapping("/save")
  public void save(Account account, HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    accountService.saveAccount(account);
    response.sendRedirect(request.getContextPath() + "/account/findAll");
  }

测试

[外链图片转存中…(img-hYuKz45Z-1589971462498)]

[外链图片转存中…(img-LcvHtQzQ-1589971462499)]

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐