spring-整合mvc-druid-mybatis

http://localhost/ssm-v1/log/doFindPageObjects.do?pageCurrent=1

业务架构mvc


sys_logs

/ssm-v1/pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.jt</groupId>
    <artifactId>ssm-v1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.29</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
</project>

/ssm-v1/src/main/resources/config.properties

jdbcDriver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql:///jtsys?useUnicode=true&characterEncoding=utf-8
jdbcUsername=root
jdbcPassword=123456

/ssm-v1/src/main/resources/spring-configs.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="  
       http://www.springframework.org/schema/beans   
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd  
       http://www.springframework.org/schema/mvc   
       http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd   
       http://www.springframework.org/schema/tx   
       http://www.springframework.org/schema/tx/spring-tx-4.3.xsd   
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
       http://www.springframework.org/schema/util 
       http://www.springframework.org/schema/util/spring-util-4.3.xsd
       http://www.springframework.org/schema/data/jpa 
       http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    <context:component-scan base-package="com.jt"/>
    <import resource="classpath:spring-mvc.xml" />
    <import resource="classpath:spring-mybatis.xml" />
</beans>

/ssm-v1/src/main/resources/spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="  
       http://www.springframework.org/schema/beans   
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd  
       http://www.springframework.org/schema/mvc   
       http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd   
       http://www.springframework.org/schema/tx   
       http://www.springframework.org/schema/tx/spring-tx-4.3.xsd   
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
       http://www.springframework.org/schema/util 
       http://www.springframework.org/schema/util/spring-util-4.3.xsd
       http://www.springframework.org/schema/data/jpa 
       http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    <mvc:annotation-driven />
    <!--配置springMVC视图解析器(负责视图解析操作) -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀 -->
        <property name="Prefix" value="/WEB-INF/pages/"></property>
        <property name="Suffix" value=".jsp"></property>
    </bean>
</beans>

/ssm-v1/src/main/resources/mapper/sys/SysLogMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jt.dao.SysLogDao">
    <sql id="queryWhereId">
        <where>
            <if test="username!=null and username!=''">
                username like concat('%',#{username},'%')
            </if>
        </where>
    </sql>
    <select id="findPageObjects" resultType="com.jt.entity.SysLog">
        select * from sys_logs
        <include refid="queryWhereId" />
        order by createdTime desc
        limit #{startIndex},#{pageSize}
    </select>
    <select id="getRowCount" resultType="int">
        select count(*) from sys_logs
        <include refid="queryWhereId" />
    </select>
</mapper>

/ssm-v1/src/main/resources/spring-mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="  
       http://www.springframework.org/schema/beans   
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd  
       http://www.springframework.org/schema/mvc   
       http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd   
       http://www.springframework.org/schema/tx   
       http://www.springframework.org/schema/tx/spring-tx-4.3.xsd   
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
       http://www.springframework.org/schema/util 
       http://www.springframework.org/schema/util/spring-util-4.3.xsd
       http://www.springframework.org/schema/data/jpa 
       http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    <util:properties id="cfg" location="classpath:config.properties"></util:properties>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close" lazy-init="false">
        <property name="driverClassName" value="#{cfg.jdbcDriver}"></property>
        <property name="url" value="#{cfg.jdbcUrl}"></property>
        <property name="username" value="#{cfg.jdbcUsername}"></property>
        <property name="password" value="#{cfg.jdbcPassword}"></property>
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="1800" />
        <property name="MaxActive" value="10" />
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="BasePackage" value="com.jt.**.dao"/>
        <!--下面这行可以不写,但是有多个 sqlSessionFactory会报错 -->
        <property name="SqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
    <!--整合SqlSessionFactoryBean对象(通过此对象创建SqlSession)  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" lazy-init="true">
        <property name="dataSource" ref="dataSource"></property>
    <property name="mapperLocations" value="classpath:mapper/sys/*Mapper.xml"/>
    </bean>
</beans>

/ssm-v1/src/main/webapp/index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首页</title>
</head>
<body>
    SpringMVC
</body>
</html>

/ssm-v1/src/main/webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="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_2_5.xsd" version="2.5">
  <display-name>ssm-v1</display-name>
 <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <!--配置SpringMVC前端控制器-->
    <!--注册前端控制器-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--初始化参数读取配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-configs.xml</param-value>
        </init-param>
        <!--配置servlet在服务启动时加载(数字越小,优先级越高)
        配置如下选项以后,tomcat启动时会初始化这个servlet
        这个servlet在初始化时会读取contextConfigLocation参数对应的配置文件。-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!--配置前端控制器-->
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

/ssm-v1/src/main/java/com/jt/common/exception/ServiceException.java

package com.jt.common.exception;

public class ServiceException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public ServiceException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public ServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }

    public ServiceException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

    public ServiceException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public ServiceException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }
    

}

/ssm-v1/src/main/java/com/jt/common/vo/JsonResult.java

package com.jt.common.vo;


public class JsonResult {
    //状态码:1表示正确,0表示错误
    private int state=1;
    //状态码对应的信息
    private String message="OK";
    //正确数据通过此属性进行封装,例如查询的结果
    private Object data;
    public JsonResult(){}
    public JsonResult(String message){
        this.message=message;
    }
    //初始化正确的数据
    public JsonResult(Object data) {
        this.data=data;
    }
    /**出现异常时可以通过此方法初始化异常信息*/
    public JsonResult(Throwable e){
        this.state=0;//表示错误信息
        this.message=e.getMessage();
    }
    public int getState() {
        return state;
    }
    public void setState(int state) {
        this.state = state;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
    
}

/ssm-v1/src/main/java/com/jt/common/vo/PageObject.java

对象要序列化需要实现序列化接口
添加序列化ID是为了反序列化的时候起作用,比方说序列化的时候有四个字段,但是后面对对象做了改动如又加了字段,或少了字段,或加了方法,类变化了,要想反序列化,没有序列化ID就失败。

package com.jt.common.vo;

import java.io.Serializable;
import java.util.List;
/**
 * 业务层值对象,负责封装业务层数据
 * @param <T>
 */
public class PageObject<T> implements Serializable{
    private static final long serialVersionUID = 1L;
//类泛型
    /**下面这些值和表没有对应关系,可以用int*/
    /**当前页的记录信息*/
    private List<T> records;
    /**总记录数*/
    private int rowCount;
    /**总页数*/
    private int pageCount;
    /**页面大小*/
    private int pageSize=3;
    /**当前页的页码*/
    private int pageCurrent=1;
    public List<T> getRecords() {
        return records;
    }
    public void setRecords(List<T> records) {
        this.records = records;
    }
    public int getRowCount() {
        return rowCount;
    }
    public void setRowCount(int rowCount) {
        this.rowCount = rowCount;
    }
    public int getPageCount() {
        return pageCount;
    }
    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
    public int getPageCurrent() {
        return pageCurrent;
    }
    public void setPageCurrent(int pageCurrent) {
        this.pageCurrent = pageCurrent;
    }
    @Override
    public String toString() {
        return "PageObject [records=" + records + ", rowCount=" + rowCount + ", pageCount=" + pageCount + ", pageSize="
                + pageSize + ", pageCurrent=" + pageCurrent + "]";
    }
    
}

/ssm-v1/src/main/java/com/jt/common/web/GlobalExceptionHandler.java

package com.jt.common.web;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jt.common.vo.JsonResult;
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理运行时异常
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public JsonResult doHandleRuntimeException(RuntimeException e){
        /**
         * 封装异常信息
         */
        e.printStackTrace();
        return new JsonResult(e);
    }
}

/ssm-v1/src/main/java/com/jt/controller/SysLogController.java

package com.jt.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jt.common.vo.JsonResult;
import com.jt.service.SysLogService;

@RequestMapping("/log/")
@Controller
public class SysLogController {
    @Autowired
    private SysLogService SysLogService;
    
    @RequestMapping("doFindPageObjects")
    @ResponseBody
    public JsonResult doFindPageObjects(String username,Integer pageCurrent){
        return new JsonResult(SysLogService.findPageObjects(username,pageCurrent));
    }
}

/ssm-v1/src/main/java/com/jt/dao/SysLogDao.java

username在动态sql中使用了,需要在dao中的方法加@Param修饰。如果没有注解修饰,在基于名字进行查询时会出现There is no getter for property named 'username' in class java.lang.String

package com.jt.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.jt.entity.SysLog;

public interface SysLogDao {
    /**
     * 基于条件分页查询日志信息
     * @param username 查询条件(查询哪个用户的日志信息)
     * @param startIndex 当前页的起始位置
     * @param pageSize 当前页面的大小
     * @return 当前页的日志记录信息
     * 数据库中每条日志信息封装到一个SysLog对象中
     */
    List<SysLog> findPageObjects(@Param("username")String username,@Param("startIndex")Integer startIndex,@Param("pageSize")Integer pageSize);
    /**
     * 基于条件查询总记录数
     * @param username 查询条件(基于用户名查询)
     * @return 总记录数(基于这个结果可以计算总页数)
     */
    int getRowCount(@Param("username")String username);
}

/ssm-v1/src/main/java/com/jt/service/impl/SysLogServiceImpl.java

package com.jt.service.impl;

import java.util.List;

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

import com.jt.common.exception.ServiceException;
import com.jt.dao.SysLogDao;
import com.jt.entity.SysLog;
import com.jt.service.SysLogService;
import com.jt.common.vo.PageObject;
@Service
public class SysLogServiceImpl implements SysLogService {

    @Autowired
    private SysLogDao sysLogDao;
    public SysLogDao getSysLogDao() {
        return sysLogDao;
    }
    public void setSysLogDao(SysLogDao sysLogDao) {
        this.sysLogDao = sysLogDao;
    }
    @Override
    public PageObject<SysLog> findPageObjects(String username, Integer pageCurrent) {
        //1.参数有效性验证(只验证pageCurrent)
        if(pageCurrent==null||pageCurrent<1)
            throw new IllegalArgumentException("页码值有误");
        //2.查询总记录数并进行验证
        int rowCount = sysLogDao.getRowCount(username);
        if(rowCount==0)
            throw new ServiceException("没有对应记录");
        //3.查询当前页日志数据
        int pageSize=2;
        int startIndex=(pageCurrent-1)*pageSize;
        List<SysLog> records = sysLogDao.findPageObjects(username, startIndex, pageSize);
        //4.对查询结果进行封装
        PageObject<SysLog>po=new PageObject<SysLog>();
        po.setRecords(records);
        po.setRowCount(rowCount);
        po.setPageSize(pageSize);
        po.setPageCurrent(pageCurrent);
    /*  int pageCount=rowCount/pageSize;
        if(rowCount%pageSize!=0){
            pageCount++;
        }*/
        po.setPageCount((rowCount-1)/pageSize+1);
        //5.返回结果
        return po;
    }

}

/ssm-v1/src/main/java/com/jt/service/SysLogService.java

package com.jt.service;

import com.jt.common.vo.PageObject;
import com.jt.entity.SysLog;

public interface SysLogService {
    /**
     * 依据条件分页查询日志信息
     * @param username 用户名
     * @param pageCurrent 当前页码
     * @return 对查询结果的封装
     */
    PageObject<SysLog> findPageObjects(String username,Integer pageCurrent);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,122评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,070评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,491评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,636评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,676评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,541评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,292评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,211评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,655评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,846评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,965评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,684评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,295评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,894评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,012评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,126评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,914评论 2 355

推荐阅读更多精彩内容