Springmvc+Mybatis+Velocity实现小demo(Maven项目)

转:https://blog.csdn.net/FoolishAndStupid/article/details/52005934

Velocity只是充当一个展示层,和JSP的功能类似,利用mybatis从数据库中取出数据,然后进行数据处理,最后通过Velocity在页面上展示出来。
环境搭建主要分为几个过程,第一步是配置pom文件依赖,第二步是配置spring配置文件:applicationContext.xml,第三步就是开始写DAO接口和对应的mapping.xml文件,然后是Service接口和ServiceImpl类,最后就是写controller。需要注意的是里面用到一些spring的autowire,这个关系要缕清。
目录
目录
1.pom文件依赖:
1.添加Velocity依赖:

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>

注意要是apache下的velocity,而不是以下这种:

<dependency>
<groupId>velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.5</version>
<type>pom</type>
</dependency>

2.添加springmvc依赖:

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>

3.添加mybatis,c3p0数据源等依赖

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>

<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</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.1.1</version>
</dependency>

2.spring配置文件

applicationContext.xml配置文件主要包含几个部分,一个是springmvc的,一个是velocity的,还有mybatis的配置。记得要在web.xml中配置一下applicationContext.xml的位置。
1.springmvc配置

<!--包扫描-->
<context:component-scan base-package="com.lumingfeng"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 配置文件,classpath*:*.properties 表示加载多个配置文件,即时有重名的 -->
<context:property-placeholder location="classpath:*.properties"
ignore-unresolvable="false" />
<!-- 配置文件,classpath*:*.properties 表示加载多个配置文件,即时有重名的,ignore-un..=false(如果无法解决就忽视=否)表示如果找到不到配置文件里面对应的属性
就报异常,true表示跳过这个属性而不报异常-->
<context:property-placeholder location="classpath:*.properties"
ignore-unresolvable="false" />

<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>

2.velocity配置

<!-- Velocity配置 -->
<bean id="velocityConfigurer"
class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<!-- 模板位置,即vm(html)文件的位置 -->
<property name="resourceLoaderPath" value="WEB-INF/views"></property>
<property name="velocityProperties">
<props>
<prop key="directive.foreach.counter.name">loopCounter</prop>
<prop key="directive.foreach.counter.initial.value">0</prop>
<prop key="input.encoding">UTF-8</prop><!-- 指定模板引擎进行模板处理的编码 -->
<prop key="output.encoding">UTF-8</prop><!-- 指定输出流的编码 -->
</props>
</property>
</bean>

<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<!-- 以什么什么结尾,注意不需要跟jsp的视图解析器一样配置prefix,因为前缀和上面的velocityConfigurer配置的位置是一样的 -->
<property name="suffix" value=".html"></property>
<!-- 类型 -->
<property name="contentType" value="text/html;charset=UTF-8" />
<property name="dateToolAttribute" value="dateTool" />
<property name="numberToolAttribute" value="numberTool" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
</bean>

在视图解析器的定义中,

“exposeSpringMacroHelpers”设置是否通过Spring的宏库暴露一个RequestContext(名为springBindRequestContext)供外部使用,默认值为false。它暴露了处理表单和验证错误信息的宏操作;

“requestContextAttribute”把Spring的RequestContext对象暴露为变量content。利用“content.contextPath”来获取应用程序的contextPath;利用

{content.getMessage(“user.name”)}读取/WEB-INF/classes/messages.properties本地化信息。此对象可以为那些不访问serlvet请求的View技术(类似Velocity和FreeMarker模板)提供不少的方便。

exposeRequestAttributes:默认值false,设置是否所有的request属性在与模板进行合并之前添加到model中。(request范围内包含的所有对象,而不是一个Request对象。)

exposeSessionAttributes:默认值false,设置是否所有的session属性在与模板进行合并之前添加到model中。(理解同上)
3.mybatis配置

配置数据源:

<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>

配置Mybatis:
这里需要搞清楚dao接口,mapping.xml文件都是干嘛的。dao接口就只是一个接口,里面也没有mybatis的@Insert等注解,然后接口里面的增删查改的具体实现方法就是在mapping.xml文件里面的,所以可以将一个dao接口和一个mapping.xml文件相对应。
当然还有另外一种写法就是直接在dao接口上添加增删查改的注解,然后写上sql语句,这种方法就可以不需要mapping.xml文件。

<!-- 配置Mybatis -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--dataSource属性指定要用到的连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件,因为mybatis是在配置文件中执行的对数据库的操作,我把它统一放到了resource/mybatis文件夹下 -->
<property name="mapperLocations" value="classpath:mybatis/*.xml" />
</bean>

<!-- DAO接口所在包名,Mapper扫描配置,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.lumingfeng.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

3.DAO接口和mapping.xml文件

这两个都是利用mybatis-generator自动生成的,可以不用细看,但是这种自动生成的还是比较简单,只针对单个表的增删查改,如果需要联表查询还是得自己手写mapping.xml文件。
DAO接口:

@Repository
public interface IUserDao {
int deleteByPrimaryKey(Integer id);

int insert(User record);

int insertSelective(User record);

User selectByPrimaryKey(Integer id);

int updateByPrimaryKeySelective(User record);

int updateByPrimaryKey(User record);
}

mapping.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.lumingfeng.dao.IUserDao" >
<resultMap id="BaseResultMap" type="com.lumingfeng.entity.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
<result column="sex" property="sex" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
id, name, age, sex
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.lumingfeng.entity.User" >
insert into user (id, name, age,
sex)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},
#{sex,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.lumingfeng.entity.User" >
insert into user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="name != null" >
name,
</if>
<if test="age != null" >
age,
</if>
<if test="sex != null" >
sex,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="name != null" >
#{name,jdbcType=VARCHAR},
</if>
<if test="age != null" >
#{age,jdbcType=INTEGER},
</if>
<if test="sex != null" >
#{sex,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.lumingfeng.entity.User" >
update user
<set >
<if test="name != null" >
name = #{name,jdbcType=VARCHAR},
</if>
<if test="age != null" >
age = #{age,jdbcType=INTEGER},
</if>
<if test="sex != null" >
sex = #{sex,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.lumingfeng.entity.User" >
update user
set name = #{name,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER},
sex = #{sex,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>

4.Service接口及ServiceImpl
Service接口

@Component
public interface IUserSerivice {

int deleteByPrimaryKey(Integer id);

int insert(User record);

int insertSelective(User record);

User selectByPrimaryKey(Integer id);

int updateByPrimaryKeySelective(User record);

int updateByPrimaryKey(User record);
}

ServiceImpl:


@Service("userService")
public class UserServiceImpl implements IUserSerivice{

@Resource
private IUserDao userdao;

public int deleteByPrimaryKey(Integer id) {
return userdao.deleteByPrimaryKey(id);
}
public int insert(User record) {
return this.userdao.insert(record);
}
public int insertSelective(User record) {
return insertSelective(record);
}
public User selectByPrimaryKey(Integer id) {
return userdao.selectByPrimaryKey(id);
}
public int updateByPrimaryKeySelective(User record) {
return userdao.updateByPrimaryKeySelective(record);
}
public int updateByPrimaryKey(User record) {
return userdao.updateByPrimaryKey(record);
}
}

5.Controller


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

@Resource(name="userService")
private IUserSerivice userService;

@RequestMapping("/index")
public ModelAndView index(){
System.out.println("11");
User user = userService.selectByPrimaryKey(1);
ModelAndView view =new ModelAndView("index");
view.addObject("name", user.getName());

return view;

}
}

6.Velocity展示层

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en_US" xml:lang="en_US">
<head>
<title> </title>
</head>
<body>
hello,$name
</body>
</html>

用Velocity展示数据还是挺方便的。
7.效果

数据库数据
查询结果:

这里还有一种不用mapping.xml文件的方式,即给dao接口添加注解,举个例子:

@Repository
public interface IUserDao {

@Delete("delete from user where id =#{id}")
int deleteByPrimaryKey(Integer id);
}

以上这种写法,我把mapping.xml文件删了,然后测试之后发现也是可以删除用户的。其他配置保持不变。

当然,mybatis,Velocity的更多特性就等着大家去研究发现了…

原文地址:https://www.cnblogs.com/zhanglijun/p/9836500.html