学习内容链接
http://how2j.cn/k/tmall_ssm/tmall_ssm-1516/1516.html
总体思路
使用springMVC+spring+mybatis的方式打通表现层/业务层/持久层。从浏览器接收访问路径开始,经过数据库调取数据(只做查询),最后从浏览器显示视图的全部简易流程。
开发环境
- Eclipse oxygen
- tomcat 8.5
- Apache maven 3.5.3
- mysql
实现步骤
- 环境配置完成后,启动Maven新建webapp项目
- 在pom.xml中添加依赖(依赖来源:Maven Repository)
依赖清单:
<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>
- 创建实体类Category,定义了private的id和name,以及getter/setter方法
public class Category {
private Integer id;
private String name;
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; }
}
- 创建接口CategoryMapper,申明list方法,未来可以添加增删改查等操作
public interface CategoryMapper {
List<Category> list();
}
- 创建接口CategoryService,申明list方法
public interface CategoryService {
List<Category> list();
}
- 创建类CategoryServiceImpl实现CategoryService接口
@Service
public class CategoryServiceImpl implements CategoryService {
@Autowired
CategoryMapper categoryMapper;
@Override
public List<Category> list() { return categoryMapper.list(); }
}
@Service 表示将CategoryServiceImpl类交给spring来管理,并申明为Service类
@Autowired 表示由spring自动装配注入categoryMapper
- 创建类CategoryController,处理请求,跳转视图
@Controller
@RequestMapping("")
public class CategoryController {
@Autowired
CategoryService categoryService;
//处理admin_category_list路径的url
@RequestMapping("admin_category_list")
public String list(Model model) {
List<Category> cs=categoryService.list();
//向model传递数据
model.addAttribute("cs",cs);
//视图跳转到listCategory.jsp文件
return "admin/listCategory";
}
}
- 创建CategoryMapper.xml配置文件,实现id倒排序查询所有分类
<mapper namespace="com.ihappy.lee.mapper.CategoryMapper">
//id="list"唯一标识此sql语句,并与接口方法名保持一致
<select id="list" resultType="Category">
select * from category order by id desc
</select>
</mapper>
- 创建核心文件applicationContext.xml--对注解的识别;对jdbc.properties的引用;指定数据库连接池;配置Mybatis的SessionFactory;
<context:component-scan base-package="com.ihappy.lee.service" />
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="typeAliasesPackage" value="com.ihappy.lee.pojo" />
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
- 创建springMVC.xml
<!--springMVC的注解配置-->
<context:annotation-config/>
<!-- base-package后跟要扫描的包 expression是注解类的全名 -->
<context:component-scan base-package="com.ihappy.lee.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<mvc:annotation-driven />
<!--开通静态资源的访问-->
<mvc:default-servlet-handler />
<!-- 视图定位到/WEB-INF/jsp目录下 -->
<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>
<!-- 对上传文件的解析-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
- 配置web.xml--指定spring核心配置文件applicationContext.xml;设置中文过滤器;分发servlet,指定springMVC配置文件springMVC.xml
<!-- 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>
<!--中文过滤器-->
<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>
<!-- 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>
- 其他配置(日志文件log4j.properties;数据库配置文件jdbc.properties),略
- 使用的静态资源,略
- 创建listCategory.jsp文件
<!-- 关键代码:
遍历cs里的内容,然后挨个显示出来 -->
<c:forEach items="${cs}" var="c">
- 简易测试类
public static void main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try (Connection c = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/tmall_ssm?useUnicode=true&characterEncoding=utf8", "root", "admin");
Statement s = c.createStatement();) {
for(int i=0;i<=10;i++) {
String sqlFormat="insert into category values (null,'测试分类%d')";
String sql=String.format(sqlFormat, i);
s.execute(sql);
}
}catch(SQLException e) {
e.printStackTrace();
}
}
运行思路
- 从浏览器上访问路径/admin_category_list
- 根据web.xml中的配置(分发servlet),将拦截到的/admin_category_list,交给DispatcherServlet来处理
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
【注】<url-pattern>使用的'/'将会覆盖到容器的default servlet,凡是web.xml中找不到匹配的URL,访问请求都将交给该servlet,即DispatcherServlet来处理
- DispatcherServlet根据springMVC的配置(扫描注解),将这次请求交由CategoryController类来处理,映射到该类的list方法上(list方法带有@RequestMapping("admin_category_list")注解)
- CategoryController自动注入CategoryService,在访问了categoryService.list()方法时,再自动注入CategoryMapper
- 根据applicationContext.xml配置的会话工厂SessionFactory,使用mapperLocations属性来指定resources/mapper下的xml文件,将读取的CategoryMapper.xml与CategoryMapper关联起来
- 通过步骤4、5完成CategoryController的实例化,使用CategoryController.list()处理查询请求,id为‘list’的sql语句被执行,将查询结果封装到Category对象,并存入List<Category>类型的cs中
- 把集合cs放入model中传递给jsp,之后跳转到admin/listCategory.jsp页面,经过foreach把List项逐个显示出来