一、ssm框架整体目录架构
二、编写后端代码
1、编写实体层代码 实体层代码就是你的对象
entity
package com.cv.entity;
public class Apple {
private Integer id;
private String name;
private Integer quantity;
private Integer price;
private Integer categoryId;
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;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", quantity=" + quantity +
", price=" + price +
", categoryId=" + categoryId +
'}';
}
}
2、编写service,服务层是你的业务代码
package com.cv.service;
import com.cv.entity.Apple;
import java.util.Map;
public interface AppleService{
void insert(Apple apple);
Object[] query(Map map);
void delete(Apple apple);
void update(Apple apple);
}
3、编写业务层的实现代码
package com.cv.service;
import com.cv.dao.AppleMapper;
import com.cv.entity.Apple;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
@Service
public class AppleServiceImpl implements AppleService {
@Autowired
AppleMapper appleMapper;
@Override
@Transactional
public void insert(Apple apple) {
appleMapper.insert(apple);
}
@Override
public Object[] query(Map map) {
Integer pageNo = 1;
if(map != null) {
pageNo = (Integer) map.get("pageNo");
}
Page page = PageHelper.startPage(pageNo, 5);
PageHelper.orderBy("id asc");
List<Apple> products = appleMapper.query(map);
Object[] result = new Object[2];
result[0] = products;
result[1] = page.getPages();
return result;
}
@Override
public void delete(Apple apple) {
appleMapper.delete(apple);
}
@Override
public void update(Apple apple) {
appleMapper.update(apple);
}
}
4、dao 层 编写连写数据库层代码,对数据库进行操作
package com.cv.dao;
import com.cv.entity.Apple;
import java.util.List;
import java.util.Map;
public interface AppleMapper {
void insert (Apple apple);
void delete(Apple apple);
void update(Apple apple);
List<Apple> query(Map map);
}
5、编写数据库层配置文件AppleDao.xml,与数据库进行交互,并与dao层交互后,与实体类进行交互
<?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">
<!-- namespace:命名空间,用于隔离sql,还有一个很重要的作用,后面会讲 -->
<mapper namespace="com.cv.dao.AppleMapper">
<insert id="insert" parameterType="com.cv.entity.Apple">
insert into product(`name`,`quantity`,`price`,`categoryId`) values(#{name}, #{quantity}, #{price}, #{categoryId})
</insert>
<select id="query" parameterType="java.util.Map" resultType="com.cv.entity.Apple">
select * from product
<where>
<if test="name != null and name != ''">
name like #{name}
</if>
</where>
</select>
<delete id="delete" parameterType="com.cv.entity.Apple">
delete from product
<where>
<if test="id != null">
id = #{id}
</if>
<if test="name != null and name != ''">
and name = #{name}
</if>
</where>
</delete>
<update id="update" parameterType="com.cv.entity.Apple">
update product set name=#{name}, quantity=#{quantity}, price=#{price}, categoryId=#{categoryId} where id = #{id}
</update>
</mapper>
6、指定扫描mybatis包,以及连接数据库所使用的配置文件,并创建连接池,并指出扫描的数据库接口类
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 创建连接池 配置连接池的属性值 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 配置mybatis核心配置文件
<property name="configLocation" value="classpath:SqlMapConfig.xml" />-->
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath*:mybatis/*.xml" />
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<value>dialect=mysql</value>
</property>
</bean>
</array>
</property>
</bean>
<!-- mapper接口的扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.cv.dao"/>
</bean>
<!--事务管理器-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven />
</beans>
7、编写数据库配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/big?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
8、编写连接池配置文件
# fatal > error > warn > info > debug
log4j.rootLogger = info,console,file
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = %d %-5p [%t] %-17c - %m%n
# D://logs/debug.log
log4j.appender.file = org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern = '.'yyyy-MM-dd
log4j.appender.file.File = D://debug.log
log4j.appender.file.Encoding = UTF-8
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = %d %-5p [%t] %-17c - %m%n
log4j.logger.org.apache.ibatis=debug, console
9、配置空制器层配置文件,负责和前端交互,以及进行视图解析
<?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:p="http://www.springframework.org/schema/p"
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-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!--springmvc注解驱动-->
<mvc:annotation-driven />
<context:component-scan base-package="com.cv.comtroller" />
<!--定义视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 多部分文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
<mvc:default-servlet-handler/>
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/image/" mapping="/image/**" />
<mvc:resources location="/plugins/" mapping="/plugins/**" />
</beans>
10、编写控制器层代码,负责和前后端交互
package com.cv.comtroller;
import com.cv.entity.Apple;
import com.cv.service.AppleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/product")
public class AppleController {
@Autowired
AppleService appleService;
@RequestMapping("/insert")
@ResponseBody
public void insert(Apple apple) {
appleService.insert(apple);
}
@RequestMapping("/query")
@ResponseBody
public Object[] query(String keywords, Integer pageNo) {
Map map = new HashMap();
if(keywords != null) {
map.put("name", "%" + keywords +"%");
}
if(pageNo != null) {
map.put("pageNo", pageNo);
} else {
map.put("pageNo", 1);
}
return appleService.query(map);
}
@RequestMapping("/delete")
@ResponseBody
public void delete(Apple apple) {
appleService.delete(apple);
}
@RequestMapping("/update")
@ResponseBody
public void update(Apple apple) {
appleService.update(apple);
}
}
三、编写前端代码,负责和后端交互
1、使用ajax去调用后端代码,并指定所使用的css代码,并用html编写相应web界面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018/8/17
Time: 13:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>商品列表</title>
<link rel="stylesheet" type="text/css" href="${request.contextPath}/css/bootstrap.css">
<script type="text/javascript" src="${request.contextPath}/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="${request.contextPath}/js/bootstrap.js"></script>
<script type="text/javascript" src="${request.contextPath}/js/jquery.validate.js"></script>
<script type="text/javascript" src="${request.contextPath}/js/messages_zh.js"></script>
<script>
$(document).ready(function() {
var pageNo = 1; // 全局变量,当前页码
var pageCount = 0; // 总页数
function query(keywords) {
$("#products").empty();
$.ajax({
url: "${request.contextPath}/product/query.action",
type: "get",
data: {"pageNo":pageNo,"keywords":keywords},
success: function(result) {
var products = result[0];
pageCount = result[1];
refreshPage(); // 更新分页链接状态
for(var index=0;index<products.length;index++) {
var product = products[index];
$("#products").append("<tr>"+
"<td><input type='checkbox' name='check' value='" + product.id + "'></td>"+
"<td>" + product.id + "</td>" +
"<td><span id='label_name_" + product.id + "'>" + product.name +"</span>" + "<input type='text' style='display:none' id='name_" + product.id +"' value='" + product.name + "'></td>" +
"<td><span id='label_quantity_" + product.id + "'>" + product.quantity + "</span>" + "<input type='text' style='display:none' id='quantity_" + product.id +"' value='" + product.quantity + "'></td>"+
"<td><span id='label_price_" + product.id + "'>" + product.price + "</span>" + "<input type='text' style='display:none' id='price_" + product.id +"' value='" + product.price + "'></td>"+
"<td><span id='label_categoryId_" + product.id + "'>" + product.categoryId + "</span>" + "<input type='text' style='display:none' id='categoryId_" + product.id +"' value='" + product.categoryId + "'></td>"+
"<td>"+
"<button id='delete_" + product.id + "'><span class='text-danger glyphicon glyphicon-minus'></span></button>"+
"<button id='edit_" + product.id + "'><span class='text-warning glyphicon glyphicon-pencil'></span></button>"+
"<button style='display:none' id='save_" + product.id + "'><span class='text-info glyphicon glyphicon-floppy-disk'></span></button>"+
"</td></tr>");
$("#delete_" + product.id).click(function() {
if(confirm("确定删除吗?")) {
var id = $(this).attr("id");
remove(id.substr(id.indexOf("_")+1));
}
});
$("#edit_" + product.id).click(function() {
var id = $(this).attr("id");
$("#label_name_" + id.substr(id.indexOf("_")+1)).hide();
$("#label_quantity_" + id.substr(id.indexOf("_")+1)).hide();
$("#label_price_" + id.substr(id.indexOf("_")+1)).hide();
$("#label_categoryId_" + id.substr(id.indexOf("_")+1)).hide();
$("#name_" + id.substr(id.indexOf("_")+1)).show();
$("#quantity_" + id.substr(id.indexOf("_")+1)).show();
$("#price_" + id.substr(id.indexOf("_")+1)).show();
$("#categoryId_" + id.substr(id.indexOf("_")+1)).show();
$(this).hide();
$("#save_" + id.substr(id.indexOf("_")+1)).show();
});
$("#save_" + product.id).click(function() {
var id = $(this).attr("id");
update(id.substr(id.indexOf("_")+1)); // 从按钮的ID值截取商品id
$("#label_name_" + id.substr(id.indexOf("_")+1)).show();
$("#label_quantity_" + id.substr(id.indexOf("_")+1)).show();
$("#label_price_" + id.substr(id.indexOf("_")+1)).show();
$("#label_categoryId_" + id.substr(id.indexOf("_")+1)).show();
$("#name_" + id.substr(id.indexOf("_")+1)).hide();
$("#quantity_" + id.substr(id.indexOf("_")+1)).hide();
$("#price_" + id.substr(id.indexOf("_")+1)).hide();
$("#categoryId_" + id.substr(id.indexOf("_")+1)).hide();
$(this).hide();
$("#edit_" + id.substr(id.indexOf("_")+1)).show();
});
}
}
});
}
function update(id) {
$.ajax({
url: "${request.contextPath}/product/update.action",
type: "get",
data: {"id":id, "name": $("#name_" + id).val(),
"quantity": $("#quantity_" +id).val(), "price": $("#price_" + id).val(),
"categoryId": $("#categoryId_" + id).val()},
success: function(result) {
alert("更新成功!");
query();
}
});
}
function insert() {
$.ajax({
url: "${request.contextPath}/product/insert.action",
type: "get",
data: {"name": $("#name").val(),
"quantity": $("#quantity").val(), "price": $("#price").val(),
"categoryId": $("#categoryId").val()},
success: function(result) {
alert("增加成功!");
query();
}
});
}
function remove(id){
$.ajax({
url: "${request.contextPath}/product/delete.action",
type: "get",
data: {"id":id},
success: function(result) {
query();
}
});
}
/**
* pageNo发生变化时需要更新分页链接状态
*/
function refreshPage() {
if(pageNo == 1) {
$("#first").addClass("disabled");
$("#pre").addClass("disabled");
} else {
$("#first").removeClass("disabled");
$("#pre").removeClass("disabled");
}
if(pageNo == pageCount) {
$("#last").addClass("disabled");
$("#next").addClass("disabled");
} else {
$("#last").removeClass("disabled");
$("#next").removeClass("disabled");
}
}
query(); // 初始化时查询第一页数据
$("#first").click(function() {
if(pageNo > 1) {
pageNo = 1;
query();
}
});
$("#pre").click(function() {
if(pageNo > 1) {
pageNo = pageNo - 1;
query();
}
});
$("#next").click(function() {
if(pageNo < pageCount) {
pageNo = pageNo + 1;
query();
}
});
$("#last").click(function() {
if(pageNo < pageCount) {
pageNo = pageCount;
query();
}
});
$("#add").click(function() {
$("#products").append("<tr><td> </td><td>#</td>" +
"<td><input type='text' id='name'></td>" +
"<td><input type='text' id='quantity'></td>"+
"<td><input type='text' id='price'></td>"+
"<td><input type='text' id='categoryId'></td>"+
"<td> </td></tr>");
$(this).hide();
$("#save").show();
});
$("#save").click(function() {
insert();
$(this).hide();
$("#add").show();
});
$("#search").click(function() {
pageNo = 1;// 搜索后显示第一页数据
query($("#keywords").val())
});
$("#delete").click(function(){
var checks = $("[name='check']:checked");
for(var index=0;index<checks.length;index++) {
var productId = $(checks[index]).val();
remove(productId);
}
});
})
</script>
</head>
<body>
<div class="container">
<div class="row">
<ul class="pagination">
<li id="first"><a href="javascript:void(0)">第一页</a></li>
<li id="pre"><a href="javascript:void(0)">上一页</a></li>
<li id="next"><a href="javascript:void(0)">下一页</a></li>
<li id="last"><a href="javascript:void(0)">最后页</a></li>
</ul>
<table class="table table-bordered table-striped table-hover">
<caption>商品列表
<div class="input-group col-md-4">
<input id="keywords" type="text" class="form-control">
<span id="search" class="input-group-addon"><span class="glyphicon glyphicon-search"></span></span>
</div><!-- /input-group --></caption>
<thead>
<th><input type="checkbox" id="all" >全选</th>
<th>ID</th>
<th>名称</th>
<th>数量</th>
<th>价格</th>
<th>类别</th>
<th>操作<button id='add'><span class='text-info glyphicon glyphicon-plus'></span></button>
<button id='save' style="display:none"><span class='text-info glyphicon glyphicon-floppy-disk'></span></button>
<button id='delete'><span class='text-info glyphicon glyphicon-minus'></span></button>
</th>
</thead>
<tbody id="products">
</tbody>
</table>
<ul class="pagination">
<li id="first2"><a href="javascript:void(0)">第一页</a></li>
<li id="pre2"><a href="javascript:void(0)">上一页</a></li>
<li id="next2"><a href="javascript:void(0)">下一页</a></li>
<li id="last2"><a href="javascript:void(0)">最后页</a></li>
</ul>
</div>
</div>
</body>
</html>
2、编写前端解析器配置文案间web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
metadata-complete="true">
<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>
<!-- 前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
四、至此ssm框架的web界面配置完成,web界面如图所示