1.SSM简单使用
导入包
工程创建
目录结构
导入lib压缩包里的包,我这里使用maven导入
修改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.how2java</groupId>
<artifactId>ssm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring.version>4.1.3.RELEASE</spring.version>
<pagehelper.version>5.1.2-beta</pagehelper.version>
<mysql.version>5.1.6</mysql.version>
<mybatis.spring.version>1.2.3</mybatis.spring.version>
<mybatis.version>3.1.1</mybatis.version>
<junit.version>4.12</junit.version>
<jstl.version>1.2</jstl.version>
<jsqlparser.version>1.0</jsqlparser.version>
<jackson.version>1.2.7</jackson.version>
<servlet-api.version>3.1.0</servlet-api.version>
<druid.version>1.0.18</druid.version>
<log4j.version>1.2.16</log4j.version>
<commons-logging.version>1.2</commons-logging.version>
<commons-fileupload.version>1.2.1</commons-fileupload.version>
<commons-io.version>1.3.2</commons-io.version>
<commons-lang.version>2.6</commons-lang.version>
<aopalliance.version>1.0</aopalliance.version>
<mybatis-generator.version>1.3.5</mybatis-generator.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</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-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- JSP相关 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<!-- pageHelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${pagehelper.version}</version>
</dependency>
<!--jsqlparser-->
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>${jsqlparser.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>${commons-logging.version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons-lang.version}</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>${aopalliance.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>${mybatis-generator.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- 资源文件拷贝插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<!-- 配置Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</pluginManagement>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.tld</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
1.2 创建表并添加数据
CREATE TABLE category_ (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(30) ,
PRIMARY KEY (id)
) DEFAULT CHARSET=UTF8;
insert into category_ values(null,"category1");
insert into category_ values(null,"category2");
insert into category_ values(null,"category3");
insert into category_ values(null,"category4");
insert into category_ values(null,"category5");
select * from category_
1.3 先创建实体类
package com.llbk.pojo;
public class Category {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Category [id=" + id + ", name=" + name + "]";
}
}
1.4 创建mapper接口
package com.llbk.mapper;
import com.llbk.pojo.Category;
import java.util.List;
public interface CategoryMapper {
public int add(Category category);
public void delete(int id);
public Category get(int id);
public int update(Category category);
public List<Category> list();
public int count();
}
1.5 Category.xml
Category.xml需要和CategoryMapper放在同一个包下面,并且namespace必须写CategoryMapper的完整类名
<?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">
<!--将CategoryMapper和Category.xml关联起来-->
<mapper namespace="com.llbk.mapper.CategoryMapper">
<insert id="add" parameterType="Category" >
insert into category_ ( name ) values (#{name})
</insert>
<delete id="delete" parameterType="Category" >
delete from category_ where id= #{id}
</delete>
<select id="get" parameterType="_int" resultType="Category">
select * from category_ where id= #{id}
</select>
<update id="update" parameterType="Category" >
update category_ set name=#{name} where id=#{id}
</update>
<select id="list" resultType="Category">
select * from category_
</select>
</mapper>
1.6 CategoryService
package com.llbk.service;
import com.llbk.pojo.Category;
import java.util.List;
public interface CategoryService {
List<Category> list();
}
1.7 CategoryServiceImpl
package com.llbk.service.impl;
import com.llbk.mapper.CategoryMapper;
import com.llbk.pojo.Category;
import com.llbk.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/*@Service服务层组件,用于标注业务层组件,表示定义一个bean,自动根据bean的类名实例化一个首写字母为小写的bean,
例如Chinese实例化为chinese,如果需要自己改名字则:@Service("你自己改的bean名")*/
@Service
public class CategoryServiceImpl implements CategoryService{
//@Autowired按byType自动注入
@Autowired
CategoryMapper categoryMapper;
//调用list方法
public List<Category> list(){
return categoryMapper.list();
}
}
1.8 CategoryController
package com.llbk.controller;
import com.llbk.pojo.Category;
import com.llbk.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
// 告诉spring mvc这是一个控制器类
@Controller
//RequestMapping代表路径映射,加上的话下面的映射都可以是相对路径,但是删掉也没问题,所以不知道有什么用
@RequestMapping("")
public class CategoryController {
//注入CategoryServiceImpl,其实这里不懂
@Autowired
CategoryService categoryService;
@RequestMapping("listCategory")
public ModelAndView listCategory(){
ModelAndView mav = new ModelAndView();
List<Category> cs= categoryService.list();
// 放入转发参数
mav.addObject("cs", cs);
// 放入jsp路径
mav.setViewName("listCategory");
return mav;
}
}
1.9 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:web="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">
<!-- spring的配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- spring mvc核心:分发servlet -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- spring mvc的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
1.10 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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config />
<!--通过注解,将Service的生命周期纳入Spring的管理-->
<context:component-scan base-package="com.llbk.service" />
<!--配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/sys?characterEncoding=UTF-8</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>123456</value>
</property>
</bean>
<!--扫描类型,并且将将CategoryMapper和Category.xml关联起来-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--typeAliasesPackage写了之后就不用写完全路径-->
<property name="typeAliasesPackage" value="com.llbk.pojo" />
<!--dataSource数据源,在上面定义了-->
<property name="dataSource" ref="dataSource"/>
<!--mapperLocations意思是mapperLocations的映射位置-->
<property name="mapperLocations" value="classpath:com/llbk/mapper/Category.xml"/>
</bean>
<!--扫描Mapper,并将其生命周期纳入Spring的管理-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.llbk.mapper"/>
</bean>
</beans>
1.11 springMVC.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:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:annotation-config/>
<!--扫描Controller,并将其生命周期纳入Spring管理-->
<context:component-scan base-package="com.llbk.controller">
<!--
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
这段代码代表会只扫描base-package指定下的有@Controller下的java类,并注册成bean
-->
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<!-- 视图定位 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
1.12 listCategory.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<table align='center' border='1' cellspacing='0'>
<tr>
<td>id</td>
<td>name</td>
</tr>
<c:forEach items="${cs}" var="c" varStatus="st">
<tr>
<td>${c.id}</td>
<td>${c.name}</td>
</tr>
</c:forEach>
</table>
2.分页查询
2.1 分页类:Page
package com.llbk.util;
public class Page {
int start=0;
int count = 5;
int last = 0;
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getLast() {
return last;
}
public void setLast(int last) {
this.last = last;
}
public void caculateLast(int total) {
// 假设总数是50,是能够被5整除的,那么最后一页的开始就是45
if (0 == total % count)
last = total - count;
// 假设总数是51,不能够被5整除的,那么最后一页的开始就是50
else
last = total - total % count;
}
}
2.2 修改Category.xml
添加修改
<select id="list" resultType="Category">
select * from category_
<if test="start!=null and count!=null">
limit #{start},#{count}
</if>
</select>
<select id="total" resultType="int">
select count(*) from category_
</select>
2.3 CategoryMapper增加方法
public List<Category> list(Page page);
public int total();
2.4 修改CategoryService
public interface CategoryService {
List<Category> list();
int total();
List<Category> list(Page page);
void delete(int id);
}
2.5 CategoryServiceImpl
//Override是重写的意思
@Override
public List<Category> list(Page page) {
// TODO Auto-generated method stub
return categoryMapper.list(page);
}
@Override
public int total() {
return categoryMapper.total();
};
2.6 修改CategoryController
@RequestMapping("listCategory")
public ModelAndView listCategory(Page page){
ModelAndView mav = new ModelAndView();
List<Category> cs= categoryService.list(page);
int total = categoryService.total();
page.caculateLast(total);
// 放入转发参数
mav.addObject("cs", cs);
// 放入jsp路径
mav.setViewName("listCategory");
return mav;
}
2.7 修改listCategory.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<div style="width:500px;margin:0px auto;text-align:center">
<table align='center' border='1' cellspacing='0'>
<tr>
<td>id</td>
<td>name</td>
</tr>
<c:forEach items="${cs}" var="c" varStatus="st">
<tr>
<td>${c.id}</td>
<td>${c.name}</td>
</tr>
</c:forEach>
</table>
<div style="text-align:center">
<a href="?start=0">首 页</a>
<a href="?start=${page.start-page.count}">上一页</a>
<a href="?start=${page.start+page.count}">下一页</a>
<a href="?start=${page.last}">末 页</a>
</div>
</div>
2.使用 PAGEHELPER
2.1 导入包
2.2 修改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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config />
<!--通过注解,将Service的生命周期纳入Spring的管理-->
<context:component-scan base-package="com.llbk.service" />
<!--配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/sys?characterEncoding=UTF-8</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>123456</value>
</property>
</bean>
<!--扫描类型,并且将将CategoryMapper和Category.xml关联起来-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--typeAliasesPackage写了之后就不用写完全路径-->
<property name="typeAliasesPackage" value="com.llbk.pojo" />
<!--dataSource数据源,在上面定义了-->
<property name="dataSource" ref="dataSource"/>
<!--mapperLocations意思是mapperLocations的映射位置-->
<property name="mapperLocations" value="classpath:com/llbk/mapper/*.xml"/>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!--使用下面的方式配置参数,一行配置一个 -->
<value>
</value>
</property>
</bean>
</array>
</property>
</bean>
<!--扫描Mapper,并将其生命周期纳入Spring的管理-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.llbk.mapper"/>
</bean>
</beans>
2.3 CategoryService
public interface CategoryService {
List<Category> list();
}
2.4 CategoryServiceImpl
/*@Service服务层组件,用于标注业务层组件,表示定义一个bean,自动根据bean的类名实例化一个首写字母为小写的bean,
例如Chinese实例化为chinese,如果需要自己改名字则:@Service("你自己改的bean名")*/
@Service
public class CategoryServiceImpl implements CategoryService{
//@Autowired按byType自动注入
@Autowired
CategoryMapper categoryMapper;
//调用list方法
public List<Category> list(){
return categoryMapper.list();
}
}
2.5 CategoryMapper
public interface CategoryMapper {
public int add(Category category);
public void delete(int id);
public Category get(int id);
public int update(Category category);
public List<Category> list();
}
2.6 Category.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">
<!--将CategoryMapper和Category.xml关联起来-->
<mapper namespace="com.llbk.mapper.CategoryMapper">
<insert id="add" parameterType="Category" >
insert into category_ ( name ) values (#{name})
</insert>
<delete id="delete" parameterType="Category" >
delete from category_ where id= #{id}
</delete>
<select id="get" parameterType="_int" resultType="Category">
select * from category_ where id= #{id}
</select>
<update id="update" parameterType="Category" >
update category_ set name=#{name} where id=#{id}
</update>
<select id="list" resultType="Category">
select * from category_
</select>
</mapper>
2.7 CategoryController
// 告诉spring mvc这是一个控制器类
@Controller
//RequestMapping代表路径映射,加上的话下面的映射都可以是相对路径,但是删掉也没问题,所以不知道有什么用
@RequestMapping("")
public class CategoryController {
//注入CategoryServiceImpl,其实这里不懂
@Autowired
CategoryService categoryService;
@RequestMapping("listCategory")
public ModelAndView listCategory(Page page){
ModelAndView mav = new ModelAndView();
PageHelper.offsetPage(page.getStart(),5);
List<Category> cs= categoryService.list();
int total = (int) new PageInfo<>(cs).getTotal();
page.caculateLast(total);
// 放入转发参数
mav.addObject("cs", cs);
// 放入jsp路径
mav.setViewName("listCategory");
return mav;
}
}
2.8 运行
3.在SSM中使用C3P0连接池
3.1 修改applicationContext.xml
注释掉原有datasource,新增Druid连接池
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="jdbc:mysql://localhost:3306/sys?characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="123456" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="3" />
<property name="minIdle" value="3" />
<property name="maxActive" value="20" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<!--validationQuery该选项用来验证数据库连接的有效性-->
<property name="validationQuery" value="SELECT 1" />
<!--testWhileIdle:在检查闲置连接时同时检查连接可用性-->
<property name="testWhileIdle" value="true" />
<!--testOnBorrow:在借出连接时检查连接可用性-->
<property name="testOnBorrow" value="false" />
<!--testOnReturn:在客户端归还连接时检查连接可用性-->
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小
不是很明白有什么用-->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
</bean>
<!-- <!–配置数据源–>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/sys?characterEncoding=UTF-8</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>123456</value>
</property>
</bean>-->
3.2 运行
4.CRUD
4.1 listCategory.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<div style="width:500px;margin:0px auto;text-align:center">
<table align='center' border='1' cellspacing='0'>
<tr>
<td>id</td>
<td>name</td>
<td>编辑</td>
<td>删除</td>
</tr>
<c:forEach items="${cs}" var="c" varStatus="st">
<tr>
<td>${c.id}</td>
<td>${c.name}</td>
<td><a href="editCategory?id=${c.id}">编辑</a></td>
<td><a href="deleteCategory?id=${c.id}">删除</a></td>
</tr>
</c:forEach>
</table>
<div style="text-align:center">
<a href="?start=0">首 页</a>
<a href="?start=${page.start-page.count}">上一页</a>
<a href="?start=${page.start+page.count}">下一页</a>
<a href="?start=${page.last}">末 页</a>
</div>
<div style="text-align:center;margin-top:40px">
<form method="post" action="addCategory">
分类名称: <input name="name" value="" type="text"> <br><br>
<input type="submit" value="增加分类">
</form>
</div>
</div>
4.2 editCategory.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<div style="width:500px;margin:0px auto;text-align:center">
<div style="text-align:center;margin-top:40px">
<form method="post" action="updateCategory">
分类名称:
<input name="name" value="${c.name}" type="text"> <br>
分类id:
<input disabled="disabled" value="${c.id}" name="lj"><br>
<input type="hidden" value="${c.id}" name="id"><br>
<input type="submit" value="增加分类">
</form>
</div>
</div>
4.3 CategoryController
// 告诉spring mvc这是一个控制器类
@Controller
//RequestMapping代表路径映射,加上的话下面的映射都可以是相对路径,但是删掉也没问题,所以不知道有什么用
@RequestMapping("")
public class CategoryController {
//注入CategoryServiceImpl,其实这里不懂
@Autowired
CategoryService categoryService;
@RequestMapping("listCategory")
public ModelAndView listCategory(Page page){
ModelAndView mav = new ModelAndView();
PageHelper.offsetPage(page.getStart(),5);
List<Category> cs= categoryService.list();
int total = (int) new PageInfo<>(cs).getTotal();
page.caculateLast(total);
// 放入转发参数
mav.addObject("cs", cs);
// 放入jsp路径
mav.setViewName("listCategory");
return mav;
}
@RequestMapping("deleteCategory")
public ModelAndView deleteCategory(int id){
categoryService.deleteCategory(id);
return new ModelAndView("redirect:/listCategory");
}
@RequestMapping("editCategory")
public ModelAndView editCategory(int id){
ModelAndView mav = new ModelAndView();
Category c = categoryService.selectCategory(id);
mav.addObject("c",c);
mav.setViewName("editCategory");
return mav;
}
@RequestMapping("updateCategory")
public ModelAndView updateCategory(Category c){
categoryService.updateCategory(c);
return new ModelAndView("redirect:/listCategory");
}
@RequestMapping("addCategory")
public ModelAndView addCategory(Category c){
categoryService.addCategory(c);
return new ModelAndView("redirect:/listCategory");
}
}
4.4 CategoryServiceImpl
@Service
public class CategoryServiceImpl implements CategoryService{
//@Autowired按byType自动注入
@Autowired
CategoryMapper categoryMapper;
//调用list方法
public List<Category> list(){
return categoryMapper.list();
}
public void deleteCategory(int id) {
categoryMapper.delete(id);
}
public Category selectCategory(int id) {
return categoryMapper.get(id);
}
public void updateCategory(Category c) {
categoryMapper.update(c);
}
public void addCategory(Category c) {
categoryMapper.add(c);
}
}
4.5 CategoryMapper
public interface CategoryMapper {
public int add(Category category);
public void delete(int id);
public Category get(int id);
public int update(Category c);
public List<Category> list();
}
4.6 CategoryService
public interface CategoryService {
List<Category> list();
void deleteCategory(int id);
Category selectCategory(int id);
void updateCategory(Category c);
void addCategory(Category c);
}
5.SSM中进行注解式和XML配置式事务管理
5.1 导入aspectjweaver
5.2 CategoryService
增加
void addTwo();
void deleteAll();
5.3 CategoryServiceImpl
增加
public void deleteAll() {
List<Category> cs = list();
for (Category c : cs) {
categoryMapper.delete(c.getId());
}
}
@Override
/*
* Propagation.REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。这是最常见的选择。
* rollbackForClassName="Exception":导致事务回滚的异常类名字数组
* */
@Transactional(propagation= Propagation.REQUIRED,rollbackForClassName="Exception")
public void addTwo() {
Category c1 = new Category();
c1.setName("短的名字");
categoryMapper.add(c1);
Category c2 = new Category();
c2.setName("名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,");
categoryMapper.add(c2);
};
5.4 进行事务配置
修改applicationContext.xml,添加事务管理器和事务注解扫描器
<!--配置事务管理-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
5.5 运行
参考网站:https://how2j.cn/k/ssm/ssm-tutorial/1137.html

2430

被折叠的 条评论
为什么被折叠?



