代码改变世界

spring+springmvc+mybatis

2018-11-21 00:36  crow!  阅读(150)  评论(0编辑  收藏  举报

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>SMMProject</display-name>
  <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>
  <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>
          org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
      </init-param>
  </servlet>
  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

mybatis.cfg.xml

<?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>
    <typeAliases>
        <typeAlias type="cn.mldn.vo.Message" alias="Message"/>
    </typeAliases>
    <mappers>
        <mapper resource="cn/mldn/mapping/Message.xml"/>
    </mappers>
</configuration>

databases.properties

db.driver=org.gjt.mm.mysql.Driver
db.url=jdbc:mysql://localhost:3306/mldn
db.user=root
db.password=******
pool.max=100
pool.min=20
pool.init=10
pool.idle=100

applicationContext.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
    <!-- annotation -->
    <context:annotation-config/>
    <context:component-scan base-package="cn.mldn"/>
    
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    
    <context:property-placeholder location="classpath:database.properties"/>
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${db.driver}" />
        <property name="jdbcUrl" value="${db.url}" />
        <property name="user" value="${db.user}" />
        <property name="password" value="${db.password}" />
        <property name="maxPoolSize" value="${pool.max}" />
        <property name="minPoolSize" value="${pool.min}" />
        <property name="initialPoolSize" value="${pool.init}" />
        <property name="maxIdleTime" value="${pool.idle}" />
    </bean>
    <!-- 如果需要对事物进行控制,可直接在数据源上进行操作 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis.cfg.xml" />
    </bean>
    <!-- 进入到事物配置的声明 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 定义一切与服务层有关的控制方法名称,只要是使用特定名称那么就会自动处理事务 -->
        <tx:attributes>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="edit*" propagation="REQUIRED"/>
            <tx:method name="change*" propagation="REQUIRED"/>
            <tx:method name="remove*" propagation="REQUIRED"/>
            <tx:method name="login*" propagation="REQUIRED"/>
            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="load*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="list*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- 定义事物的处理切入点 -->
    <aop:config expose-proxy="true" >
        <aop:pointcut expression="execution(* cn.mldn..service.*.*(..))" id="pointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>
    
</beans>

vo

package cn.mldn.vo;

import java.io.Serializable;
import java.util.Date;

@SuppressWarnings("serial")
public class Message implements Serializable {
    private Integer mid ;
    private String  title ;
    private Date    pubdate ;
    private String  content ;
    public Integer getMid() {
        return mid;
    }
    public void setMid(Integer mid) {
        this.mid = mid;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public Date getPubdate() {
        return pubdate;
    }
    public void setPubdate(Date pubdate) {
        this.pubdate = pubdate;
    }
    public String getContext() {
        return content;
    }
    public void setContext(String content) {
        this.content = content;
    }
    
}

action

package cn.mldn.action;

import java.text.SimpleDateFormat;

import javax.annotation.Resource;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.mldn.service.IMessageService;
import cn.mldn.vo.Message;

@Controller
@RequestMapping("/pages/back/msg/*")
public class MessageAction {
    @Resource
    private IMessageService messageService ;
    
    @RequestMapping("add")
    public ModelAndView add(Message msg){
        try {
            System.out.println(this.messageService.add(msg));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    
    @RequestMapping("list")
    public ModelAndView list(String col,String kw,int cp,int ls) {
        try {
            System.out.println(this.messageService.list(col, kw, cp, ls));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null ;
    }
    
    @InitBinder
    public void initBindler(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
        binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(sdf, true));
    }
}

dao

package cn.mldn.dao;

import java.util.List;

import cn.mldn.vo.Message;

public interface IMessageDAO {
    public boolean doCreate(Message vo) throws Exception ;
    public List<Message> findAllSplit(String column ,String keyWord,Integer currentPage , Integer lineSize) throws Exception ;
}
package cn.mldn.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;

import cn.mldn.dao.IMessageDAO;
import cn.mldn.vo.Message;

@Component
public class MessageDAOImpl extends SqlSessionDaoSupport implements IMessageDAO {
//    @Resource
//    private SqlSessionFactory sessionFactory ;
    @Autowired
    public MessageDAOImpl(SqlSessionFactory sqlSessionFactory){
        super.setSqlSessionFactory(sqlSessionFactory);
    }
//    @Resource
//    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory){
//        super.setSqlSessionFactory(sqlSessionFactory);
//    }
    @Override
    public boolean doCreate(Message vo) throws Exception {
        // TODO Auto-generated method stub
        return super.getSqlSession().insert("cn.mldn.mapping.MessageNS.doCreate",vo) > 0;
    }

    @Override
    public List<Message> findAllSplit(String column, String keyWord, Integer currentPage, Integer lineSize)
            throws Exception {
        
        Map<String,Object> map = new HashMap<String,Object> () ;
        if("".equals(keyWord)){
            map.put("keyWork", keyWord) ;
        }
        map.put("column", column) ;
        map.put("start", (currentPage-1) * lineSize) ;
        map.put("lineSize", lineSize) ;
        
        return this.getSqlSession().selectList("cn.mldn.mapping.MessageNS.findAllSplit",map);
    }

}

service

package cn.mldn.service;

import java.util.List;

import cn.mldn.vo.Message;

public interface IMessageService {
    public boolean add(Message vo) throws Exception ;
    public List<Message> list(String column,String keyWord,int currentPage,int lineSize) throws Exception ;
}
package cn.mldn.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.mldn.dao.IMessageDAO;
import cn.mldn.service.IMessageService;
import cn.mldn.vo.Message;

@Service
public class MessageServiceImpl implements IMessageService {
    @Resource
    private IMessageDAO messageDAO ;
    
    @Override
    public boolean add(Message vo) throws Exception {
        // TODO Auto-generated method stub
        return this.messageDAO.doCreate(vo);
    }

    @Override
    public List<Message> list(String column, String keyWord, int currentPage, int lineSize) throws Exception {
        // TODO Auto-generated method stub
        return this.messageDAO.findAllSplit(column, keyWord, currentPage, lineSize);
    }

}