SpringMVC04和MyBatis01

SpringMVC的全局异常处理

全局异常处理指的是在一处配置之后,对于控制层所有类的所有方法的指定异常都可以处理

1,基于注解的全局异常处理

具体实现:

在类上加@ControllerAdvice注解

在方法上加@ExceptionHandler注解

在springmvc.xml文件中配置

代码:

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("test01")
    public ModelAndView test01(@RequestParam("i") Integer i) {
        int num = 10/i;
        ModelAndView mv = new ModelAndView();
        mv.setViewName("error");
        return mv;
    }
}
@ControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(value= {ArithmeticException.class})
    public ModelAndView exception(Exception ex) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("error");
        mv.addObject("msg", ex.getMessage());
        return mv;
    }
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>



"UTF-8">
Insert title here


    

来到页面

错误信息为:${msg }

 2.基于xml文件配置全局异常处理

springmvc配置文件中配置一个SimpleMappingException

class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
      
       "exceptionAttribute" value="ex">
       "exceptionMappings">
         
           
           "java.lang.ArithmeticException">error  
         
       

SpringMVC与Spring的整合

1.导包

SpringMVC04和MyBatis01_第1张图片

 2.web.xml中配置spring的ContextLoaderLister和 Springmvc的前端控制器和两个filter

"1.0" encoding="UTF-8"?>
"http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  springmvc04_01
  
  
    
        contextConfigLocation
        classpath:applicationContext.xml
    

    
        class>org.springframework.web.context.ContextLoaderListenerclass>
    
    
    
    
        springDispatcherServlet
        class>org.springframework.web.servlet.DispatcherServletclass>
        
            contextConfigLocation
            classpath:springmvc.xml
        
        1
    

    
        springDispatcherServlet
        /
    
    
    
    
      CharacterEncodingFilter
      class>org.springframework.web.filter.CharacterEncodingFilterclass>
      
         encoding
         UTF-8
      
    
    
    
      CharacterEncodingFilter
      /*
    
HiddenHttpMethodFilter org.springframework.web.filter.HiddenHttpMethodFilter HiddenHttpMethodFilter /*

3.创建springmvc.xml,并配置

SpringMVC04和MyBatis01_第2张图片

 4.创建applicationContext.xml,并配置

base-package="com.offcn.service,com.offcn.dao">
     "classpath:jdbc.properties"/>
     "dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
         "user" value="${jdbc.userName}">
         "password" value="${jdbc.password}">
         "jdbcUrl" value="${jdbc.jdbcUrl}">
        "driverClass" value="${jdbc.driverClass}">
     
     class="org.springframework.jdbc.core.JdbcTemplate">
         "dataSource" ref="dataSource">
     
     "transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
         "dataSource" ref="dataSource">
     
     "transactionManager"/>

扫描包说明:

  springmvc扫描控制层,Spring扫描service层和dao层:

  第一种解决方案:

 Springmvc.xml  扫描 base-package="com.offcn.controller"/>
   Beans.xml base-package="com.offcn.service,com.offcn.dao"/>

第二种解决方案:

Springmvc.xml

   base-package="com.offcn" use-default-filters="false">
      "annotation" expression="org.springframework.stereotype.Controller"/>
      "annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
   

applicationContext.xml

  base-package="com.offcn">
      "annotation" expression="org.springframework.stereotype.Controller"/>
      "annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
   

Springmvc的容器和spring容器的关系:

SpringMVC04和MyBatis01_第3张图片

如何将get请求转换为DELETE请求?

借助于js和一个空的form表单

代码实现增删改查

bean层

package com.offcn.bean;

public class Book {
    private int bid;
    private String bname;
    private String author;
    private double price;
    private String type;
    public int getBid() {
        return bid;
    }
    public void setBid(int bid) {
        this.bid = bid;
    }
    public String getBname() {
        return bname;
    }
    public void setBname(String bname) {
        this.bname = bname;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    @Override
    public String toString() {
        return "Book [bid=" + bid + ", bname=" + bname + ", author=" + author + ", price=" + price + ", type=" + type
                + "]";
    }
    
}

dao层

package com.offcn.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.offcn.bean.Book;

@Repository
public class BookDao {
    @Autowired
    JdbcTemplate jdbcTemplate;
    public List getList() {
        String sql = "select * from book";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper(Book.class));
    }
    public void add(Book book) {
        String sql = "insert into book values(null,?,?,?,?)";
        jdbcTemplate.update(sql, book.getBname(),book.getAuthor(),book.getPrice(),book.getType());
    }
    public void delete(Integer bid) {
        String sql="delete from book where bid=?";
        jdbcTemplate.update(sql, bid);
    }
    public Book selectOne(Integer bid) {
        String sql = "select * from book where bid=?";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper(Book.class),bid);
    }
    public void update(Book book) {
        String sql = "update book set bname=?,author=?,price=?,type=? where bid=?";
        jdbcTemplate.update(sql, book.getBname(),book.getAuthor(),book.getPrice(),book.getType(),book.getBid());
    }
    
}

service层

package com.offcn.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.offcn.bean.Book;
import com.offcn.dao.BookDao;

@Service
public class BookService {
    @Autowired
    BookDao bookDao;
    public List getList() {
        return bookDao.getList();
    }
    public void add(Book book) {
        bookDao.add(book);
    }
    public void delete(Integer bid) {
        bookDao.delete(bid);
    }
    public Book selectOne(Integer bid) {
        return bookDao.selectOne(bid);
    }
    public void update(Book book) {
        bookDao.update(book);
    }

}

Controller层

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    BookService bookService;
    @RequestMapping(value="/getList",method=RequestMethod.GET)
    public ModelAndView getList() {
        List list = bookService.getList();
        ModelAndView mv = new ModelAndView();
        mv.setViewName("show");
        mv.addObject("list", list);
        return mv;
        
    }
    @RequestMapping(value="/add",method = RequestMethod.POST)
    public String add(Book book){
        bookService.add(book);
        return "redirect:/book/getList";
    }
    @RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer bid) {
        bookService.delete(bid);
        return "redirect:/book/getList";
    }
    @RequestMapping("/selectOne/{id}")
    public ModelAndView selectOne(@PathVariable("id") Integer bid) {
        Book book = bookService.selectOne(bid);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("update");
        mv.addObject("book", book);
        return mv;
    }
    @RequestMapping(value="/update",method=RequestMethod.PUT)
    public String update(Book book) {
        bookService.update(book);
        return "redirect:/book/getList";
    }
    @RequestMapping(value="/json",method = RequestMethod.GET)
    @ResponseBody
    public boolean json(int bid) {
        if(bid != 0) {
            bookService.delete(bid);
            return true;
        }
        return false;
    }
    
}

 

show.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>



"UTF-8">
Insert title here



    
"f" action="" method="post"> "hidden" name="_method" value="delete">
"2px" align="center" width="70%" cellspacing="0px"> "${list }" var="book"> "center"> "center">
编号 书名 作者 价格 类型 操作
"bid">${book.bid } ${book.bname } ${book.author } ${book.price } ${book.type } "${pageContext.request.contextPath }/book/selectOne/${book.bid}">修改 &nbsp; "del_${book.bid }" href="${pageContext.request.contextPath }/book/delete/${book.bid }">同步删除 &nbsp; "down_${book.bid }" href="${pageContext.request.contextPath }/book/json?bid=${book.bid}">异步删除
"6">"${pageContext.request.contextPath }/add">添加图书

add.jsp

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



"UTF-8">
Insert title here


    

"center">添加图书

"book/add" method="post" align="center"> 书名:"text" name="bname">
作者:"text" name="author">
价格:"text" name="price">
类型:"text" name="type">
"submit" value="添加">

update.jsp

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



"UTF-8">
Insert title here


    

"center">添加图书

"book/add" method="post" align="center"> 书名:"text" name="bname">
作者:"text" name="author">
价格:"text" name="price">
类型:"text" name="type">
"submit" value="添加">

MyBatis

MyBatis相对于原生Jdbc、JdbcTemplate、Hibernate的优势【必问】

1.MyBatis本身是一个框架,除了可以对数据表中的数据进行增删改查之外,还有缓存、字段映射等机制。
2.MyBatis支持动态SQL(根据你传过来的不同参数,拼接不同的SQL语句)
3.MyBatis支持将Java代码和SQL语句分离开来。
4.MyBatis支持将表的关联关系直接映射为POJO对象的关联关系
5.MyBatis是一个半自动化【手写SQL】的ORM框架

案例:

导入mysql驱动包、mybatis的jar包

创建mybatis的全局配置文件


    default="development">
      
        "development">
            "JDBC" />
            "POOLED">
                "driver" value="com.mysql.jdbc.Driver" />
                "url" value="jdbc:mysql://localhost:3306/test" />
                "username" value="root" />
                "password" value="1129" />
            
        
    
    
    
    
        "aaa.xml" />
    

 创建mybatis的sql映射文件

namespace="org.mybatis.example.BlogMapper">

    <select id="selectBlog" resultType="com.offcn.bean.Book">
        select * from book where id = #{id}
    select>
    

编写测试代码

public void test01() throws IOException {
        //1.根据xml构建SqlSessionFactory对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);
        //2.通过SqlSessionFactory对象的openSession方法得到SqlSession对象
        SqlSession openSession = sqlSessionFactory.openSession();
        //3.通过SqlSession对象执行SQL语句
        Book blog = openSession.selectOne("org.mybatis.example.BlogMapper.selectBlog", 2);
        System.out.println(blog);
        //4.关闭sqlSession对象
        openSession.close();                                  
    }

流程梳理:

SpringMVC04和MyBatis01_第4张图片

你可能感兴趣的:(SpringMVC04和MyBatis01)