Spring + SpringMVC + mybatis + easyui integration instance (3) spring mvc integration and mybatis transaction

Source: Internet
Author: User

Spring + SpringMVC + mybatis + easyui integration instance (3) spring mvc integration and mybatis transaction

Let's use an example to illustrate this part. For the complete steps of integrating instances, please read my previous blog. In addition, I will update the remaining parts every day, and finally complete a complete integrated instance project. You can follow the steps and reply to any questions.

1. Add the framework to support adding jar package configuration xml
Because we want to use spring mvc for the presentation layer and spring aop configuration transactions, we need to import something related to mvc, aop, and tx 0.0

Add the supported applicationContext. xml:


      
       
        
            
          
         
            
             
             
             
          
          
              
               
              
     
      
   
  
Ii. Configure transactions:

To use transactions, we add the service Middle Layer in the project.
Create the com. etoak. exception package to store the custom exception.

Add the following code to applicationContext. xml:


          
               
                
                 
       
        
       
      
     
    
       
      
          
       
                          

Note: rollback-for indicates an exception during rollback. Let's take addStudent as an example.
Create addStudentException:

Public class AddStudentException extends Exception {public String getMessage () {return failed to add students ;}}

Compile the service layer:
StudentService. java:

@Repositorypublic interface StudentService{    public int addStudent(Student stu) throws Exception;    public int delStudentById(int id);    public int updateStudent(Student stu);    public Student selectStudentById(int id);    public List
  
    selectAllStudents();    public int StudentCount();    public List
   
     selectStudentByPage(Map map);}
   
  

StudentServiceImpl. java

@ Repositorypublic class StudentServiceImpl implements StudentService {@ Autowired private StudentDaoIF dao; @ Override public int addStudent (Student stu) throws Exception {int I = 0; try {I = dao. addStudent (stu);} catch (Exception e) {throw new AddStudentException ();} return I ;}// other methods ...}

Now the student transaction has been configured.
We can test it using the test class:

public class TestMybatis {    public static void main(String[] args) throws Exception {         ApplicationContext ac = new ClassPathXmlApplicationContext(applicationContext.xml);          ac = new FileSystemXmlApplicationContext(src/applicationContext.xml);         StudentService dao = (StudentService)ac.getBean(studentServiceImpl);         Student stu = (Student)ac.getBean(student);         stu.setName(a);         stu.setPassword(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);         dao.addStudent(stu);         List
  
    list;        list = dao.selectAllStudents();        System.out.println(list.get(0).getName());    }}
  

Here, the password field exceeds the limit, so the transaction rollback will report our custom exception:

Iii. Integrate spring mvc

We have already imported the Framework Support (jar and xml). We will not go into details here,
Let's take the example of adding students to illustrate the use of spring mvc.
First, configure the spring central controller in web. xml:


  
    
       
    
     etoak
        
    
     com.etoak.util.MyDispatcherServlet
        
            
     
      contextConfigLocation
             
     
      /WEB-INF/applicationContext.xml
         
      
     
       
    
     etoak
        
    
     *.do
      
     
      
       
    
     index.jsp
      
   
  

ApplicationContext. xml has been configured above now do not need to add other configuration, just need to copy this file to the WEB-INF directory, at that time put under src just for the purpose of testing method OH ~

Compile the test page: index. jsp:

<%@ page language=java import=java.util.* pageEncoding=utf-8%>
<Script type = text/javascript src = js/jquery-1.10.2.js> </script> <script type = text/javascript> function OK () {$. ajax ({url: addStudent2.do, type: post, dataType: json, data: {name: $ (# name ). val (), password: $ (# password ). val ()}, success: function (data) {alert (add + data. status + successful) ;}, error: function () {alert (system error) ;}}) ;}</script> Return View:
Return json:

Jump page success. jsp:

<%@ page language=java import=java.util.* pageEncoding=utf8%><%@taglib prefix=c uri=http://java.sun.com/jstl/core%>
Successful Operation Username: $ {student. name} password: $ {student. password}

Write the Controller layer addStudentController. java

@Controllerpublic class AddStudentController {    @Autowired    private StudentService dao;    @RequestMapping(/addStudent1.do)    public String add1(Student stu,ModelMap map) throws Exception{        dao.addStudent(stu);        map.put(student,stu);        return forward:success.jsp;    }    @RequestMapping(value = /addStudent2.do,method = RequestMethod.POST)    @ResponseBody    public Map add2(Student stu) throws Exception{        Map map = new HashMap();        dao.addStudent(stu);        map.put(status, success);        return map;    }}

Note: here we use two methods to accept the returned results. 1 is the returned page and data. when the data is placed in modelMap, it is automatically placed in the request, therefore, when the front-end is displayed, we can use the el expression $ {student. name} to display returned fields. 2. json data is returned. Note that the @ ResponseBody annotation is used in the writing method, and you must add it in applicationContext. xml. This sentence has been added before and will not be repeated here. In addition, to return json, add the json jar package in spring.

The following is the result of the returned View:

Return json results:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.