1. 程式人生 > >做一個合格的程式猿之Spring MVC+Spring + mybatis + Bootstrap 整合

做一個合格的程式猿之Spring MVC+Spring + mybatis + Bootstrap 整合

準備環境:JDK1.7+MAVEN+Eclipse

1) 開啟Eclipse 點選Window-->Preferences-->Maven--->User Settings 配置一下你的Maven配置檔案setting.xml

2)新建Maven專案

記得勾選紅色方框中的鉤,點選Next,出現如下:

將packaging中的jar修改成pom,如上圖所示,Group Id為你的基本包名,可以任意命名,點選Finish,完成後出現

開啟study-pom中的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>org.lyncc</groupId>
	<artifactId>study-pom</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>

	<properties>
		<spring.version>4.0.1.RELEASE</spring.version>
		<mybatis.version>3.2.4</mybatis.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.9</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</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-context-support</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.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>2.0.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.0.2</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.11</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.8.4</version>
		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.18.2-GA</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.28</version>
		</dependency>

		<!-- mybatis核心包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>
		<!-- mybatis/spring包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
		</dependency>
	</dependencies>

</project>
3)新建Maven模組Maven Module

選擇Maven Module然後點選Next,如下


Module Name輸入study-intf(該maven模組是介面模組),然後點選Browse

選擇study-pom然後點選ok,回到上個視窗,點選Next,出現:

選擇如上圖紅色框框選中的quickstart,點選NEXT:

點選Finish,如下圖:

4)再次新建maven模組,模組名為study-service(service模組),新建方法與上述步驟3中一致,只是在Moudle Name修改為study-service,建立好如下圖所示:


5)新建maven-moudle,模組名為study-web

點選Next


選擇webapp,點選Next:

點選Finish:

分別開啟study-intf,service,web模組中的pom.xml檔案,將有黃色下劃線的去掉,否則專案會有warning警告),例外,依次修改study-intf,service,web的預設依賴的jdk版本,分別右擊專案模組,然後依次修改為


然後依次修改pom的依賴

study-intf下的pom.xml如下:

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.lyncc</groupId>
    <artifactId>study-pom</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>study-intf</artifactId>
  <name>study-intf</name>
  <url>http://maven.apache.org</url>
 
</project>
study-service下的pom.xml如下:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.lyncc</groupId>
    <artifactId>study-pom</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>study-service</artifactId>
  <name>study-service</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.lyncc</groupId>
      <artifactId>study-intf</artifactId>
      <version>${project.version}</version>
    </dependency>
  </dependencies>
</project>
study-web下的pom.xml需要新增web的依賴
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.lyncc</groupId>
    <artifactId>study-pom</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>study-web</artifactId>
  <packaging>war</packaging>
  <name>study-web Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
		<spring.version>4.0.1.RELEASE</spring.version>
	</properties>
  <dependencies>
   <dependency>
      <groupId>org.lyncc</groupId>
      <artifactId>study-service</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-mapper-asl</artifactId>
		<version>1.9.11</version>
	</dependency>
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-core-asl</artifactId>
		<version>1.9.11</version>
	</dependency>
	<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
  </dependencies>
  <build>
    <finalName>study-web</finalName>
  </build>
</project>

6)修改study-web下的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" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0">
	<display-name>study-web</display-name>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:spring-mybatis.xml,classpath*:spring.xml</param-value>
	</context-param>

	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.xml</param-value>
	</context-param>

	<context-param>
		<param-name>rootLevel</param-name>
		<param-value>DEBUG</param-value>
	</context-param>

	<context-param>
		<param-name>loggingLevel</param-name>
		<param-value>INFO</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>

	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath*:spring-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<filter>
		<filter-name>encodingFilter</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>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>
選擇study-web,新建spring.xml,spring-servlet.xml,log4j.xml

spring.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:aop="http://www.springframework.org/schema/aop" xmlns:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <context:component-scan base-package="org.study">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
</beans>
spring-servlet.xml
<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"
       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/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
       
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    
     <context:component-scan base-package="org.study.lyncc.web.controller" >
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> 
    </context:component-scan>  
    
    <mvc:resources mapping="/fonts/**" location="/WEB-INF/fonts/"/>
    <mvc:resources mapping="/resources/**" location="/WEB-INF/resources/"/>


    <bean id="viewResolver"  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/jsp/"></property>  
        <property name="suffix" value=".jsp"></property>  
    </bean> 
    
</beans>
log4j.xml
<?xml version="1.0" encoding="UTF-8"?>    
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">  
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">  
  <!-- [控制檯STDOUT] -->  
  <appender name="console" class="org.apache.log4j.ConsoleAppender">  
     <param name="encoding" value="GBK" />  
     <param name="target" value="System.out" />  
     <layout class="org.apache.log4j.PatternLayout">  
       <param name="ConversionPattern" value="%-5p %c{2} - %m%n" />  
     </layout>  
  </appender>  
  
  <!-- [公共Appender] -->  
  <appender name="DEFAULT-APPENDER" class="org.apache.log4j.DailyRollingFileAppender">  
     <param name="File" value="${webapp.root}/logs/common-default.log" />  
     <param name="Append" value="true" />  
     <param name="encoding" value="GBK" />  
     <param name="DatePattern" value="'.'yyyy-MM-dd'.log'" />  
     <layout class="org.apache.log4j.PatternLayout">  
    <param name="ConversionPattern" value="%d %-5p %c{2} - %m%n" />  
     </layout>  
   </appender>  
  
   <!-- [錯誤日誌APPENDER] -->  
   <appender name="ERROR-APPENDER" class="org.apache.log4j.DailyRollingFileAppender">  
     <param name="File" value="${webapp.root}/logs/common-error.log" />  
     <param name="Append" value="true" />  
     <param name="encoding" value="GBK" />  
     <param name="threshold" value="error" />  
     <param name="DatePattern" value="'.'yyyy-MM-dd'.log'" />  
     <layout class="org.apache.log4j.PatternLayout">  
        <param name="ConversionPattern" value="%d %-5p %c{2} - %m%n" />  
     </layout>  
   </appender>  
  
   <!-- [元件日誌APPENDER] -->  
   <appender name="COMPONENT-APPENDER"  
class="org.apache.log4j.DailyRollingFileAppender">  
     <param name="File" value="${webapp.root}/logs/logistics-component.log" />  
     <param name="Append" value="true" />  
     <param name="encoding" value="GBK" />  
     <param name="DatePattern" value="'.'yyyy-MM-dd'.log'" />  
     <layout class="org.apache.log4j.PatternLayout">  
    <param name="ConversionPattern" value="%d %-5p %c{2} - %m%n" />  
     </layout>  
   </appender>  
  
   <!-- [元件日誌] -->  
   <logger name="LOGISTICS-COMPONENT">  
      <level value="${loggingLevel}" />  
      <appender-ref ref="COMPONENT-APPENDER" />  
      <appender-ref ref="ERROR-APPENDER" />  
   </logger>  
  
   <!-- Root Logger -->  
   <root>  
       <level value="${rootLevel}"></level>  
       <appender-ref ref="DEFAULT-APPENDER" />  
       <appender-ref ref="ERROR-APPENDER" />  
       <appender-ref ref="console" /> 
       <appender-ref ref="COMPONENT-APPENDER" /> 
   </root>  
</log4j:configuration>  

7)在study-intf的src/main/resources(可能需要自己新建)新增jdbc.properties,,mybatis-config.xml,spring-mybatis.xml檔案

jdbc.properites

jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=utf-8
jdbc_username=root
jdbc_password=

mybatis-config.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 alias="User" type="org.study.intf.lyncc.entity.User"/> 
    </typeAliases>
    <mappers>
    </mappers>
</configuration>
spring-mybatis.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:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util-3.2.xsd">
    
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean>
 
 
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc_driverClassName}" />
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />
    </bean>
    
	
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
     
    <!-- mybatis檔案配置,掃描所有mapper檔案 -->
      <bean id="sqlSessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean"
          p:dataSource-ref="dataSource"
          p:configLocation="classpath:mybatis-config.xml"
          p:mapperLocations="classpath:mapper/*.xml"/> 
       
   <!-- spring與mybatis整合配置,掃描所有dao -->
 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
        p:basePackage="org.study.intf.lyncc.mapper"
        p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
  
</beans>
資料庫建表語句:
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `age` int(11) NOT NULL,
  `mail` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4;

INSERT INTO `user` VALUES ('1', '曾子墨', '123456', '25', '[email protected]');
INSERT INTO `user` VALUES ('2', '吳神', '234456', '24', '[email protected]');
INSERT INTO `user` VALUES ('3', '張巖', '654321', '23', '[email protected]');
INSERT INTO `user` VALUES ('4', '武松', '12wsas', '45', '[email protected]');
INSERT INTO `user` VALUES ('5', '孫悟空', 'qwert', '5000', '[email protected]');
INSERT INTO `user` VALUES ('6', '孫燕姿', 'yanzi', '29', '[email protected]');
INSERT INTO `user` VALUES ('7', '京東', 'JD', '15', '[email protected]');
INSERT INTO `user` VALUES ('8', '淘寶', 'taobao', '19', '[email protected]');
INSERT INTO `user` VALUES ('9', '蘑菇街', 'mogujie', '6', '[email protected]');
INSERT INTO `user` VALUES ('10', '噹噹', 'dangdang', '11', '[email protected]');
INSERT INTO `user` VALUES ('11', 'facebook', 'facebook', '12', '[email protected]');

好了,到此為止所有的準備工作都好了,接下來就是寫程式碼了

UserController.java

package org.study.lyncc.web.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.study.intf.lyncc.entity.User;
import org.study.service.UserService;


@Controller
@RequestMapping(value="/user")
public class UserController {
	

	@Resource
	private UserService userService;
	
	@ResponseBody
	@RequestMapping(value="test")
	public List<User> getAllList(){
		List<User> users = userService.getAllUser();
		return users;
	}
	
	
	@RequestMapping(value="list")
	public String list(){
		return "list";
	}
	
	@ResponseBody
	@RequestMapping("/page")
	public Map<String, Object> page(@RequestParam Map<String, Object> requestMap){
		
		int limit = Integer.valueOf("" + requestMap.get("limit"));
		int offset = Integer.valueOf("" + requestMap.get("offset"));
		List<User> users = userService.findByPage(limit,offset);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("status", "success");
		resultMap.put("total", userService.findCount());
		resultMap.put("rows", users);
		
		return resultMap;
	}
	
	
}

UserService.java
package org.study.service;

import java.util.List;

import org.study.intf.lyncc.entity.User;

public interface UserService {

	List<User> getAllUser();

	List<User> findByPage(int limit, int offset);

	Integer findCount();

}

UserSerivceImpl.java
package org.study.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.study.intf.lyncc.entity.User;
import org.study.intf.lyncc.mapper.UserMapper;
import org.study.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Resource
	private UserMapper userMapper;

	public List<User> getAllUser() {
		return userMapper.findAllUser();
	}

	public List<User> findByPage(int limit, int offset) {
		return userMapper.findByPage(limit,offset);
	}

	public Integer findCount() {
		return userMapper.countAll();
	}

}

UserMapper.java

package org.study.intf.lyncc.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.study.intf.lyncc.entity.User;


public interface UserMapper{

	List<User> findAllUser();

	List<User> findByPage(@Param("limit")Integer limit,@Param("offset")Integer offset);

	Integer countAll();
	
 
}
UserMapper.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="org.study.intf.lyncc.mapper.UserMapper">

 	<resultMap type="User" id="userInfo">
	     <id property="id" column="id"/>
		 <result property="username" column="username"/>
		 <result property="mail" column="mail"/>
		 <result property="age" column="age"/>
		 <result property="password" column="password"/>
	</resultMap>
	
	<select id="findAllUser" resultMap="userInfo">
	  select * from user
	</select>
	
	<select id="findByPage" resultMap="userInfo">
	     select * from user limit #{offset},#{limit}
	</select>
	
	<select id="countAll" resultType="Integer">
	  select count(*) from user
	</select>
	 
</mapper>
User.java
package org.study.intf.lyncc.entity;

import java.io.Serializable;

 
public class User implements Serializable {
	
	
	private static final long serialVersionUID = 1L;
	
	private Integer id;  
	
    private String username;  
    
    private String password;  
    
    private int age;
    
    private String mail;

    public User() {
    	
    }


    public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getMail() {
		return mail;
	}

	public void setMail(String mail) {
		this.mail = mail;
	}

	 
}
list.html
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Demo</title>
<link rel="stylesheet" href="${ctx}/resources/bootstrap-table.min.css">
<script type="text/javascript" src="${ctx}/resources/jquery-1.11.1.min.js"/></script>
<script type="text/javascript" src="${ctx}/resources/bootstrap-table.min.js"></script>
<link rel="stylesheet" href="${ctx}/resources/bootstrap.min.css">
<script type="text/javascript" src="${ctx}/resources/bootstrap.min.js"></script>
</head>
<body >
	<div class="page-container">
	  <div style="height:500px">
	   <table class="table table-bordered table-striped" id="usertable">
	   </table>
	   </div>
	</div>
</body>
<script type="text/javascript">
$(function(){
	 $("#usertable").bootstrapTable({
		 method:'get',
		 url:"${ctx}/user/page",
		 cache: false, 
		 striped: true,
		 pagination: true,
		 pageList: [10,20,50],
		 pageSize:10,
		 pageNumber:1,
		 queryParams: function(params){
		 		paramsReturn = {
					limit: params.limit,
					offset: params.offset,
				};
			 	return paramsReturn;
		 },
		 sidePagination:'server',
		 contentType: "application/x-www-form-urlencoded",
		 showColumns: true, 
		 showRefresh: true,  
		 smartDisplay:true,
		 columns: [
          {  
				field: 'id',  
				title: '編號',  
				align: 'center',  
				width: '60',  
				valign: 'middle',	
          },
          {  
        	  	field: 'username', 
          	    title: '名稱',  
				align: 'center',  
				width: '60',  
				valign: 'middle', 
          },
          {  
				field: 'age',  
				title: '年齡',  
				align: 'center',  
				width: '40',  
				valign: 'middle',
          },
          {   
        	  	field: 'password',
          		title: '密碼',  
				align: 'center',  
				width: '120',  
				valign: 'middle',
          },
          {
        	    field: 'mail',
				title: '郵箱',  
				align: 'center',  
				width: '40',  
				valign: 'middle', 
          },
          {
				title: '使用者操作',  
				align: 'center',  
				width: '240',  
				valign: 'middle', 
				formatter: function(value,row,index){
	        		 var str = "";
	            	 if(row.type == 0)
	            		 str += '<button class="btn btn-secondary btn-xs"><i class="fa fa-edit"></i><span>檢視</span></button>';
	            	 else
	            		 str += '<button class="btn btn-warning btn-xs"><i class="fa fa-edit"></i><span >編輯</span></button>';
	            	 return str;
   			}
          },
	     ]
	 });
});
</script>
</html>
就做了簡單的分頁功能,效果圖如下:


好了,到此為止,基本程式碼已經貼出了,bootstrap的包在附件中,這邊就不貼出了,原始碼下載地址是(下載後用jdk1.7編譯):

http://download.csdn.net/detail/linuu/9454826

如果有問題,請指出~

相關推薦

spring mvcmybatis事務整合

  之前公司用的是mybatis,但事務管理這塊是用ejb的CMT容器管理的事務。基本原理是ejb請求進來,業務程式碼會建立一個mybatis的session然後放入當前執行緒,之後所有的方法操作涉及到資料庫的都從當前執行緒取session。當所有service層程式碼完成

一個合格程式Spring MVC+Spring + mybatis + Bootstrap 整合

準備環境:JDK1.7+MAVEN+Eclipse 1) 開啟Eclipse 點選Window-->Preferences-->Maven--->User Settings 配置一下你的Maven配置檔案setting.xml 2)新建Maven專案

一個合格程式淺析Spring IoC原始碼(十)Spring Bean的初始化順序

上幾節我們比較詳細地說明了一下BeanFactoryPostProcessor和BeanPostProcessor這2個介面的作用和意義,並且也花了一個章節,講了一下BeanFactory和FactoryBean的關係,最後我們也稍微說明了一下BeanFactoryAwar

一個合格程式淺析Spring IoC原始碼(十一)Spring refresh()方法解析後記1

上次分析refresh這塊spring IoC的時候,時間比較倉促,只是debug了部分原始碼,大家分析起來不是很好~ 今天我們還是先總結一下吧~ spring在例項化bean的時候,根據bean

一個合格程式淺析Spring IoC原始碼(十一)Spring refresh()方法解析之一

經過上面幾節的簡單介紹我們瞭解了spring的一些元件,現在我們來分析一下AbstractApplicationContext中的refresh()這個核心方法吧~ 用我們上一節的程式碼,debug進入refresh方法: public void refresh() th

一個合格程式淺析Spring AOP原始碼(十五) 分析JdkDynamicAopProxy的invoke方法

 上一節我們已經分析了Proxyfactorybean如何去生成一個目標物件的代理的,這一節我們將淺析一下基於JDK動態代理的核心回撥方法invoke的原始碼: 首先先開啟JdkDynamicAop

4.6 基於Spring-Boot的Mysql+jpa的增刪改查學習記錄 > 我的程式路:第三十六章

    1.專案結構       -JDK  1.8       -SpringBoot  2.0.6     &nbs

一個合格程式設計師需要具備哪些素質?

 程式設計師是一種技術工作.在IT的發展中有相當重要的地位.從底層硬體通訊協議的建立. 到資料傳輸層的處理.到作業系統的建設.到資料庫平臺的建設.一直到應用層上各種數 據營銷平臺的搭建.程式設計師在裡面都扮演著舉足輕重的角色併為IT事業的發展做出了巨大 的貢獻. 中國

4.6 基於Spring-Boot的Mysql+jpa的增刪改查學習記錄 > 我的程式路:第三十六章

1.專案結構       -JDK  1.8       -SpringBoot  2.0.6       -Thymeleaf       -Hot Start         1.1 後臺(5個)       java\com\example\demo\beans\user.java        

4.7 基於Spring註解的定時任務(@Schedule) > 我的程式路:第三十七章

Cron表示式是一個字串,字串以5或6個空格隔開,分為6或7個域,每一個域代表一個含義,Cron有如下兩種語法格式:  Seconds Minutes Hours DayofMonth Month DayofWeek Year或 Seconds Minutes Hours DayofMonth Month

4.4 Spring-bootidea熱部署 > 我的程式路:第三十四章

1、點選: file ,Settings ,Build ,Execution,Deplment,compiler 然後記得apply,ok。 2、組合鍵:Shift+ALT+Ctrl+/ ,選擇“Registry”,找到“complier.automake.allow.when.app.running”

4.5 Spring-Boot自定義更新Maven依賴包空間倉庫 > 我的程式路:第三十五章

SpringBoot預設會把依賴所用的框架和jar包等下載到 C:\Users\admin\.m2 下,有時候啟動專案會報一些bug,可能是包衝突引起的。    自定義倉庫 1.File   --   Other Settings  --  Settings for New Projects  -- Buil

一個合格程式設計師該的事情

程式設計師每天應該做的事1、總結自己一天任務的完成情況最好的方式是寫工作日誌,把自己今天完成了什麼事情,遇見了什麼問題都記錄下來,日後翻看好處多多2、考慮自己明天應該做的主要工作把明天要做的事情列出來,並按照優先順序排列,第二天應該把自己效率最高的時間分配給最重要的工作3、考

一個合格的前端,gulp自動化構建工具入門教程

安裝完成 基本 合成 node.js 文件替換 mage 9.png basename 加載 我的新作觀點網http://www.guandn.com (觀點網是一個獵獲新奇、收獲知識、重在獨立思考的網站),它前端js、css的壓縮、合並、md5命名等就使用了gulp自動化

maven初始搭建一個基礎項目(spring mvc+spring+jdbc mysql+)

mon 處理 名稱 archetype HA name -m web.xml 控制器 技術選型: 一.項目搭建: 1)創建maven項目 (我博客裏面有介紹)   選擇aptach的maven-archetype-webapp   填入groupIDhe ar

001 一個合格的噴子---springcloud起步

span manage 過程 all pom -s 環境 編寫 import 一 .概述   本次開始springcloud的學習,參考的資料有springcloud微服務實踐--翟永超和周立的springcloud與docker實踐.國內的書籍不多,但是這兩本都算不錯,覆

從0開始的web程式

        寫寫自己剛入程式設計師,然後又走向JAVA,web短短一年的經驗和經歷,寫給未來自己,也寫給迷茫的新人們,讓他們少走一點彎路。         剛開始,學了c,就想做東西,現實狠狠的告訴我,發現只學了c做不了什麼

5.0 SpringBoot普通上傳功能 > 我的程式路:第四十章

SpringBoot 2.0 1.upLoad.html 1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta ch

5.2 SpringBoot實現斷點續傳功能 > 我的程式路:第四十二章

  功能使用webuploader元件分片下載檔案 文件地址: http://fex.baidu.com/webuploader/document.html 從  http://fex.baidu.com/webuploader/download.html中下載 用到的是:

崔永元 一個合格的公民

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!