近来由于公司项目的需要,暂时放下了前端android的开发,慢慢投入到后台接口系统搭建,在经过与众兄弟的讨论下,决定就使用最常规的框架去搭建一个后台接口系统,这样一方面大家都比较的熟悉,另一方面对于新人和后期的维护都会相对比较容易一些,因此,针对这一系列框架最基础的搭建,在此做一个简单的总结,希望能对这一块儿还相对陌生的猿猿能有所帮助
先上源码,点击下载
阅读请参考博客:SpringMvc+MyBatis+MySQL+Maven+Redis搭建一个基础的web项目
(根据个人需要;可用可不用)
- 资源下载
maven-3.2.1版本下载
- 解压压缩包
如下图:
- 配置环境变量
- 如第一步中配置jdk一样,进入到环境变量配置页面
- 添加“MAVEN_HOME”配置解压后maven的路径
如下图:
- 将maven路径指定到path下
如下图:
- 测试
打开cmd (如果还是之前测试jdk的cmd窗口,请关闭了重新打开)输入:mvn -v 如果出现以下效果,说明已经安装成功:
- 调整maven的配置文件
- 找到解压路径下的conf文件,进去找到setting.xml配置文件
- 将该配置文件拷贝至“C:\Users\Administrator.m2”路径下
配置到这里的目的是为了以后我们更新了maven的版本之后,不需要出现配置setting文件,至需要更换一下环境变量即可,如下图:
- 打开setting文件,找到“localRepository”配置自己本机maven仓库的路径(根据个人习惯配置),如果不配置这个路径,默认会在将以下路径“C:\Users\Administrator.m2\repository“作为Maven仓库
- Myeclipse配置Maven
打开MyEclipse,选择Window–>Preferences–>Maven4MyEclipse–>User Settings,配置上一步中修改的settings.xml文件,如下图:
(根据个人需要,redis可用可不用)
可参考资料Redis安装
创建maven项目
项目结构调整
Date: 2017-07-02 19:20:45
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for userinfo
-- ----------------------------
DROP TABLE IF EXISTS `userinfo`;
CREATE TABLE `userinfo` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(20) NOT NULL,
`AGE` int(5) DEFAULT NULL,
`SEX` int(1) DEFAULT NULL,
`ADD` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of userinfo
-- ----------------------------
INSERT INTO `userinfo` VALUES ('1', '张三', '10', '0', '北京');
INSERT INTO `userinfo` VALUES ('2', '李四', '20', '1', '上海');
INSERT INTO `userinfo` VALUES ('3', '赵五', '23', '1', '广州');
INSERT INTO `userinfo` VALUES ('4', '钱六', '50', '0', '台湾');
Maven的pom.xml配置
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<spring.version>3.2.8.RELEASEspring.version>
<slf4j.version>1.6.6slf4j.version>
<log4j.version>1.2.12log4j.version>
<junit.version>4.10junit.version>
<mybatis.version>3.2.1mybatis.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>${junit.version}version>
<scope>testscope>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.2.0version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.29version>
dependency>
<dependency>
<groupId>javaxgroupId>
<artifactId>javaee-apiartifactId>
<version>6.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javaxgroupId>
<artifactId>javaee-web-apiartifactId>
<version>6.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.7.4version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.7.4version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.7.4version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.32version>
dependency>
<dependency>
<groupId>org.springframework.datagroupId>
<artifactId>spring-data-redisartifactId>
<version>1.3.0.RELEASEversion>
dependency>
<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
<version>2.6.2version>
dependency>
dependencies>
添加成功保存,Maven会自动下载相应的对应版本的包到本地仓库;由于部分资源包在不同的网络环境下下载会比较慢,如果Maven下载不下来,我在百度云盘共享了一份上面各个版本对应的包,可以下载下来解压到本地的仓库即可使用;点击下载
MyBatis配置
jdbc属性配置文件
在properties文件夹下创建jdbc.properties,并配置以下参数:
jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://127.0.0.1:3306/springmvcdb
jdbc_username=lpf
jdbc_password=123456
mybatis配置
这里直接配置在application.xml;请参考后续的applocation配置
redis配置
redis参数配置文件
在redis文件夹下创建redis.properties,添加如下参数:
redis.pool.maxTotal=105
redis.pool.maxIdle=10
redis.pool.maxWaitMillis=5000
redis.pool.testOnBorrow=true
redis.host=127.0.0.1
redis.port=6379
redis.password=
redis.db.index=0
redis基础配置
在redis下创建redis-config.xml文件,并添加一下配置文件:
version="1.0" encoding="UTF-8"?>
"http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
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">
-- 缓存的层级 -->
"com.lpf.springmvc" />
-- 引入redis配置 -->
--
/> -->
-- Redis 配置 -->
id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.pool.maxTotal}" />
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" />
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
id="jedisPool" class="redis.clients.jedis.JedisPool">
name="poolConfig" ref="jedisPoolConfig" />
name="host" value="${redis.host}" />
name="port" value="${redis.port}" type="int" />
name="timeout" value="${redis.pool.maxWaitMillis}" type="int" />
name="password" value="#{'${redis.password}'!=''?'${redis.password}':null}" />
name="database" value="${redis.db.index}" type="int" />
-- JedisCluster 集群高可用配置 -->
--
index="0"> <set> class="redis.clients.jedis.HostAndPort"> "0" value="${redis.ip1}" /> "1" value="${redis.port1}"
type="int" /> class="redis.clients.jedis.HostAndPort"> "0" value="${redis.ip2}" /> "1" value="${redis.port2}"
type="int" /> class="redis.clients.jedis.HostAndPort"> "0" value="${redis.ip3}" /> "1" value="${redis.port3}"
type="int" /> class="redis.clients.jedis.HostAndPort"> "0" value="${redis.ip4}" /> "1" value="${redis.port4}"
type="int" /> class="redis.clients.jedis.HostAndPort"> "0" value="${redis.ip5}" /> "1" value="${redis.port5}"
type="int" /> class="redis.clients.jedis.HostAndPort"> "0" value="${redis.ip6}" /> "1" value="${redis.port6}"
type="int" /> set> "1"
value="2000" type="int"> "2" value="100"
type="int"> "3" ref="jedisPoolConfig">
-->
--redis Sentinel主从高可用方案配置 -->
--
<property name="master"> class="org.springframework.data.redis.connection.RedisNode">
<property name="name" value="master-1">property> property> <property
name="sentinels"> <set> class="org.springframework.data.redis.connection.RedisNode">
name="host" value="${sentinel1.ip}"> name="port" value="${sentinel1.port}"> class="org.springframework.data.redis.connection.RedisNode">
name="host" value="${sentinel2.ip}"> name="port" value="${sentinel2.port}"> class="org.springframework.data.redis.connection.RedisNode">
name="host" value="${sentinel3.ip}"> name="port" value="${sentinel3.port}"> set> property>
id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:use-pool="true"> <property name="password" value="${redis.pass}" /> <property
name="poolConfig"> <ref bean="jedisPoolConfig" /> property> name="sentinelConfig" ref="sentinelConfiguration" /> -->
-- redis单节点数据库连接配置 -->
id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<property name="password" value="${redis.password}" />
<property name="poolConfig" ref="jedisPoolConfig" />
-- redisTemplate配置,redisTemplate是对Jedis的对redis操作的扩展,有更多的操作,封装使操作更便捷 -->
id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
redis dao层相关配置
接口定义
在Dao文件加下创建一个用于获取redis下数据的接口(以获取一个文本型的数据为例)
package com.lpf.springmvc.dao;
import org.springframework.stereotype.Repository;
@Repository
public interface RedisDao
{
String get(String key);
}
创建Jedis帮助对象
一个公共的帮助类,代码太长,放到网盘了,下载下来即可:JedisUtil
package com.lpf.springmvc.dao;
import javax.annotation.Resource;
import com.lpf.springmvc.utils.JedisUtil;
import redis.clients.jedis.JedisPool;
public class RedisDaoImpl implements RedisDao
{
@Resource
JedisPool jedisPool;
public String get(String key)
{
// TODO Auto-generated method stub
JedisUtil jedisUtil = new JedisUtil(jedisPool);
JedisUtil.Strings strings = jedisUtil.new Strings();
System.out.println("cache: " + strings.get(key));
return strings.get(key);
}
}
SpringMvc相关配置
<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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULLvalue>
property>
bean>
property>
bean>
mvc:message-converters>
mvc:annotation-driven>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" />
list>
property>
bean>
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" />
list>
property>
bean>
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="text" />
<constructor-arg index="1" value="plain" />
<constructor-arg index="2" value="UTF-8" />
bean>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="*" />
<constructor-arg index="1" value="*" />
<constructor-arg index="2" value="UTF-8" />
bean>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="text" />
<constructor-arg index="1" value="*" />
<constructor-arg index="2" value="UTF-8" />
bean>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="application" />
<constructor-arg index="1" value="json" />
<constructor-arg index="2" value="UTF-8" />
bean>
list>
property>
bean>
<context:component-scan base-package="com.lpf.springmvc.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/view/" p:suffix=".jsp" />
beans>
application.xml配置
在配置文件根目录下创建一个application.xml配置文件,并添加如下的配置代码:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/jdbc.propertiesvalue>
<value>classpath:redis/redis.propertiesvalue>
list>
property>
bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${jdbc_driverClassName}value>
property>
<property name="url">
<value>${jdbc_url}value>
property>
<property name="username">
<value>${jdbc_username}value>
property>
<property name="password">
<value>${jdbc_password}value>
property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.lpf.springmvc.dao" />
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath*:com/lpf/springmvc/mapper/**/*.xml" />
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
bean>
<bean id="redisDao" class="com.lpf.springmvc.dao.RedisDaoImpl">
bean>
<import resource="redis/redis-config.xml" />
<context:component-scan base-package="com.lpf.springmvc.service" />
beans>
项目web.xml配置
打开src–>main–>webapp–>WEB-INF–>web.xml,配置如下代码:
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>display-name>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:application.xmlparam-value>
context-param>
<context-param>
<param-name>webAppRootKeyparam-name>
<param-value>springmvc.rootparam-value>
context-param>
<filter>
<filter-name>SpringEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>SpringEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<context-param>
<param-name>log4jConfigLocationparam-name>
<param-value>classpath:log4j.propertiesparam-value>
context-param>
<context-param>
<param-name>log4jRefreshIntervalparam-name>
<param-value>6000param-value>
context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListenerlistener-class>
listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc/spring-mvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<error-page>
<error-code>404error-code>
<location>/WEB-INF/errorpage/404.jsplocation>
error-page>
<error-page>
<error-code>405error-code>
<location>/WEB-INF/errorpage/405.jsplocation>
error-page>
<error-page>
<error-code>500error-code>
<location>/WEB-INF/errorpage/500.jsplocation>
error-page>
web-app>
主要用于梳理从前端–>controller–>service–>dao 处理完数据再回去的这么一个过程
dao层相关代码编写
用户 信息dao层接口定义
定义2个方法,分别用于获取所有用户信息和根据id获取指定用户信息,代码如下
package com.lpf.springmvc.dao;
import java.util.List;
import com.lpf.springmvc.model.UserInfo;
/**
* 操作用户消息的dao
* @author lupf
*
*/
public interface UserInfoDao {
/**
* 获取所有的用户
* @return
*/
public List getUserInfos();
/**
* 根據用戶id获取用户消息
* @param id
* @return
*/
public UserInfo getUserInfoByID(int id);
}
MyBatis mapper配置文件
添加用户信息相关的mapper配置文件,在mapper文件夹下创建user-info-mapper.xml,并添加以下代码:
<mapper namespace="com.lpf.springmvc.dao.UserInfoDao">
<resultMap id="BaseResultMap" type="com.lpf.springmvc.model.UserInfo">
<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="INTEGER" />
<result column="ADD" property="add" jdbcType="VARCHAR" />
resultMap>
<select id="getUserInfoByID" parameterType="int" resultMap="BaseResultMap">
SELECT * FROM userinfo WHERE ID = #{id}
select>
<select id="getUserInfos" resultMap="BaseResultMap">
SELECT * FROM userinfo
select>
mapper>
用户service配置
定义service接口
用于获取用户信息的service,根本用来根据id获取和获取所以,service基本和到差不对匹配,但是不是绝对匹配
package com.lpf.springmvc.service;
import java.util.List;
import com.lpf.springmvc.model.UserInfo;
/**
* 操作用户消息的service
*
* @author lupf
*
*/
public interface UserInfoService {
/**
* 获取所有的用户
*
* @return
*/
public List getUserInfos();
/**
* 根據用戶id获取用户消息
*
* @param id
* @return
*/
public UserInfo getUserInfoByID(int id);
/**
* 根据redis的key获取redis的一个文本型value
* @param key
* @return
*/
public String getValueByRedisKey(String key);
}
用户信息service的具体实现
package com.lpf.springmvc.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.lpf.springmvc.dao.RedisDao;
import com.lpf.springmvc.dao.UserInfoDao;
import com.lpf.springmvc.model.UserInfo;
@Service
public class UserInfoServiceImpl implements UserInfoService {
@Resource
UserInfoDao userInfoDao;
@Resource
RedisDao redisDao;
@Override
public List getUserInfos() {
// TODO Auto-generated method stub
return userInfoDao.getUserInfos();
}
@Override
public UserInfo getUserInfoByID(int id) {
// TODO Auto-generated method stub
return userInfoDao.getUserInfoByID(id);
}
@Override
public String getValueByRedisKey(String key) {
// TODO Auto-generated method stub
return redisDao.get(key);
}
}
记住,需要在类上添加@Service的注解,service才会被自动注入进来;在service中引入dao,即可操作数据;
用户信息controller
view层代码编写
在WEB-INF下的view文件夹(该文件的路径在spring-mvc.xml中配置了)下添加一个用于获取了一个用户之后,绑定用户信息的user.jsp页面,代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<body>
<h2>Hello World!h2>
编号:${user.id}<br>
姓名:${user.name}<br>
年龄:${user.age}<br>
性别:${user.sex==0?"女":"男"}<br>
地址:${user.add}<br>
body>
html>
controller代码编写
主要用户和前段交互的入口,代码如下:
package com.lpf.springmvc.controller;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.lpf.springmvc.model.UserInfo;
import com.lpf.springmvc.service.UserInfoService;
@Controller
public class UserInfoController {
protected Logger logger = LoggerFactory.getLogger(getClass());
@Resource
UserInfoService userInfoService;
@RequestMapping("/userInfo")
public ModelAndView getUserInfoByID(int id) {
// 指定view层的页面,参数user即为对应的jsp的名称
ModelAndView mav = new ModelAndView("user");
if (id <= 0)
id = 1;
// 获取数据
UserInfo userInfo = userInfoService.getUserInfoByID(id);
// 将获取到的对象添加到ModelAndView对象中
mav.addObject("user", userInfo);
return mav;
}
@RequestMapping("/getUserInfos")
@ResponseBody
public List getUserInfos() {
List users = userInfoService.getUserInfos();
logger.info(""+JSON.toJSONString(users));
return users;
}
}
RequestMapping指明了前端请求该方法的路径。如getUserInfoByID方法配置了userInfo这个注解,那么前段请求时候的路径即为:http://localhost:8080/SpringMvc/userInfo
getUserInfoByID方法解析
该方法主要用于前段jsp界面的请求;实例化的ModelAndView指明了绑定的view界面,上面方法中添加了 ;获取到数据添加到ModelAndView中即可自动绑定到相应的位置。
前端测试地址为:http://localhost:8080/SpringMvc/userInfo?id=1;界面显示效果如下:
getUserInfos方法解析
该接口主要用于给前端提供api接口时使用,添加了@ResponseBody即可,因为RequestMapping注解为getUserInfos;前端请求即以getUserInfos作为该方法的请求路径。
前端测试地址为:http://localhost:8080/SpringMvc/getUserInfos;前端显示效果如下:
针对上面service的具体实现,我们通过Junit进行一下单元测试;在没有前端的情况下即可完成接口的调试。
代码编写
在src/test/java目录下编写但愿测试代码
创建测试代码的基类,代码如下:
package com.lpf.springmvc.test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//指定bean注入的配置文件
@ContextConfiguration(locations = { "classpath:application.xml" })
// 使用标准的JUnit @RunWith注释来告诉JUnit使用Spring TestRunner
@RunWith(SpringJUnit4ClassRunner.class)
public abstract class SpringTestCase extends AbstractJUnit4SpringContextTests {
protected Logger logger = LoggerFactory.getLogger(getClass());
}
编写service测试代码
package com.lpf.springmvc.test;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import com.lpf.springmvc.model.UserInfo;
import com.lpf.springmvc.service.UserInfoService;
public class UserInfoTest extends SpringTestCase {
@Resource
UserInfoService usersInfoService;
@Test
public void selectUserByIdTest() {
UserInfo user = usersInfoService.getUserInfoByID(1);
logger.debug("查找结果" + user);
}
@Test
public void selectUserInfosTest() {
List users = usersInfoService.getUserInfos();
logger.debug("查找结果" + JSON.toJSONString(users));
}
@Test
public void getValueByRedisKey(){
String va =usersInfoService.getValueByRedisKey("name");
logger.debug("key为name的redis数据:"+va);
}
}
写好上面的测试代码,选择方法名,右键–>Run as –>JUnit test运行,如下图:
到这里,一个基于SpringMvc+MyBatis+MySQL+Maven+Redis搭建一个常规的web项目就已经完成了,虽然没有写什么很牛的技术点;但是涵盖的每个技术所需要用到的东西;后续会对MyBatis和redis进行更详细的,便于更好的在项目中运用,提高项目的性能。