SSM初体验
这个简单的SSM项目我实在how2j网站上学习的,感兴趣可以前去学习,比较全面,最主要是有源代码提供下载,如果你照着打代码仍然编译失败,可以使用Beyond Compare来进行文件对比,我就是多次有细小的代码错误导致编译失败。
具体思路
- 首先浏览器上访问路径 /listCategory
- tomcat根据web.xml上的配置信息,拦截到了/listCategory,并将其交由DispatcherServlet处理。
- DispatcherServlet 根据springMVC的配置,将这次请求交由CategoryController类进行处理,所以需要进行这个类的实例化
- 在实例化CategoryController的时候,注入CategoryServiceImple
- 在实例化CategoryServiceImple的时候,又注入CategoryMapper
- 根据ApplicationContext.xml中的配置信息,讲CategoryMapper和Category.xml关联起来了。
- 这样拿到了实例化好了的CategoryController,并调用listCategory方法
- 在listCategory方法中,访问CategoryService,并获取数据,并把数据放在”cs”上,接着服务端跳转到listCategory.jsp去
- 最后在listCategory.jsp 中显示数据
代码演示
包结构
配置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>
配置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/>
<context:component-scan base-package="com.zy.controller">
<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>
配置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 />
<context:component-scan base-package="com.zy.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/how2java?characterEncoding=UTF-8</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>admin</value>
</property>
</bean> -->
<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/how2java?characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="admin" />
<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" />
<property name="validationQuery" value="SELECT 1" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="typeAliasesPackage" value="com.zy.pojo" />
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:com/zy/mapper/*.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.zy.mapper"/>
</bean>
</beans>
创建实体包pojo下Category类
package com.zy.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;
}
public String toString(){
return "Category [id=" + id+ ", name="+ name + "]";
}
}
mybatis框架应用创建Category.xml和对应的CategoryMapper.java接口
<?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.zy.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_
<if test="start!=null and count!=null">
limit #{start},#{count}
</if>
</select>
<select id="total" resultType="int">
select count(*) from category_
</select>
</mapper>
package com.zy.mapper;
import java.util.List;
import com.zy.pojo.Category;
import com.zy.util.Page;
public interface CategoryMapper {
public void add(Category category);
public void delete(int id);
public Category get(int id);
public void update(Category category);
public List<Category> list();
public int total();
public List<Category> list(Page page);
}
创建分页工具类
package com.zy.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 end) {
this.last = end;
}
public void caculateLast(int total){
if(total % count == 0 ){
last = total - count ;
}
else{
last = total - total%count;
}
}
}
创建service接口
package com.zy.service;
import java.util.List;
import com.zy.pojo.Category;
import com.zy.util.Page;
public interface CategoryService {
List<Category> list();
List<Category> list(Page page);
int total();
}
创建serviceimpl类继承service接口
package com.zy.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zy.mapper.CategoryMapper;
import com.zy.pojo.Category;
import com.zy.service.CategoryService;
import com.zy.util.Page;
@Service
public class CategoryServiceImpl implements CategoryService{
@Autowired
CategoryMapper categoryMapper;
public List<Category> list(){
return categoryMapper.list();
}
@Override
public List<Category> list(Page page) {
return categoryMapper.list(page);
}
@Override
public int total() {
return categoryMapper.total();
}
}
最后创建Controller类
package com.zy.controller;
import java.util.List;
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 com.zy.pojo.Category;
import com.zy.service.CategoryService;
import com.zy.util.Page;
//告诉spring MVC这是一个控制类
@Controller
@RequestMapping("")
public class CategoryController {
@Autowired
CategoryService categoryService;
@RequestMapping("listCategory")//映射网址后的地址,当mvc-dispatcher接收到这个地址后通知controller
public ModelAndView listCategory(Page page){
ModelAndView modelAndView = new ModelAndView();
List<Category> cs = categoryService.list(page);
int total = categoryService.total();
page.caculateLast(total);
//放入转发参数
modelAndView.addObject("cs", cs);
//放入jsp路径
modelAndView.setViewName("listCategory");
return modelAndView ;
}
}
创建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' bordercolor="red">
<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>
其它
- 项目的输出放在Web/WEB-INF/classes中
- 在eclipse中新建项目ssm,使用java project的方式,不要使用web dynamic project的方式。项目目录必须是e:\project\ssm,因为jar包路径的关系,使用其他项目路径会报错。
- lib中内容在此处下载:点我下载
总结
这是一个简单的小项目,初窥SSM门径,以前我都是使用的jsp/servlet的方式,现在了解了SSM的基本雏形,发觉简单了很多,而且更利于代码的修改和重构,更有利于理解设计者的思路。