springMVC入门

Spring MVC 入门

参考视频:SpringMVC教程IDEA版-3天-2018黑马SSM-03

入门程序分析

  • 步骤

    1. 启动服务器,加载一些配置文件
      • DispatcherServlet对象创建
      • springmvc.xml配置文件被加载了
      • HelloController被创建成单例对象
    2. 发送请求,后台处理请求
  • 流程图
    在这里插入图片描述

  • springMVC执行流程
    在这里插入图片描述

请求参数绑定

  • 解决post请求中文乱码的问题。

    <!--配置解决中文乱码的过滤器-->
    <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>
    
  • 绑定简单的字符串,在Controller中定义的方法中传入字符串参数即可。

  • 绑定JavaBean对象。eg. Account对象中包含User对象:

    <%--把数据封装到Account类中--%>
        <form action="param/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.uname"/><br/>
            用户年龄<input type="text" name="user.age"/><br/>
            <input type="submit" value="提交"><br/>
        </form>
    
  • 类中存在list和map的集合

     <%--把数据封装到Account类中,类中存在list和map的集合--%>
         <form action="param/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="list[0].uname"/><br/>
             用户年龄<input type="text" name="list[0].age"/><br/>
    
             用户姓名<input type="text" name="map['one'].uname"/><br/>
             用户年龄<input type="text" name="map['one'].age"/><br/>
    
    
  • 自定义类型转化器

    • 字符串的日期转成日期格式,eg. 2018-10-11

    • 步骤:

      1. 新建一个工具类,实现Converter接口

        /**
         * 把字符串转化为日期
         */
        public class StringToDateConverter implements Converter<String, Date> {
            @Override
            public Date convert(String s) {
                if(s==null){
                    throw new RuntimeException("请您传入数据");
                }
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                try {
                   return df.parse(s);
                } catch (ParseException e) {
                    e.printStackTrace();
                    throw new RuntimeException("数据类型转化出现错误");
                }
        
            }
        }
        
      2. springmvc.xml中配置自定义类型转化器,并注册刚写的工具类。

        <!--配置自定义类型转化器-->
            <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
                <property name="converters">
                    <set>
                        <bean class="com.qmh.utils.StringToDateConverter"></bean>
                    </set>
                </property>
            </bean>
        
      3. 向springMVC注册自定义类型转化器

         <!--开启springMVC注解支持-->
            <mvc:annotation-driven conversion-service="conversionService"/>
        

常用注解

  1. RequestParam

    • 作用:把请求中指定名称的参数给控制器的形参赋值,适用于jsp中传入的参数和方法中参数名不一致的情况。

      @RequestMapping("/testRequestParam")
          public String testRequestParam(@RequestParam(name="name") String username){
              System.out.println(username);
              return "success";
          }
      
  2. RequestBody

    • 作用:用于获取请求体内容,直接使用得到的是键值对结构的数据。get请求方式不适用。

      @RequestMapping("/testRequestBody")
          public String testRequestBody(@RequestBody String body){
              System.out.println(body);
              return "success";
          }
      
  3. PathVarible

    • Restful编程风格
      在这里插入图片描述

    • 作用:用于绑定url中的占位符。例如请求url中delete/{id}这个{id}就是url的占位符。

      @RequestMapping("/testPathVariable/{sid}")
      public String testPathVariable(@PathVariable(name="sid") String id){
          System.out.println(id);
          return "success";
      }
      
  4. RequestHeader

    • 用于获取请求消息头

      @RequestMapping("/testRequestHeader")
          public String testRequestHeader(@RequestHeader(value = "user-agent") String header){
              System.out.println(header);
              return "success";
          }
      
  5. CookieValue

    • 用于把指定cookie名称的值传入控制器方法参数,即获取cookie

      @RequestMapping("/testCookieValue")
          public String testCookieValue(@CookieValue(value = "JSESSIONID") String cookieValue){
              System.out.println(cookieValue);
              return "success";
          }
      
  6. ModelAttribute

    • 用于修饰方法和参数,出现在方法上表示当前方法会在控制器的方法执行之前先执行。出现在参数上,获取指定的数据给参数赋值。

    • 应用场景:当表单数据提交不完整时,可以保证没有提交的字段使用数据库原来的数据。

      /*    @RequestMapping("/testModelAttribute")
          public String testModelAttribute(User user){
              System.out.println("testModelAttribute执行了");
              System.out.println(user);
              return "success";
          }*/
      
          /**
           * 该方法先执行,带返回值
           */
      /*    @ModelAttribute
          public User showUser(String uname){
              System.out.println("showUser执行了..");
              //通过用户查询数据库(模拟)
              User user = new User();
              user.setUname(uname);
              user.setAge(20); //表单提交的数据会覆盖原有的值
              user.setDate(new Date());
              return user;
          }*/
      
          @RequestMapping("/testModelAttribute")
          public String testModelAttribute(@ModelAttribute(value="abc") User user){
              System.out.println("testModelAttribute执行了");
              System.out.println(user);
              return "success";
          }
      
          /**
           * 该方法先执行,不带返回值
           */
          @ModelAttribute
          public void showUser(String uname, Map<String,User> userMap){
              System.out.println("showUser执行了..");
              //通过用户查询数据库(模拟)
              User user = new User();
              user.setUname(uname);
              user.setAge(20); //表单提交的数据会覆盖原有的值
              user.setDate(new Date());
              userMap.put("abc",user);
          }
      
  7. SessionAttributes

    • 用于多次执行控制器方法间的参数共享

      //将值存入session域中,此时,类上需要添加注解:
      //@SessionAttributes(value={"msg"}) //把msg=妹妹存入session域中
      @RequestMapping("/testSessionAttributes")
          public String testSessionAttributes(Model model){
              //底层会存储到request域对象中
              model.addAttribute("msg","妹妹");
              return "success";
          }
          //将值从session域中取出
          @RequestMapping("/getSessionAttributes")
          public String getSessionAttributes(ModelMap model){
              //底层会存储到request域对象中
              System.out.println(model.get("msg"));
              return "success";
          }
          //清除session域中的值
          @RequestMapping("/delSessionAttributes")
          public String delSessionAttributes(SessionStatus status){
              status.setComplete();
              return "success";
          }
      
      

响应数据和结果视图

返回值分类
  • 字符串

    • 将对象存入request域中,然后再到结果视图success.jsp中取得request域中的值并显示。
    @Controller
    @RequestMapping("/user")
    public class UserController {
        @RequestMapping("/testString")
        public String testString(Model model){
            User user = new User();
            user.setUsername("美美");
            user.setPassword("123");
            user.setAge(30);
            model.addAttribute("user",user);
            return "success";
        }
    }
    
  • void

    • request的请求转发
    • response的重定向
    • response直接进行响应
    @RequestMapping("/testVoid")
        public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //编写请求转发 不用写项目名称,由于不会走视图解析器/WEB-INF/pages/,所以自己需要写全路径
            //request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
            //重定向
            //response.sendRedirect(request.getContextPath()+"/index.jsp");
    
            //直接进行响应
            //response解决中文乱码
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print("你好");
            return;
        }
    
  • 返回值是ModelAndView对象

    • ModelAndView对象是spring提供的一个对象,可以用来调整具体的JSP视图。

    • 返回值是字符串的底层实现就是通过ModelAndView对象。

      @RequestMapping("/testModelAndView")
      public ModelAndView testModelAndView(){
          //创建ModelAndView对象
          ModelAndView mv = new ModelAndView();
          //模拟数据库中查询user对象
          User user = new User();
          user.setUsername("哈哈");
          user.setPassword("456");
          user.setAge(30);
          //把user对象存入mv对象中,也会把user对象存入request对象中
          mv.addObject("user",user);
          //跳转到哪个页面
          mv.setViewName("success");
          return mv;
      }
      
springMVC框架提供的转发和重定向
/**
     * 使用关键字的方式进行转发或重定向
     * @return
     */
    @RequestMapping("/testForwardOrRedirect")
    public String testForwardOrRedirect(){
        //请求转发
        //return "forward:/WEB-INF/pages/success.jsp";

        //重定向  底层添加了项目名
        return "redirect:/index.jsp";

    }
ResponseBody响应json数据
  1. DispatcherServlet会拦截到所有资源,导致静态资源也会被拦截,从而不能被使用。解决方法是在springmvc.xml中添加如下配置:

    • mvc:resources标签配置不过滤

      <!--前端控制器,哪些静态资源不被拦截-->
      <mvc:resources mapping="/css/**" location="/css/"/><!--样式-->
      <mvc:resources mapping="/images/**" location="/images/"/> <!--图片-->
      <mvc:resources mapping="/js/**" location="/js/"/> <!--js-->
      
  2. 将json字符串与javaBean对象互相转化,需要引用jackson中的jar包,需要引入以下坐标:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.0</version>
    </dependency>
    
  3. 前端发送ajax请求

    <script  type="text/javascript" src="js/jquery.min.js"></script>
    <script>
        //页面加载,绑定点击事件
        $(function () {
            $("#btn").click(function () {
                // alert("hello btn");
               //发送ajax请求
                $.ajax({
                    url:"user/testAjax",
                    contentType:"application/json;charset=UTF-8",
                    data:'{"username":"呵呵","password":"789","age":24}',
                    dataType:"json",
                    type:"post",
                    success:function (data) {
                        alert(data);
                        alert(data.username);
                        alert(data.password);
                        alert(data.age);
                    }
                })
            });
        });
    </script>
    
  4. 后端接收异步ajax请求,并更新数据,再把数据以json格式返回到前端。

    /**
     * 模拟异步请求响应
     */
    @RequestMapping("/testAjax")
    public @ResponseBody User testAjax(@RequestBody User user){
        //客户端发送ajax请求,传送json字符串。后端把json字符串封装到user对象中。
        System.out.println(user);
        //模拟查询数据库
        user.setUsername("haha");
        user.setAge(40);
        //做响应
        return user;
    }
    

Spring MVC实现文件上传

传统方式上传文件
  • 文件上传相关的jar包

    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
    
  • 前端

    <form action="user/fileUpload1" method="post" enctype="multipart/form-data">
        选择文件<input type="file" name="upload"/><br>
        <input type="submit" value="上传">
    </form>
    
  • 控制器代码

    @RequestMapping("/fileUpload1")
    public String fileUpload1(HttpServletRequest request) throws Exception {
        //使用fileupload完成文件上传
        String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
        System.out.println(realPath);
        //判断该路径是否存在
        File file = new File(realPath);
        //不存在则创建该文件夹
        if(!file.exists()){
            file.mkdirs();
        }
        //解析request对象,获取上传文件项
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解析request对象
        List<FileItem> fileItems = upload.parseRequest(request);
        //遍历
        for(FileItem item:fileItems){
            //判断当前item是否是上传文件项
            if(item.isFormField()){
                //说明是普通表单项
            }else{
                //说明是上传文件项
                String filename = item.getName();
                //把文件名称设置为唯一值 uuid
                String uuid = UUID.randomUUID().toString().replace("-", "");
                filename = uuid+"_"+filename;
                //完成文件上传
                item.write(new File(realPath,filename));
                //删除临时文件
                item.delete();
            }
        }
        return "success";
    }
    
SpringMVC传统方式上传文件
  1. SpringMVC框架提供了MultipartFile对象,该对象表示上传的文件,要求变量名称必须和表单file标签的name属性名称相同。

  2. SpringMVC文件上传原理分析
    在这里插入图片描述

  3. 代码

    @RequestMapping("/fileUpload2")
    public String fileUpload2(HttpServletRequest request, MultipartFile upload) throws Exception {
        //使用fileupload完成文件上传
        String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
        System.out.println(realPath);
        //判断该路径是否存在
        File file = new File(realPath);
        //不存在则创建该文件夹
        if(!file.exists()){
            file.mkdirs();
        }
        //获取文件名字
        String filename = upload.getOriginalFilename();
        //把文件名称设置为唯一值 uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid+"_"+filename;
        //完成文件上传
        upload.transferTo(new File(realPath,filename));
        return "success";
    }
    
SpringMVC跨服务器方式文件上传
  1. 搭建图片服务器

  2. 实现代码

    • 引入开发需要的jar包

      <dependency>
          <groupId>com.sun.jersey</groupId>
          <artifactId>jersey-core</artifactId>
          <version>1.18.1</version>
      </dependency>
      <dependency>
          <groupId>com.sun.jersey</groupId>
          <artifactId>jersey-client</artifactId>
          <version>1.18.1</version>
      </dependency>
      
      
    • 代码:

      @RequestMapping("/fileUpload3")
      public String fileUpload3(MultipartFile upload) throws Exception {
          //定义上传文件服务器路径
          String path = "http://localhost:9090/fileupload_server_war/uploads/";
          //说明上传文件项
          String filename = upload.getOriginalFilename();
          //把文件名称设置为唯一值 uuid
          String uuid = UUID.randomUUID().toString().replace("-", "");
          filename = uuid+"_"+filename;
          //完成文件跨服务器上传
          //创建客户端对象
          Client client = Client.create();
          //和图片服务器进行连接
          WebResource resource = client.resource(path + filename);
          //上传文件
          resource.put(upload.getBytes());
          return "success";
      }
      
    • 如果遇到405错误,则需要使tomcat服务器允许写入。在安装目录下的conf/web.xml的配置文件中加上:

        <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>
              <init-param>
                  <param-name>readonly</param-name>
                  <param-value>false</param-value>
              </init-param>
              <load-on-startup>1</load-on-startup>
          </servlet>
      

SpringMVC中的异常处理

异常处理思路

Controller调用service,service调用dao,异常都是向上抛出的,最终有DispatcherServlet找异常处理器进行异常的处理。

SpringMVC的异常处理
  • 异常处理流程
    在这里插入图片描述

  • 异常处理步骤:

    1. 编写自定义异常类(做提示信息)

      /**
       * 自定义异常类
       */
      public class SysException extends Exception{
          //存储提示信息
          private String message;
      
          @Override
          public String getMessage() {
              return message;
          }
      
          public void setMessage(String message) {
              this.message = message;
          }
      
          public SysException(String message) {
              this.message = message;
          }
      }
      
    2. 编写异常处理器

      /**
       * 异常处理器
       */
      public class SysExceptionResolver implements HandlerExceptionResolver {
          /**
           * 处理异常业务逻辑
           * @param httpServletRequest
           * @param httpServletResponse
           * @param o
           * @param e
           * @return
           */
          @Override
          public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
              //获取到异常对象
              SysException ex = null;
              if(e instanceof SysException){
                  ex = (SysException) e;
              }else{
                  ex = new SysException("系统正在维护...");
              }
              //创建ModelAndView对象
              ModelAndView mv = new ModelAndView();
              mv.addObject("errorMsg",ex.getMessage());
              mv.setViewName("error");
              return mv;
          }
      }
      
    3. 配置异常处理器springmvc.xml(跳转到提示页面)

      <!--配置异常处理器对象-->
      <bean id="sysExceptionResolver" class="com.qmh.exception.SysExceptionResolver"></bean>
      

SpringMVC中的拦截器

过滤器Filter和拦截器的区别
  1. 过滤器是servlet规范中的一部分,任何java web工程都可以使用。
  2. 拦截器是spring mvc框架中的,只有使用了springmvc框架的工程才能用。
  3. 过滤器在url-pattern中配置了/*后,可以对所有要访问的资源拦截。
  4. 拦截器只会拦截访问的控制方法,如果访问的是静态资源,是不会进行拦截的。
使用步骤
  1. 编写拦截器类,实现HandlerInterceptor接口

    /**
     * 自定义拦截器
     */
    public class MyInterceptor implements HandlerInterceptor {
    
        /**
         * 预处理,Controller方法执行前
         * return true 放行,执行下一个拦截器或controller方法
         * return false 不放行
         * @param request
         * @param response
         * @param handler
         * @return
         * @throws Exception
         */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            System.out.println("MyInterceptor执行了 预处理");
    //        request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);
            return true;
        }
    
        /**
         * 后处理方法 controller方法执行后,success.jsp执行前
         * @param request
         * @param response
         * @param handler
         * @param modelAndView
         * @throws Exception
         */
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            System.out.println("MyInterceptor执行了 后处理");
    //        request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);
        }
    
        /**
         * success.jsp执行后,该方法会执行
         * @param request
         * @param response
         * @param handler
         * @param ex
         * @throws Exception
         */
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            System.out.println("MyInterceptor执行了 最后");
        }
    
  2. 配置拦截器,在 springmvc.xml中

    <!--配置拦截器-->
    <mvc:interceptors>
        <!--配置第一个拦截器-->
        <mvc:interceptor>
            <!--要拦截的具体方法-->
            <mvc:mapping path="/user/*"/>
            <!--不要拦截的方法-->
           <!-- <mvc:exclude-mapping path=""/>-->
            <!--配置拦截器对象-->
            <bean class="com.qmh.interceptor.MyInterceptor"></bean>
        </mvc:interceptor>
        <!--配置第二个拦截器-->
        <mvc:interceptor>
            <!--要拦截的具体方法-->
            <mvc:mapping path="/**"/>
            <!--不要拦截的方法-->
            <!-- <mvc:exclude-mapping path=""/>-->
            <!--配置拦截器对象-->
            <bean class="com.qmh.interceptor.MyInterceptor1"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
    
  • 多个拦截器的执行顺序

    拦截器1预处理=>拦截器2预处理=>Controller方法=>拦截器2后处理=>拦截器1后处理=>success.jsp=>拦截器2最后方法=>拦截器1最后方法

SSM 框架整合

  • 采用xml+注解的方式

  • 利用spring整合Spring MVC 和 MyBatis

步骤
创建数据库和表结构
  create table accounts(
      id    int primary key auto_increment,
      name  varchar(20),
      money double
  );
导入依赖 pom.xml
   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <maven.compiler.source>1.8</maven.compiler.source>
      <maven.compiler.target>1.8</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>8.0.11</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>
      <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>
      <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
  • 创建controller、service、dao、domain目录

  • 在domain中编写Account实体类

    • dao中定义接口,分别是查询所有和保存账户。
    • service中定义接口和方法,也是查询所有和保存账户。
    • controller中定义AccountController类,实现controller方法。
  1. 先整合spring,使用注解进行注入。创建application.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: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">
      </beans>
    
    • 开启注解扫描

            <!--开启注解扫描,希望处理service和dao,controller不需要spring处理-->
            <context:component-scan base-package="com.qmh">
                <!--配置哪些注解不扫描-->
                <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
            </context:component-scan>
      
    • 引入log4j的配置文件。

        ### 设置Logger输出级别和输出目的地 ### debug更详细,如果设为info那么打印出的表数据遇到字符串就不显示,此外还有logfile
        log4j.rootLogger=debug,stdout
        
        ### 把日志信息输出到控制台 ###
        log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
        #log4j.appender.stdout.Target=System.err
        log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout 
        
        ### 把日志信息输出到文件:jbit.log ###
        #log4j.appender.logfile=org.apache.log4j.FileAppender
        #log4j.appender.logfile.File=jbit.log
        #log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
        #log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n
        
        ###显示SQL语句部分
        #log4j.logger.com.mybatis=DEBUG
        #log4j.logger.com.mybatis.common.jdbc.SimpleDataSource=DEBUG
        #log4j.logger.com.mybatis.common.jdbc.ScriptRunner=DEBUG
        #log4j.logger.com.mybatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
        #log4j.logger.java.sql.Connection=DEBUG
        #log4j.logger.java.sql.Statement=DEBUG
        #log4j.logger.java.sql.PreparedStatement=DEBUG
        #log4j.logger.java.sql.ResultSet=DEBUG
        
      
    • 测试spring整合结果

            @Test
            public void run1(){
                //加载配置文件
                ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
                //获取Bean对象
                AccountService accountService = context.getBean("accountService", AccountService.class);
                accountService.findAll();
           }
      
spring整合springMVC
  • 配置spring MVC的环境

    • web.xml

        
        <web-app>
          <display-name>Archetype Created Web Application</display-name>
          <!--配置前端控制器-->
          <servlet>
            <servlet-name>dispatcherServlet</servlet-name>
            <!--加载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-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
          </servlet>
         
          <servlet-mapping>
            <servlet-name>dispatcherServlet</servlet-name>
            <url-pattern>/</url-pattern>
          </servlet-mapping>
          
          <!--解决中文乱码的过滤器-->
          <filter>
            <filter-name>characterEncodingFilter</filter-name>
            <init-param>
              <param-name>encoding</param-name>
              <param-value>UTF-8</param-value>
            </init-param>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
          </filter>
          <filter-mapping>
            <filter-name>characterEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
          </filter-mapping>
        </web-app>
      
    • springmvc.xml

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:mvc="http://www.springframework.org/schema/mvc"
             xmlns:context="http://www.springframework.org/schema/context"
             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
              http://www.springframework.org/schema/context
              http://www.springframework.org/schema/context/spring-context.xsd">
      
          <!--开启注解扫描,只扫描controller注解-->
          <context:component-scan base-package="com.qmh">
              <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="WEB-INF/pages/"></property>
              <property name="suffix" value=".jsp"></property>
          </bean>
      
          <!--过滤静态资源-->
          <!--前端控制器,哪些静态资源不被拦截-->
          <mvc:resources mapping="/css/**" location="/css/"/><!--样式-->
          <mvc:resources mapping="/images/**" location="/images/"/> <!--图片-->
          <mvc:resources mapping="/js/**" location="/js/"/> <!--js-->
      
          <!--开启springMVC注解的支持-->
          <mvc:annotation-driven></mvc:annotation-driven>
      
      
      </beans>
      
  • spring整合SpringMVC方法:
    在这里插入图片描述

    • web.xml中设置spring的监听器

        <!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
        <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("/findAll")
          private String findAll(){
              System.out.println("表现层查询所有用户");
              //调用service的方法
              accountService.findAll();
              return "list";
          }
      }
      
spring 整合MyBatis框架
  • 搭建Mybatis环境,编写主配置文件SqlMapConfig.xml

    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    <configuration>
        <!--配置环境-->
        <environments default="mysql">
            <environment id="mysql">
                <transactionManager type="JDBC"></transactionManager>
                <dataSource type="POOLED">
                    <!--配置连接数据库的4个基本信息-->
                    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/eesy?serverTimezone=UTC"/>
                    <property name="username" value="root"/>
                    <property name="password" value="070622"/>
                </dataSource>
            </environment>
        </environments>
    
        <!--引入配置文件-->
        <mappers>
            <package name="com.qmh.dao"/>
        </mappers>
    </configuration>
    
    • 使用注解的方式操作数据库

      package com.qmh.dao;
      
      import com.qmh.domain.Account;
      import org.apache.ibatis.annotations.Insert;
      import org.apache.ibatis.annotations.Select;
      
      
      import java.util.List;
      
      /**
       * Dao接口
       */
      public interface AccountDao {
          /**
           * 查询所有
           * @return
           */
          @Select("select * from account")
          public List<Account> findAll();
      
          /**
           * 保存账户信息
           * @param account
           */
          @Insert("insert into account(name,money) values(#{name},#{money)")
          public void saveAccount(Account account);
      }
      
    • 测试mybatis环境

       @Test
          public void run1() throws Exception {
              //加载配置文件
              InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
              //创建工厂对象
              SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
              //创建数据库连接对象
              SqlSession session = factory.openSession();
              //创建操作数据库代理对象
              AccountDao accountDao = session.getMapper(AccountDao.class);
              //调用方法
              List<Account> accounts = accountDao.findAll();
              for(Account account:accounts){
                  System.out.println(account);
              }
              //关闭资源
              session.close();
              inputStream.close();
          }
      
测试查询所有方法
  • 把mybatis创建的代理对象放入IOC容器中,在spring的配置文件applicationContext.xml中配置:

     <!--spring整合Mybatis框架-->
        <!--配置连接池-->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy?serverTimezone=UTC"></property>
            <property name="user" value="root"></property>
            <property name="password" value="070622"></property>
        </bean>
        <!--配置SqlSessionFactory工厂-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!--配置AccountDao接口所在包-->
        <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.qmh.dao"></property>
        </bean>
    
  • 在service实现类中调用accountDao的方法

    
    @Service("accountService")
    public class AccountServiceImpl implements AccountService{
    
        @Autowired
        private AccountDao accountDao;
        @Override
        public List<Account> findAll() {
            System.out.println("业务层,查询所有账户");
            return accountDao.findAll();
        }
    
        @Override
        public void saveAccount(Account account)
        {
            System.out.println("业务层,查询保存账户");
            accountDao.saveAccount(account);
        }
    }
    
    
    测试保存方法
  • applicationContext.xml中配置事务通知:

    <!--配置spring框架声明式事务管理-->
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>
    <!--配置AOP增强-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.qmh.service.impl.*.*(..))"></aop:advisor>
    </aop:config>
    
  • 在controller中写保存方法,并重定向到查询所有的servlet中,注意路径一定要配置正确。

     @RequestMapping("/save")
        private void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
            accountService.saveAccount(account);
            response.sendRedirect(request.getContextPath()+"/account/findAll");
            return;
        }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值