Spring+SpringMVC+mybatis入门(环境搭建+crud)

大学毕业快一年了,在学校里做了一个android APP的项目,一直都只是熟悉android后台开发是最大的短板,工作后,公司都是自己的框架,这种开源框架基本也没时间去接触。app和后台都是基于公司的平台开发,我觉得一个人做也没有啥难度。一直在混日子,把整个app的架构分析了一遍。后来公司业务需求,我被迫PC端和android客户端都的做。真心现在啥都不是研究的很深。心累。吐槽完毕。接下来,记录我自己学习ssm框架完成crud的整个过程。

一、开发环境搭建

1、新建一个动态web项目

点击完成工程就创建完毕。本文是以ssm为工程的如下:

2、配置基于SSM的开发环境

2,1添加springmvc和mybatis的整合需要的所有jar包

jar包下载将在后面提供。

2.2配置web.xml

2.2.1加载spring容器

如下所示是spring配置的类所在的路径:

<!-- 加载spring容器 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
	</context-param>
	<listener>

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

2.2.2springmvc前端控制器

<!-- springmvc前端控制器 -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) 如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml) -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring/springmvc.xml</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>

		<url-pattern>*.action</url-pattern>
	</servlet-mapping>

2.2.3post乱码过虑器

 <!-- post乱码过虑器 -->
	<filter>
		<filter-name>CharacterEncodingFilter</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>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

2.2.4整个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/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SSM</display-name>

  <!-- 加载spring容器 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
	</context-param>
	<listener>

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

	<!-- springmvc前端控制器 -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) 如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml) -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring/springmvc.xml</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>

	</servlet-mapping>

  <!-- post乱码过虑器 -->
	<filter>
		<filter-name>CharacterEncodingFilter</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>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

2.3创建配置文件

工程下建立源文件夹

创建spring相关的配置文件夹:

首先在config文件夹下创建如下文件:

db.properties

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/mybatis

jdbc.username=root

jdbc.password=mysql

log4j.properties

# Global logging configuration\uff0c\u5efa\u8bae\u5f00\u53d1\u73af\u5883\u4e2d\u8981\u7528debug

log4j.rootLogger=DEBUG, stdout

# Console output...

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

然后在spring文件夹下配置如下文件

applicationContext-dao.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-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/aop
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

	<!-- 加载db.properties文件中的内容,db.properties文件中key命名要有一定的特殊规则 -->
	<context:property-placeholder location="classpath:db.properties" />
	<!-- 配置数据源 ,dbcp -->

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxActive" value="30" />
		<property name="maxIdle" value="5" />
	</bean>
	<!-- sqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 数据库连接池 -->
		<property name="dataSource" ref="dataSource" />
		<!-- 加载mybatis的全局配置文件 -->
		<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
	</bean>
	<!-- mapper扫描器 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
		<property name="basePackage" value="com.yqq.ssm.mapper"></property>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	</bean>

</beans>
applicationContext-service.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-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/aop
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 商品管理的service -->
<bean id="itemsService" class="com.yqq.ssm.service.impl.ItemsServiceImpl"/>
</beans>
applicationContext-transaction.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-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/aop
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

<!-- 事务管理器
	对mybatis操作数据库事务控制,spring使用jdbc的事务控制类
-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<!-- 数据源
	dataSource在applicationContext-dao.xml中配置了
	 -->
	<property name="dataSource" ref="dataSource"/>
</bean>

<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
	<tx:attributes>
		<!-- 传播行为 -->
		<tx:method name="save*" propagation="REQUIRED"/>
		<tx:method name="delete*" propagation="REQUIRED"/>
		<tx:method name="insert*" propagation="REQUIRED"/>
		<tx:method name="update*" propagation="REQUIRED"/>
		<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
		<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
		<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
	</tx:attributes>
</tx:advice>
<!-- aop -->
<aop:config>
	<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.yqq.ssm.service.impl.*.*(..))"/>
</aop:config>

</beans>

创建mybatis相关的文件夹

sqlMapConfig.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>

	<!-- 全局setting配置,根据需要添加 -->

	<!-- 配置别名 -->
	<typeAliases>
		<!-- 批量扫描别名 -->
		<package name="com.yqq.ssm.po"/>
	</typeAliases>

	<!-- 配置mapper
	由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。
	必须遵循:mapper.xml和mapper.java文件同名且在一个目录
	 -->

	<!-- <mappers>

	</mappers> -->
</configuration>

逆向工程生成po类和mapper接口

修改数据库连接

运行后生成的代码

为了生成动态代理对象,servce能自动注入需要确保如下配置。

编写service层类

Service层的方法需要注册到spring容器中

编写控制层controller

控制层调用service层的方法。通过modeandview返回数据给视图层(视图层通过addobject key取数据)。

视图层

调用控制层方法:

function queryItems(){

//提交form

document.itemsForm.action="${pageContext.request.contextPath }/items/getItemInfo.action?id=1";

document.itemsForm.submit();

}

<input type="button" value="查询" onclick="queryItems()"/>

http://localhost:8080/SSM/items/getItemInfo.action?id=1即可访问

至此环境搭建完成。

下面进行crud操作。

1、首先,需要建立一个test2数据库。

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/test2

jdbc.username=root

jdbc.password=admin

2、dao开发

便于扩展,定义如下三个类

package com.yqq.ssm.po;

import java.util.Date;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotEmpty;

public class Items {

    private Integer id;

    private String name;

    private Float price;

    private String pic;

    private Date createtime;

    private String detail;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic == null ? null : pic.trim();
    }

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail == null ? null : detail.trim();
    }
}
package com.yqq.ssm.po;

public class ItemsCustom extends Items {

}
package com.yqq.ssm.po;

public class ItemsCustomVO  {
	private Items items;
	private ItemsCustom itemsCustom;
	public Items getItems() {
		return items;
	}

	public void setItems(Items items) {
		this.items = items;
	}

	public ItemsCustom getItemsCustom() {
		return itemsCustom;
	}

	public void setItemsCustom(ItemsCustom itemsCustom) {
		this.itemsCustom = itemsCustom;
	}

}

编写ItemCustomMapper.xmll映射文件

<?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.yqq.ssm.mapper.ItemCustomMapper" >

<insert id="saveItems" parameterType="itemsCustomVO" >
<selectKey keyProperty="itemsCustom.id" order="AFTER" resultType="java.lang.Integer" >
select LAST_INSERT_ID()
</selectKey>
insert into items(name,price,pic,createtime,detail) values(#{itemsCustom.name},#{itemsCustom.price},
#{itemsCustom.pic},#{itemsCustom.createtime},#{itemsCustom.detail})

</insert>

<insert id="saveItemsUUID" parameterType="itemsCustomVO" >
<selectKey keyProperty="itemsCustom.id" order="BEFORE" resultType="java.lang.String" >
select uuid()
</selectKey>
insert into items(name,price,pic,createtime,detail) values(#{itemsCustom.name},#{itemsCustom.price},#{itemsCustom.pic},#{itemsCustom.createtime},#{itemsCustom.detail})

</insert>

<select id="getAllItemsInfos" resultType="itemsCustom">

select * from items

</select>

<update id="updItems" parameterType="itemsCustomVO" >

update items set name=#{itemsCustom.name},price=#{itemsCustom.price},pic=#{itemsCustom.pic},createtime=#{itemsCustom.createtime},
detail=#{itemsCustom.detail}  where id=#{itemsCustom.id}

</update>

<update id="updItems2" parameterType="itemsCustomVO">

update items set name=#{itemsCustom.name},price=#{itemsCustom.price},pic=#{itemsCustom.pic},createtime=#{itemsCustom.createtime},
detail=#{itemsCustom.detail}  where id=#{itemsCustom.id}

</update>

<delete id="delItembyId" parameterType="int">

delete from items where id=#{id}

</delete>

</mapper>

定义ItemCustomMapper..java接口

package com.yqq.ssm.mapper;

import java.util.List;

import com.yqq.ssm.po.ItemsCustom;
import com.yqq.ssm.po.ItemsCustomVO;

public interface ItemCustomMapper {

	 int saveItems(ItemsCustomVO v) throws Exception;
	 int  saveItemsUUID(ItemsCustomVO v) throws Exception;

	 List<ItemsCustom> getAllItemsInfos() throws Exception;

	 void updItems(ItemsCustomVO v)throws Exception;

	 void delItembyId(int v)throws Exception;

}

编写service层代码

定义service接口,如下:

注册服务给controller使用:

控制层:

整个学习项目访问的地址:http://localhost:8080/SSM/items/getAllItemsInfos.action

代码下载地址:http://download.csdn.net/detail/u014600432/9527779

时间: 2024-12-12 16:09:34

Spring+SpringMVC+mybatis入门(环境搭建+crud)的相关文章

Spring+SpringMvc+Mybatis框架集成搭建教程

一.背景 最近有很多同学由于没有过SSM(Spring+SpringMvc+Mybatis , 以下简称SSM)框架的搭建的经历,所以在自己搭建SSM框架集成的时候,出现了这样或者那样的问题,很是苦恼,网络上又没有很详细的讲解以及搭建的教程.闲来无事,我就利用空闲时间来写这样一个教程和搭建步骤,来帮助那些有问题的小伙伴,让你从此SSM搭建不再有问题. 二.教程目录 1.Spring+SpringMvc+Mybatis框架集成搭建教程一(项目创建) 2.Spring+SpringMvc+Mybat

用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建三:配置spring并测试

这一部分的主要目的是 配置spring-service.xml  也就是配置spring  并测试service层 是否配置成功 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建二:配置MyBatis 并测试(2 配置spring-dao和测试)在这个基础上面 继续进行spring的配置. 回顾上面  我们已经成功测试通过了Mybatis的配置. 这时候的目录结构是: 一:下面我们继续补充目录结构,在com.peakfortake的文件目录项目 

Spring+SpringMvc+Mybatis框架集成搭建教程一(背景介绍及项目创建)

一.背景 最近有很多同学由于没有过SSM(Spring+SpringMvc+Mybatis , 以下简称SSM)框架的搭建的经历,所以在自己搭建SSM框架集成的时候,出现了这样或者那样的问题,很是苦恼,网络上又没有很详细的讲解以及搭建的教程.闲来无事,我就利用空闲时间来写这样一个教程和搭建步骤,来帮助那些有问题的小伙伴,让你从此SSM搭建不再有问题. 二.搭建步骤 1.框架搭建环境 Spring 4.2.6.RELEASE SpringMvc 4.2.6.RELEASE Mybatis 3.2.

Spring+SpringMVC+MyBatis框架的搭建

1,SSM的简介 SSM(Spring+SpringMVC+MyBatis)框架集由Spring.SpringMVC.MyBatis三个开源框架整合而成,常作为数据源较简单的web项目的框架. 其中spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架. SpringMVC分离了控制器.模型对象.分派器以及处理程序对象的角色,这种分离让它们更容易进行定制. MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架. 2,SSM的搭建 项目的结构如下: 首先配

Spring+SpringMvc+Mybatis框架集成搭建教程二(依赖配置及框架整合)

依赖导入以及框架整合 (1).打开项目的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/maven-v4_

[转]SSM(Spring+SpringMVC+Mybatis)框架搭建详细教程【附源代码Demo】

一.新建项目 运行IDEA,进入初始化界面,然后我们选择新建项目(进入主界面新建项目也是一样的) 在Maven选项卡里面找到对应的java web选项,然后我们点下一步 这一步填入组织等信息,这里比较随意,按照自己的需求进行填写,然后下一步 这里我早已配置好本地Maven仓库,因此直接默认即可.如果没进行配置本地默认仓库的话,请网上查找对应的资料进行配置 输入Project name,和需要保存的路径,然后finish 去泡一杯咖啡吧,这里需要一小段时间哦~ 稍等片刻,idea已经为我们自动建好

Spring+SpringMvc+Mybatis框架集成搭建教程四(项目部署及测试)

在IDEA中将项目部署到本地Tomcat下进行运行并验证整合结果 (1).点击如下图所示的下拉按钮,弹出Edit Configurations...后点击该项. (2).跳出如下界面后,点击红框内的"+"号,选择Tomcat Server->Local (3).出现以下界面,修改自定义启动项的名称.配置本地tomcat (4).选择要运行的项目 (5).指定项目运行的ContextPath (6).点击启动按钮,启动项目 (7).在浏览器中输入控制器的url,观察输出结果 打印出

spring+springMVC+Maven+mysql环境搭建

转载: http://www.importnew.com/20215.html 首先看一下项目截图: 搭建完毕,访问结果: mysql数据 CREATE TABLE `t_user` ( `USER_ID` int(11) NOT NULL AUTO_INCREMENT, `USER_NAME` char(30) NOT NULL, `USER_PASSWORD` char(10) NOT NULL, PRIMARY KEY (`USER_ID`), KEY `IDX_NAME` (`USER_

Mybatis入门环境搭建

1.依赖jar包 mybatis-3.2.2.jar  sqlserver2008.jar 2.代码 package ttyouni.model; public class Student { public int ID; public String UserName; public String Password; public int getID() { return ID; } public void setID(int iD) { ID = iD; } public String get