整合SpringMVC、Hibernate框架,以注解的方式实现作业三的各个功能。提示:应包含1个Cake实体类,1个CakeController控制器类,1个CakeService类,1个CakeDao类cakeForm.jsp、list.jsp2个页面,注意配置事务。
Cake.java:
package com.lrf.cakeonline.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="cake")
public class Cake {
private int id;
private int weight;
private double price;
private String pic;
@Id
@GeneratedValue(generator="my_inc")
@GenericGenerator(name="my_inc",strategy="native")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public Cake() {
super();
}
public Cake(int id, int weight, double price, String pic) {
super();
this.id = id;
this.weight = weight;
this.price = price;
this.pic = pic;
}
@Override
public String toString() {
return "Cake [id=" + id + ", weight=" + weight + ", price=" + price + ", pic=" + pic + "]";
}
}
CakeDao.java:
package com.lrf.cakeonline.cake.dao;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;
import com.lrf.cakeonline.entity.Cake;
@Repository
public class CakeDao {
@Resource
private SessionFactory sessionFactory;
public void saveCake(Cake cake) {
Session session = this.sessionFactory.getCurrentSession();
Transaction transaction = session.beginTransaction();
session.save(cake);
transaction.commit();
}
public List<Cake> findAllCakes() {
Query query = this.sessionFactory.getCurrentSession().createQuery("from Cake");
List<Cake> cakes = query.list();
return cakes;
}
public Cake findCakeById(int cakeId) {
Cake cake = (Cake) this.sessionFactory.getCurrentSession().get(Cake.class, cakeId);
return cake;
}
public void editCake(Cake cake) {
Session session = this.sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.update(cake);
transaction.commit();
}
public void deleteCakeById(int cakeId) {
Session session = this.sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Cake cake = session.get(Cake.class, cakeId);
session.delete(cake);
transaction.commit();
}
}
CakeService.java:
package com.lrf.cakeonline.cake.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lrf.cakeonline.cake.dao.CakeDao;
import com.lrf.cakeonline.entity.Cake;
@Service
@Transactional(readOnly = false)
public class CakeService {
@Resource
private CakeDao cakeDao;
public void addCake(Cake cake) {
this.cakeDao.saveCake(cake);
}
public void updateCake(Cake cake) {
this.cakeDao.editCake(cake);
}
public void deleteCake(int cakeId) {
this.cakeDao.deleteCakeById(cakeId);
}
@Transactional(readOnly = true)
public List<Cake> findAll() {
return this.cakeDao.findAllCakes();
}
@Transactional(readOnly = true)
public Cake getCakeById(int cakeId) {
return this.cakeDao.findCakeById(cakeId);
}
}
CakeController.java:
package com.lrf.cakeonline.cake.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.lrf.cakeonline.cake.service.CakeService;
import com.lrf.cakeonline.entity.Cake;
@Controller
@RequestMapping("/cake")
public class CakeController {
@Resource
private CakeService cakeService;
@RequestMapping(value = "add", method = RequestMethod.GET)
public String toAdd(HttpServletRequest request) {
request.setAttribute("action", "add");
return "cakeForm";
}
@RequestMapping(value = "add", method = RequestMethod.POST)
public String add(@RequestParam("upFile") MultipartFile file, Cake cake, HttpServletRequest request) {
if (!file.getOriginalFilename().isEmpty()) {
// 保存图片
String path = request.getServletContext().getRealPath("/");
try {
FileCopyUtils.copy(file.getBytes(), new File(path + "/upload", file.getOriginalFilename()));
cake.setPic(file.getOriginalFilename());
} catch (IOException e) {
e.printStackTrace();
}
// 保存蛋糕信息
this.cakeService.addCake(cake);
System.out.println("add:" + cake);
return "redirect:/cake/list";
} else {
request.setAttribute("error", "您还未选择图片!");
request.setAttribute("action", "add");
return "cakeForm";
}
}
@RequestMapping("list")
public String list(HttpServletRequest request) {
List<Cake> cakeList = this.cakeService.findAll();
request.setAttribute("cakes", cakeList);
System.out.println("cakeList:" + cakeList);
return "list";
}
@RequestMapping(value = "edit/{cakeId}", method = RequestMethod.GET)
public String toEdit(@PathVariable("cakeId") int cakeId, HttpServletRequest request) {
Cake cake = this.cakeService.getCakeById(cakeId);
System.out.println("toEdit:" + cake);
request.setAttribute("cake", cake);
request.setAttribute("action", "edit");
return "cakeForm";
}
@RequestMapping(value = "edit", method = RequestMethod.POST)
public String editCake(@RequestParam("upFile") MultipartFile file, Cake cake, HttpServletRequest request) {
System.out.println("editCake_before:" + cake);
// 修改图片
String path = request.getServletContext().getRealPath("/");
try {
if (!file.getOriginalFilename().isEmpty()) {
FileCopyUtils.copy(file.getBytes(), new File(path + "/upload", file.getOriginalFilename()));
cake.setPic(file.getOriginalFilename());
} else {
Cake oldCake = this.cakeService.getCakeById(cake.getId());
cake.setPic(oldCake.getPic());
}
} catch (IOException e) {
e.printStackTrace();
}
// 修改蛋糕信息
this.cakeService.updateCake(cake);
System.out.println("editCake_after:" + cake);
return "redirect:/cake/list";
}
@RequestMapping("/delete/{cakeId}")
public String deleteCake(@PathVariable("cakeId") int cakeId) {
this.cakeService.deleteCake(cakeId);
System.out.println("deleteCake:" + cakeId);
return "redirect:/cake/list";
}
}
index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:forward page="cake/list"></jsp:forward>
</body>
</html>
list.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="ctx" value="${pageContext.request.contextPath }" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="/Homework04/cake/add">新 增 蛋 糕</a><br><br>
<table border="1">
<tr>
<th width="80px" style="text-align: center;">编 号</th>
<th width="80px" style="text-align: center;">重 量</th>
<th width="120px" style="text-align: center;">价 格</th>
<th width="120px" style="text-align: center;">图 片</th>
<th width="120px" style="text-align: center;">操 作</th>
</tr>
<c:forEach items="${cakes }" var="cake">
<tr>
<td style="text-align: center;">${cake.id }</td>
<td style="text-align: center;">${cake.weight }</td>
<td style="text-align: center;">${cake.price }</td>
<td style="text-align: center;"><img alt="" src="${ctx }/upload/${cake.pic }" style="width:100px;height:100px;"></td>
<td style="text-align: center;">
<a href="/Homework04/cake/edit/${cake.id }">修 改</a><br/><br/>
<a href="/Homework04/cake/delete/${cake.id }">删 除</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
cakeForm.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>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:if test="${action == 'add' }">
<h2>添加蛋糕</h2>
<form action="/Homework04/cake/add" method="post" enctype="multipart/form-data">
重 量:<input type="text" name="weight" value="${cake.weight }"/><br/>
价 格:<input type="text" name="price" value="${cake.price }"/><br/>
图 片:<input type="file" name="upFile" value="${cake.pic }"/><br/>
<input type="submit" value="save"/><br/>
<p style="color:red;">${error }</p>
</form>
</c:if>
<c:if test="${action == 'edit' }">
<h2>修改蛋糕</h2>
<form action="/Homework04/cake/edit" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="${cake.id }"/>
重 量:<input type="text" name="weight" value="${cake.weight }"/><br/>
价 格:<input type="text" name="price" value="${cake.price }"/><br/>
图 片:<input type="file" name="upFile" value="${cake.pic }"/><br/>
<input type="submit" value="save"/>
</form>
</c:if>
</body>
</html>
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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Homework4</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
spring-mvc.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<mvc:annotation-driven />
<!-- 处理静态资源 -->
<mvc:default-servlet-handler/>
<!-- 自动扫描且只扫描@Controller -->
<context:component-scan base-package="com.lrf.cakeonline">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 配置文件上传解析器(基于Commons FileUpload的文件上传) -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property><!-- 配置默认的字符集编码 -->
</bean>
<!-- 定义JSP文件的位置 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">
<description>Spring公共配置 </description>
<!-- 配置Spring上下文的注解 -->
<context:annotation-config />
<!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
<context:component-scan base-package="com.lrf.cakeonline">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 属性文件位置 -->
<context:property-placeholder location="classpath:*.properties" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 要扫描的实体类所在的包 -->
<property name="packagesToScan" value="com.lrf.cakeonline.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.useUnicode">${hibernate.useUnicode}</prop>
<prop key="hibernate.characterEncoding">${hibernate.characterEncoding}</prop>
<prop key="current_session_context_class">thread</prop>
</props>
</property>
</bean>
<!-- 使用annotation定义事务,事务管理器配置, Hibernate单数据源事务 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
</beans>
dbinfo.properties:
#mysql
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=
#hibernate
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.format_sql=false
hibernate.useUnicode=true
hibernate.characterEncoding=utf-8