栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringJDBC结合SpringMVC

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringJDBC结合SpringMVC

已知有数据库testdb中有一个表cake,包括id编号,weight重量,price价格和pic图片4个字段,要求实现cake模块的信息维护功能。
1.完成新增cake的功能,要求实现一个页面cakeForm,包含一个表单,CakeController类中1个方法add()接收请求,并完成新增的功能。
2.实现CakeController类中1个方法list(),查询所有蛋糕,并在list.jsp页面中展示。
3.在list.jsp展示页面中,每条记录后有一个“修改”的超链接,实现修改该蛋糕信息的功能。
4.在list.jsp展示页面中,每条记录后有一个“删除”的超链接,实现删除该蛋糕信息的功能。

Cake.java:

package com.lrf.cakeonline.entity;

public class Cake {

	private int id;
	private int weight;
	private double price;
	private String pic;

	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.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.lrf.cakeonline.entity.Cake;

@Repository
public class CakeDao {

	@Resource
	private JdbcTemplate jdbcTemplate;

	
	public void saveCake(Cake cake) {
		this.jdbcTemplate.update("insert into cake(weight,price,pic) values(?,?,?)", cake.getWeight(), cake.getPrice(),
				cake.getPic());
	}

	
	public List findAllCakes() {
		String sql = "select * from cake";
		List cakeList = new ArrayList();
		this.jdbcTemplate.query(sql, new RowCallbackHandler() {

			@Override
			public void processRow(ResultSet rs) throws SQLException {
				Cake cake = new Cake();
				cake.setId(rs.getInt(1));
				cake.setWeight(rs.getInt(2));
				cake.setPrice(rs.getDouble(3));
				cake.setPic(rs.getString(4));
				cakeList.add(cake);
			}
		});
		return cakeList;
	}

	
	public Cake findCakeById(int cakeId) {
		String sql = "select * from cake where id=?";
		Cake cake = (Cake) this.jdbcTemplate.queryForObject(sql, new Object[] { cakeId }, new RowMapper() {
			@Override
			public Cake mapRow(ResultSet rs, int arg1) throws SQLException {
				Cake cake = new Cake();
				cake.setId(rs.getInt(1));
				cake.setWeight(rs.getInt(2));
				cake.setPrice(rs.getDouble(3));
				cake.setPic(rs.getString(4));
				return cake;
			}
		});
		return cake;
	}

	
	public void editCake(Cake cake) {
		this.jdbcTemplate.update("update cake set weight=?, price=?, pic=? where id=?", cake.getWeight(),
				cake.getPrice(), cake.getPic(), cake.getId());
	}

	
	public void deleteCakeById(int cakeId) {
		this.jdbcTemplate.update("delete from cake where id=?", cakeId);
	}
}

CakeService.java:

package com.lrf.cakeonline.cake.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.lrf.cakeonline.cake.dao.CakeDao;
import com.lrf.cakeonline.entity.Cake;

@Service
public class CakeService {

	@Resource
	private CakeDao cakeDao;

	
	public void addCake(Cake cake) {
		this.cakeDao.saveCake(cake);
	}

	
	public List findAll() {
		return this.cakeDao.findAllCakes();
	}

	
	public Cake getCakeById(int cakeId) {
		return this.cakeDao.findCakeById(cakeId);
	}

	
	public void updateCake(Cake cake) {
		this.cakeDao.editCake(cake);
	}

	
	public void deleteCake(int cakeId) {
		this.cakeDao.deleteCakeById(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:/https://blog.csdn.net/weixin_43816281/article/details/cake/list";
		} else {
			request.setAttribute("error", "您还未选择图片!");
			request.setAttribute("action", "add");
			return "cakeForm";
		}
	}

	@RequestMapping("list")
	public String list(HttpServletRequest request) {
		List 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:/https://blog.csdn.net/weixin_43816281/article/details/cake/list";
	}

	@RequestMapping("/delete/{cakeId}")
	public String deleteCake(@PathVariable("cakeId") int cakeId) {
		this.cakeService.deleteCake(cakeId);
		System.out.println("deleteCake:" + cakeId);
		return "redirect:/https://blog.csdn.net/weixin_43816281/article/details/cake/list";
	}
}

index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


	新 增 蛋 糕

查看蛋糕列表

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"%>




Insert title here


	
		

添加蛋糕
重 量:
价 格:
图 片:

${error }

修改蛋糕
重 量:
价 格:
图 片:

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"%>





Insert title here


	
			
编 号 重 量 价 格 图 片 操 作
${cake.id } ${cake.weight } ${cake.price } 修 改

删 除

web.xml:



	Homework03

	
		index.jsp
	

	
		contextConfigLocation
		
            classpath*:/applicationContext.xml
        
	
	
	
		org.springframework.web.context.ContextLoaderListener
	
	
	
		springmvc
		org.springframework.web.servlet.DispatcherServlet
		
			contextConfigLocation
			/WEB-INF/spring-mvc.xml
		
		1
	
	
	
		springmvc
		/
	
	
	
	
		CharacterEncodingFilter
		org.springframework.web.filter.CharacterEncodingFilter
		
			encoding
			UTF-8
		
	
	
		CharacterEncodingFilter
		/*
	


applicationContext.xml:



	Spring公共配置 

	
	
	
	
	
	
	
	
        
        
            jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=utf-8
        
        
        
    

	
	
        
        
    
	
	
	
        
    
	

spring-mvc.xml:



	
	
	
	
	
	
	
	
		
	
	
	
	
		
	
	
	
	
		
		
	


经过一系列操作之后,最终数据在页面的展示:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/915419.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号