花了一周时间重新熟悉了一下SSM三大框架,也经历了一次由复杂及简单的过程,从刚开始的使用Mybatis操作数据就可以比较其和JDBC的不同,相应的java代码减少了,但是相对的配置文件的内容越来越多,代码以后的维护性也得到了越来越高的提升。后面使用SpringMVC后,抛弃了之前论坛项目使用的servlet,代码量是更加的大大减少了,而且原本需要一个一个request.getParament()来的,使用SpringMVC可以直接映射到我们的参数列表。但是,大量的代码优化,如果一个程序员只是单纯的学会了简单使用,这种优化是好还是坏呢?
言归正传,SpringMVC其实也是Spring的一个模块,只是有时候单独使用它的机会很多,所以习惯性的将它独立出来了,Spring本身是有很多模块的,当我从其官网看它的各个模块的时候就感受它的强大了。使用spring以后,我们可以将NEW这个功能放开交给Spring来处理,那么我们只需要使用注解就可以获得到原本需要NEW的对象。
我用了一个简单商品的增删改查来理解一下Spring
首先先确定web项目的五层结构视图层,控制层,业务层,DAO层还有POJO层
视图层代码很简单,就是显示后台传输的数据以及向后台传输数据
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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SSM</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<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:beans.xml</param-value>
</init-param>
<load-on-startup>1 </load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
productlist.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>商品列表页面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/product/deletelist.do"
method="post">
<table border=1px>
<tr>
<th><input type="checkbox"></th>
<th>商品编号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>商品描述</th>
<th>操作</th>
</tr>
<c:forEach items="${plist}" var="p">
<tr>
<td><input type="checkbox" name="ids" value="${p.id}"></td>
<td>${p.id}</td>
<td>${p.name}</td>
<td>${p.price}</td>
<td>${p.description}</td>
<td><a
href="${pageContext.request.contextPath}/product/toupdate.do?id=${p.id}">修改</a>
<a
href="${pageContext.request.contextPath}/product/delete.do?id=${p.id}">删除</a>
</td>
</tr>
</c:forEach>
</table>
<input type="submit" value="批量删除">
</form>
</body>
</html>
toadd.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>商品添加页面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/product/add.do" method="post">
商品名称:<input type="text" id="name" name="name"><br>
商品价格:<input type="text" id="price" name="price"><br>
商品描述:<textarea rows="4" id="description" name="description"></textarea>
<input type="submit" value="提交">
</form>
</body>
</html>
productupdate.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>商品修改页面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/product/update.do" method="post">
<input type="hidden" id="id" name="id" value="${product.id}">
商品名称:<input type="text" id="name" name="name" value="${product.name}"><br>
商品价格:<input type="text" id="price" name="price" value="${product.price}"><br>
商品描述:<textarea rows="4" id="description" name="description">${product.description}</textarea>
<input type="submit" value="提交">
</form>
</body>
</html>
productall.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>商品列表页面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/product/updatelist.do"
method="post">
<table border=1px>
<tr>
<th>商品编号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>商品描述</th>
</tr>
<c:forEach items="${plist}" var="p" varStatus="stat">
<input type="hidden" name="list[${stat.index}].id"
value="${p.id}" />
<tr>
<td>${p.id}</td>
<td><input type="text" name="list[${stat.index}].name"
value="${p.name}" /></td>
<td><input type="text" name="list[${stat.index}].price"
value="${p.price}" /></td>
<td><input type="text" name="list[${stat.index}].description"
value="${p.description}" /></td>
</tr>
</c:forEach>
</table>
<input type="submit" value="批量更新">
</form>
</body>
</html>
控制层实现的就是处理视图层提交过来的请求将其分给相应的业务逻辑进行处理,并且将业务层处理返回的数据相应给视图层。
package cn.edu360.controller;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.edu360.pojo.Product;
import cn.edu360.pojo.ProductClass;
import cn.edu360.pojo.ProductSubClass;
import cn.edu360.pojo.ProductVO;
import cn.edu360.service.ProductService;
@Controller
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductService productService;
@RequestMapping("/findall")
public String findall(Model model) {
List<Product> list = productService.findAll();
model.addAttribute("plist", list);
return "product/product-list";
}
@RequestMapping("/findbyscid")
public String findbyscid(Long scid,Model model){
List<Product> list = productService.findByScid(scid);
ProductSubClass subClassByScid = productService.getSubClassByScid(scid);
model.addAttribute("subClassByScid", subClassByScid);
model.addAttribute("plist", list);
return "product/product-sublist";
}
@RequestMapping("/toedit")
public String toadd(Model model,Long id) {
Product product = productService.getById(id);
List<ProductSubClass> productSubClass = productService.getSubClassById(product.getClass_id());
List<ProductClass> list = productService.getAllClass();
model.addAttribute("productSubClass", productSubClass);
model.addAttribute("jspclass", list);
model.addAttribute("product", product);
return "product/product-edit";
}
@RequestMapping("/edit")
public String edit(Product product) {
productService.update(product);
return "redirect:/product/findall.do";
}
@RequestMapping("/toadd")
public String toadd(Model model){
List<ProductClass> list = productService.getAllClass();
model.addAttribute("jspclass", list);
return "product/product-add";
}
@RequestMapping("/add")
@ResponseBody
public String add(Product product) {
productService.addProduct(product);
return "success";
}
@RequestMapping("/delete")
@ResponseBody
public String delete(Long id) {
productService.deleteById(id);
return "success";
}
@RequestMapping("/findsubclass")
@ResponseBody
public List<ProductSubClass> findsubclass(Long cid,HttpServletResponse response){
List<ProductSubClass> list = productService.getSubClassById(cid);
ObjectMapper objectMapper = new ObjectMapper();
String jsonfromList = null ;
PrintWriter printWriter = null ;
try {
jsonfromList = objectMapper.writeValueAsString(list);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/UTF-8");
//System.out.println(jsonfromList);
printWriter = response.getWriter();
printWriter.println(jsonfromList);
// printWriter.write(jsonfromList);
// printWriter.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
printWriter.close();
response.reset();
}
return list;
}
@RequestMapping("/deleteByIds")
@ResponseBody
public String deleteByIds(Long[] ids) {
productService.deleteList(ids);
return "success";
}
@RequestMapping("/toupdatelist")
public String toupdatelist(Model model) {
List<Product> list = productService.findAll();
model.addAttribute("plist", list);
return "productall.jsp";
}
@RequestMapping("/updatelist")
public String updatelist(ProductVO pvo) {
List<Product> list = pvo.getList();
productService.updatelist(list);
return "redirect:/product/findall.do";
}
}
上面代码不同一个项目,只是单纯的针对每一个模块的处理方法。
POJO商品实体层
package cn.edu360.pojo;
/**
* 商品类
*
* @author Administrator
*
*/
public class Product {
private Long id;
private String name;
private Double price;
private String description;
private Long inventory;
private Long class_id;
private Long subclass_id;
public Long getInventory() {
return inventory;
}
public void setInventory(Long inventory) {
this.inventory = inventory;
}
public Long getClass_id() {
return class_id;
}
public void setClass_id(Long class_id) {
this.class_id = class_id;
}
public Long getSubclass_id() {
return subclass_id;
}
public void setSubclass_id(Long subclass_id) {
this.subclass_id = subclass_id;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the price
*/
public Double getPrice() {
return price;
}
/**
* @param price
* the price to set
*/
public void setPrice(Double price) {
this.price = price;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description
* the description to set
*/
public void setDescription(String description) {
this.description = description;
}
}
以及批量修改所用的实体ProductVO层
package cn.edu360.pojo;
import java.util.List;
public class ProductVO {
private List<Product> list;
/**
* @return the list
*/
public List<Product> getList() {
return list;
}
/**
* @param list the list to set
*/
public void setList(List<Product> list) {
this.list = list;
}
}
业务层,处理各种控制端提交的请求,并将调用相应的dao层方法来处理它。
接口
package cn.edu360.service;
import java.util.List;
import cn.edu360.pojo.Product;
import cn.edu360.pojo.ProductClass;
import cn.edu360.pojo.ProductSubClass;
public interface ProductService {
public List<Product> findAll();
public void addProduct(Product product);
public void deleteById(Long id);
public Product toUpdate(Long id);
public void update(Product product);
public void deleteList(Long[] ids);
public void updatelist(List<Product> list);
public List<Product> findByScid(Long scid);
public Product getById(Long id);
public List<ProductClass> getAllClass();
public List<ProductSubClass> getSubClassById(Long cid);
public ProductSubClass getSubClassByScid(Long subclass_id);
}
接口实现方法:
package cn.edu360.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.edu360.mapper.ProductClassMapper;
import cn.edu360.mapper.ProductMapper;
import cn.edu360.mapper.ProductSubClassMapper;
import cn.edu360.pojo.Product;
import cn.edu360.pojo.ProductClass;
import cn.edu360.pojo.ProductSubClass;
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductMapper productMapper;
@Autowired
private ProductClassMapper productClassMapper;
@Autowired
private ProductSubClassMapper productSubClassMapper;
@Override
public List<Product> findAll() {
List<Product> list = productMapper.findAll();
return list;
}
@Override
public void addProduct(Product product) {
productMapper.save(product);
}
@Override
public void deleteById(Long id) {
productMapper.deleteById(id);
}
@Override
public Product toUpdate(Long id) {
Product product = productMapper.getById(id);
return product;
}
@Override
public void update(Product product) {
productMapper.update(product);
}
@Override
public void deleteList(Long[] ids) {
productMapper.deleteByIds(ids);
}
@Override
public void updatelist(List<Product> list) {
for (Product product : list) {
productMapper.update(product);
}
}
@Override
public List<Product> findByScid(Long scid) {
List<Product> list = productMapper.findByScid(scid);
return list;
}
@Override
public Product getById(Long id) {
Product product = productMapper.getById(id);
return product;
}
@Override
public List<ProductClass> getAllClass() {
List<ProductClass> list = productClassMapper.getAllClass();
return list;
}
@Override
public List<ProductSubClass> getSubClassById(Long cid) {
List<ProductSubClass> list = productSubClassMapper.getSubClassById(cid);
return list;
}
@Override
public ProductSubClass getSubClassByScid(Long subclass_id) {
ProductSubClass productSubClass = productSubClassMapper.getSubClassByScid(subclass_id);
return productSubClass;
}
}
最后就是对数据库的操作以及相应的配置文件
package cn.edu360.mapper;
import java.util.List;
import cn.edu360.pojo.Product;
public interface ProductMapper {
public List<Product> findAll();
public Product getById(Long id);
public void save(Product product);
public void deleteById(Long id);
public void update(Product product);
public void deleteByIds(Long[] ids);
public List<Product> findByScid(Long scid);
}
mapper层的接口实现,使用mybatis的配置文件来实现。
<?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="cn.edu360.mapper.ProductMapper">
<resultMap type="Product" id="productResultMap">
<id property="id" column="pid" />
<result property="name" column="pname" />
<result property="price" column="price" />
<result property="description" column="description" />
<result property="inventory" column="inventory" />
<result property="class_id" column="class_id" />
<result property="subclass_id" column="subclass_id" />
</resultMap>
<select id="findAll" resultMap="productResultMap">
select
pid,pname,price,description,inventory,class_id,subclass_id from t_product
</select>
<select id="findByScid" parameterType="long" resultMap="productResultMap">
select
pid,pname,price,description,inventory,class_id,subclass_id from t_product where subclass_id = #{scid}
</select>
<insert id="save" parameterType="Product">
insert into t_product
(pname,price,description,inventory,class_id,subclass_id) values (#{name},#{price},#{description},#{inventory},#{class_id},#{subclass_id})
</insert>
<delete id="deleteById" parameterType="long">
delete from t_product
where pid = #{id}
</delete>
<update id="update" parameterType="Product">
update t_product set
pname=#{name},price=#{price},description=#{description},inventory=#{inventory},class_id=#{class_id},subclass_id=#{subclass_id} where pid =
#{id}
</update>
<select id="getById" parameterType="long" resultMap="productResultMap">
select
pid,pname,price,description,inventory,class_id,subclass_id from t_product where pid = #{id}
</select>
<delete id="deleteByIds" parameterType="list">
delete from t_product where pid in
<foreach collection="array" item="i" open="(" separator=","
close=")">
#{i}
</foreach>
</delete>
</mapper>
最后是SpringMVC的配置文件
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<context:component-scan base-package="cn.edu360"/>
<!-- 配置一个连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/storemybatis?characterEncoding=UTF-8" />
<property name="user" value="root" />
<property name="password" value="12580" />
</bean>
<!-- sqlSessonFactory的配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:SqlMapConfig.xml" />
</bean>
<!-- Mybatis包扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.edu360.mapper" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 事务管理器,事务管理器要关联数据源(连接池) -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<aop:config>
<!-- execution表达式 -->
<!-- * 是否有返回值 -->
<!-- cn.edu360.service..*Impl cn.edu360.service这个包及其子包下的以Impl结尾的类 -->
<!-- *(..))类下的任务方法 ,是否有参数 -->
<aop:pointcut id="transactionPointcut"
expression="execution(* cn.edu360.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut"
advice-ref="transactionAdvice" />
</aop:config>
</beans>
在这里定义的是数据库的各项参数,和视图返回的格式,以及对包下面的程序的注解扫描,当使用@Autowired注解时,spring会将我们已经写好的实体类new到我们这个注解下面所需要的实体上面,那么new的功能就是spring直接帮我们实现了。