基于javaweb+mysql的ssm+maven网上电子书城项目(java+ssm+jsp+maven+mysql)
运行环境
Java≥8、MySQL≥5.7、Tomcat≥8
开发工具
eclipse/idea/myeclipse/sts等均可配置运行
适用
课程设计,大作业,毕业设计,项目练习,学习演示等
功能说明
基于javaweb+mysql的SSM+Maven网上电子书城项目(java+ssm+jsp+maven+mysql)
项目描述:
spring mvc +jsp实现的简单书城项目,可以在支付宝沙箱内实现支付
运行环境:
jdk8+tomcat9+mysql+IntelliJ IDEA
项目技术:
spring+spring mvc+mybatis+jsp+maven
/**
* company: www.abc.com
* Author: Administrator
*/
@Controller
@RequestMapping("/admin/order")
public class OrderManageHandler {
@Autowired
private IOrderManageService orderManageService;
@RequestMapping("/findOrder.do")
private String findOrder(@RequestParam(defaultValue = "1") int pageIndex, String id, String receiverName, Model model){
PageModel pageModel=new PageModel();
pageModel.setPageIndex(pageIndex);
int count=orderManageService.findOrderCount(id,receiverName);
pageModel.setRecordCount(count);
List<Order> orders=orderManageService.findOrder(id,receiverName,pageModel);
model.addAttribute("orders",orders);
model.addAttribute("pageModel",pageModel);
model.addAttribute("id",id);
model.addAttribute("receiverName",receiverName);
return "/admin/orders/list.jsp";
}
@RequestMapping("/findOrderById.do")
private String findOrderById(String id,Model model){
List<Orderitem> orderitems=orderManageService.findOrderitemById(id);
model.addAttribute("orderitems",orderitems);
return "/admin/orders/view.jsp";
}
@RequestMapping("/removeOrder.do")
private String removeOrder(String id){
orderManageService.removeOrderById(id);
return "redirect:/admin/order/findOrder.do";
}
}
@Controller
@RequestMapping("/client/product")
public class ProductHandler {
@Autowired
private IProductService productService;
@RequestMapping("/findBookByCategory.do")
public String findBookByCategory(@RequestParam(defaultValue = "1") int pageIndex, String category, Model model){
if(category!=null && category!=""){
PageModel pageModel = new PageModel();
pageModel.setPageIndex(pageIndex);
int count = productService.findBookCount(category);
pageModel.setRecordCount(count);
List<Product> products = productService.findBookByCategory(pageModel, category);
model.addAttribute("count", count);
model.addAttribute("products", products);
model.addAttribute("category", category);
model.addAttribute("pageModel", pageModel);
return "/client/product_list.jsp";
}else {
return "/index.jsp";
}
}
@RequestMapping("/findProductById.do")
public String findProductById(String id,Model model){
Product product=productService.findProductById(id);
model.addAttribute("p",product);
return "/client/info.jsp";
}
}
@RequestMapping("/modifyNotice.do")
public String modifyNotice(Notice notice,String flag,Model model){
if(flag != null){
notice=noticeService.findNoticeById(notice.getN_id());
model.addAttribute("n",notice);
return "/admin/notices/edit.jsp";
}else {
int rows=noticeService.modifyNotice(notice);
if(rows>0){
return "redirect:/admin/notice/findNotice.do";
}else {
model.addAttribute("message","修改公告失败!");
return "/admin/notices/error.jsp";
}
}
}
@RequestMapping("/addNotice.do")
public String addNotice(Notice notice,Model model){
int rows=noticeService.addNotice(notice);
if(rows>0){
return "redirect:/admin/notice/findNotice.do";
}else {
model.addAttribute("message","添加公告失败!");
return "/admin/notices/error.jsp";
}
}
@RequestMapping("/removeNotice.do")
public String removeNotice(Integer id,Model model){
int rows=noticeService.removeNotice(id);
if(rows>0){
return "redirect:/admin/notice/findNotice.do";
}else{
/**
* company: www.abc.com
* Author: Administrator
*/
@Controller
@RequestMapping("/admin/notice")
public class NoticeHandler {
@Autowired
private INoticeService noticeService;
@RequestMapping("/findNotice.do")
public String findNotice(@RequestParam(defaultValue = "1") int pageIndex, Model model){
PageModel pageModel=new PageModel();
pageModel.setPageIndex(pageIndex);
int count=noticeService.findNoticeCount();
pageModel.setRecordCount(count);
List<Notice> notices=noticeService.findNotice(pageModel);
model.addAttribute("notices",notices);
model.addAttribute("pageModel",pageModel);
return "/admin/notices/list.jsp";
}
@RequestMapping("/modifyNotice.do")
public String modifyNotice(Notice notice,String flag,Model model){
if(flag != null){
notice=noticeService.findNoticeById(notice.getN_id());
model.addAttribute("n",notice);
return "/admin/notices/edit.jsp";
}else {
int rows=noticeService.modifyNotice(notice);
product.setImgurl("/productImg/"+filename);
}else {
model.addAttribute("message","上传附件失败!");
return "/admin/products/error.jsp";
}
}
bookService.modifyProduct(product);
return "redirect:/admin/product/findProduct.do";
}
}
@RequestMapping("/addProduct.do")
public String addProduct(Product product, Model model, HttpSession session,HttpServletRequest request) throws IOException {
String path =IdUtils.rootDir + "/src/main/webapp/productImg";
//上传到服务器
/* String path=session.getServletContext().getRealPath("/productImg");*/
File upload = new File(path);
if (!upload.exists()) {
upload.mkdirs();
}
String filename = IdUtils.getUUID() + "-" + product.getFile().getOriginalFilename();
if(filename.endsWith(".jpg")||filename.endsWith(".png")){
product.getFile().transferTo(new File(path+File.separator+filename));
product.setId(IdUtils.getUUID());
product.setImgurl("/productImg/"+filename);
bookService.addProduct(product);
return "redirect:/admin/product/findProduct.do";
}else {
model.addAttribute("message","上传附件失败!");
return "/admin/products/error.jsp";
}
}
@RequestMapping("/removeProduct.do")
public String removeProduct(String id,Model model){
Product target = bookService.findProductById(id);
String path = IdUtils.rootDir + "/src/main/webapp";
String filename=target.getImgurl();
File file = new File(path,filename);
if (file.exists()) {
//file.delete();
// 步骤五 绘制干扰线
graphics.setColor(getRandColor(160, 200));
int x1;
int x2;
int y1;
int y2;
for (int i = 0; i < 30; i++) {
x1 = random.nextInt(width);
x2 = random.nextInt(12);
y1 = random.nextInt(height);
y2 = random.nextInt(12);
graphics.drawLine(x1, y1, x1 + x2, x2 + y2);
}
// 将上面图片输出到浏览器 ImageIO
graphics.dispose();// 释放资源
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* 取其某一范围的color
*
* @param fc
* int 范围参数1
* @param bc
* int 范围参数2
* @return Color
*/
private Color getRandColor(int fc, int bc) {
// 取其随机颜色
Random random = new Random();
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
alipayRequest.setReturnUrl(AlipayConfig.return_url);
alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
//商户订单号,商户网站订单系统中唯一订单号,必填
String out_trade_no = id;
//付款金额,必填
String total_amount = money;
//订单名称,必填
String subject =id;
//商品描述,可空
String body ="";
alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
+ "\"total_amount\":\""+ total_amount +"\","
+ "\"subject\":\""+ subject +"\","
+ "\"body\":\""+ body +"\","
+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
//请求
String result = alipayClient.pageExecute(alipayRequest).getBody();
response.setContentType("text/html");
//输出
response.getWriter().print(result);
}
@RequestMapping("paysuccess.do")
public String paysuccess(HttpServletRequest request) throws Exception {
//获取支付宝GET过来反馈信息
Map<String,String> params = new HashMap<String,String>();
Map<String,String[]> requestParams = request.getParameterMap();
for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String[] values = (String[]) requestParams.get(name);
String valueStr = "";
for (int i = 0; i < values.length; i++) {
valueStr = (i == values.length - 1) ? valueStr + values[i]
: valueStr + values[i] + ",";
}
//乱码解决,这段代码在出现乱码时使用
valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
params.put(name, valueStr);
}
boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
//——请在这里编写您的程序(以下代码仅作参考)——
if(signVerified) {
//商户订单号
String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
session.setAttribute("user",user);
return "/client/myAccount.jsp";
}else {
model.addAttribute("message","请激活账户后再登陆!");
return "/client/login.jsp";
}
}else{
model.addAttribute("message","账户或密码不正确,请重新登陆!");
return "/client/login.jsp";
}
}
@RequestMapping("/active.do")
public String active(String activeCode){
int rows=userService.active(activeCode);
if(rows>0){
return "/client/activesuccess.jsp";
}else{
return "/client/activeFail.jsp";
}
}
@RequestMapping("/modifyUserInfo.do")
public String modifyUserInfo(User user,Model model,HttpSession session){
int rows=userService.modifyUserInfo(user);
if(rows>0){
model.addAttribute("message","修改成功,请重新登陆!");
return "/client/login.jsp";
}else{
model.addAttribute("error","修改用户信息失败!");
return "/client/modifyuserinfo.jsp";
}
}
@RequestMapping("/logout.do")
public String logout(HttpSession session,HttpServletRequest request,HttpServletResponse response){
session.removeAttribute("user");
Cookie cookie1 =new Cookie("bookstore_username",null);
cookie1.setMaxAge(0);
cookie1.setPath(request.getContextPath()+"/");
response.addCookie(cookie1);
Cookie cookie2 =new Cookie("bookstore_password",null);
cookie2.setMaxAge(0);
// 步骤四 四个随机数字
Graphics2D graphics2d = (Graphics2D) graphics;
// 设置输出字体
graphics2d.setFont(new Font("宋体", Font.BOLD, 18));
Random random = new Random();// 生成随机数
int index = random.nextInt(words.size());
String word = words.get(index-1);// 获得成语
// 定义x坐标
int x = 10;
for (int i = 0; i < word.length(); i++) {
// 随机颜色
graphics2d.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
// 旋转 -30 --- 30度
int jiaodu = random.nextInt(60) - 30;
// 换算弧度
double theta = jiaodu * Math.PI / 180;
// 获得字母数字
char c = word.charAt(i);
// 将c 输出到图片
graphics2d.rotate(theta, x, 20);
graphics2d.drawString(String.valueOf(c), x, 20);
graphics2d.rotate(-theta, x, 20);
x += 40;
}
System.out.println(word);
// 将验证码内容保存session
request.getSession().setAttribute("checkcode_session", word);
// 步骤五 绘制干扰线
graphics.setColor(getRandColor(160, 200));
int x1;
int x2;
int y1;
int y2;
for (int i = 0; i < 30; i++) {
x1 = random.nextInt(width);
x2 = random.nextInt(12);
y1 = random.nextInt(height);
y2 = random.nextInt(12);
List<Product> products=productService.findProductByName(name,pageModel);
model.addAttribute("count",count);
model.addAttribute("products",products);
model.addAttribute("pageModel",pageModel);
model.addAttribute("name",name);
return "/client/product_search_list.jsp";
}
@RequestMapping("/addCart.do")
public String addCart(String id, HttpSession session,Model model){
//list数组添加购物车
/* List<Cart> cart= (List<Cart>) session.getAttribute("cart");
Product product = productService.findProductById(id);
Cart book=new Cart();
if(cart!=null){
for(int i=0;i<cart.size();i++){
if(cart.get(i).getKey().getId().equals(product.getId())){
cart.get(i).setValue(cart.get(i).getValue()+1);
}else{
book.setCount(cart.get(cart.size()-1).getCount()+1);
book.setKey(product);
book.setValue(1);
cart.add(book);
break;
}
}
}else {
book.setCount(1);
book.setValue(1);
book.setKey(product);
cart=new ArrayList<>();
cart.add(book);
}
session.setAttribute("cart",cart);
model.addAttribute("p",product);
session.setAttribute("category",product.getCategory());*/
//map添加购物车
Product product = productService.findProductById(id);
Map<Product,Integer> cart= (Map<Product, Integer>) session.getAttribute("cart");
if(cart == null){
cart=new HashMap<Product,Integer>();
}
Integer count=cart.put(product,1);
if(count != null){
cart.put(product,count+1);
}
session.setAttribute("cart",cart);
model.addAttribute("p",product);
return "/client/info.jsp";
}
@RequestMapping("/changeCart.do")
public String changeCart(String id,Integer count,HttpSession session){
//map修改购物车
Product product = productService.findProductById(id);
Map<Product,Integer> cart= (Map<Product, Integer>) session.getAttribute("cart");
if(count ==0){
cart.remove(product);
}else {
cart.put(product,count);
}
return "/client/cart.jsp";
}
@RequestMapping("/showIndex.do")
public String showIndex(Model model){
Notice notice=productService.findRecentNotice();
List<Product> products=productService.findHotProduct();
model.addAttribute("notice",notice);
model.addAttribute("products",products);
return "/client/index.jsp";
}
}
package com.bookStore.utils;
/**
* 生成验证码的工具类
*/
public class CheckImageServlet extends HttpServlet {
alipayRequest.setReturnUrl(AlipayConfig.return_url);
alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
//商户订单号,商户网站订单系统中唯一订单号,必填
String out_trade_no = id;
//付款金额,必填
String total_amount = money;
//订单名称,必填
String subject =id;
//商品描述,可空
String body ="";
alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
+ "\"total_amount\":\""+ total_amount +"\","
+ "\"subject\":\""+ subject +"\","
+ "\"body\":\""+ body +"\","
+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
//请求
String result = alipayClient.pageExecute(alipayRequest).getBody();
response.setContentType("text/html");
//输出
response.getWriter().print(result);
}
@RequestMapping("paysuccess.do")
public String paysuccess(HttpServletRequest request) throws Exception {
//获取支付宝GET过来反馈信息
Map<String,String> params = new HashMap<String,String>();
Map<String,String[]> requestParams = request.getParameterMap();
for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String[] values = (String[]) requestParams.get(name);
String valueStr = "";
for (int i = 0; i < values.length; i++) {
valueStr = (i == values.length - 1) ? valueStr + values[i]
: valueStr + values[i] + ",";
}
//乱码解决,这段代码在出现乱码时使用
valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
params.put(name, valueStr);
}
boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
//——请在这里编写您的程序(以下代码仅作参考)——
if(signVerified) {
//商户订单号
String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
User user=new User();
Cookie[] cookies=request.getCookies();
for(Cookie cookie:cookies){
try {
if("bookstore_username".equals(cookie.getName())) {
username = URLDecoder.decode(cookie.getValue(), "utf-8");
}
if("bookstore_password".equals(cookie.getName())) {
password = URLDecoder.decode(cookie.getValue(), "utf-8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
user.setUsername(username);
user.setPassword(password);
return userService.findUserByNameAndPassword(user);
}
}
package com.bookStore.client.order.handler;
@Controller
@RequestMapping("/client/order")
}
System.out.println(word);
// 将验证码内容保存session
request.getSession().setAttribute("checkcode_session", word);
// 步骤五 绘制干扰线
graphics.setColor(getRandColor(160, 200));
int x1;
int x2;
int y1;
int y2;
for (int i = 0; i < 30; i++) {
x1 = random.nextInt(width);
x2 = random.nextInt(12);
y1 = random.nextInt(height);
y2 = random.nextInt(12);
graphics.drawLine(x1, y1, x1 + x2, x2 + y2);
}
// 将上面图片输出到浏览器 ImageIO
graphics.dispose();// 释放资源
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* 取其某一范围的color
*
* @param fc
* int 范围参数1
* @param bc
* int 范围参数2
* @return Color
*/
private Color getRandColor(int fc, int bc) {
// 取其随机颜色
Random random = new Random();
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
String path = IdUtils.rootDir + "/src/main/webapp/productImg";
String filename=target.getImgurl();
File file = new File(path,filename);
//file.delete();
filename = IdUtils.getUUID() + "-" + product.getFile().getOriginalFilename();
if(filename.endsWith(".jpg")||filename.endsWith(".png")){
product.getFile().transferTo(new File(path+File.separator+filename));
product.setImgurl("/productImg/"+filename);
}else {
model.addAttribute("message","上传附件失败!");
return "/admin/products/error.jsp";
}
}
bookService.modifyProduct(product);
return "redirect:/admin/product/findProduct.do";
}
}
@RequestMapping("/addProduct.do")
public String addProduct(Product product, Model model, HttpSession session,HttpServletRequest request) throws IOException {
String path =IdUtils.rootDir + "/src/main/webapp/productImg";
//上传到服务器
/* String path=session.getServletContext().getRealPath("/productImg");*/
File upload = new File(path);
if (!upload.exists()) {
upload.mkdirs();
}
String filename = IdUtils.getUUID() + "-" + product.getFile().getOriginalFilename();
if(filename.endsWith(".jpg")||filename.endsWith(".png")){
product.getFile().transferTo(new File(path+File.separator+filename));
product.setId(IdUtils.getUUID());
product.setImgurl("/productImg/"+filename);
bookService.addProduct(product);
return "redirect:/admin/product/findProduct.do";
}else {
model.addAttribute("message","上传附件失败!");
return "/admin/products/error.jsp";
}
/**
* company: www.abc.com
* Author: Administrator
*/
@Controller
@RequestMapping("/client/user")
public class UserHandler {
@Autowired
private IUserService userService;
@RequestMapping("/register.do")
public String register(User user, String checkCode, HttpSession session, HttpServletRequest request) {
String checkcode_session= (String) session.getAttribute("checkcode_session");
if(checkCode.equals(checkcode_session)){
String activeCode= ActiveCodeUtils.createActiveCode();
user.setActiveCode(activeCode);
int rows=userService.addUser(user,request);
if(rows>0){
return "/client/registersuccess.jsp";
}else{
request.setAttribute("fail","注册失败,请重试!");
return "/client/register.jsp";
}
}else{
request.setAttribute("check_fail","验证码错误,请重新输入!");
return "/client/register.jsp";
}
}
@RequestMapping("/myAccount.do")
public String myAccount(HttpSession session, Model model,HttpServletRequest request){
User user= (User) session.getAttribute("user");
if(user==null){
user=autologin(request);
if(user!=null){
session.setAttribute("user",user);
return "/client/myAccount.jsp";
}else{
model.addAttribute("message","你还未登录,请先登录!");
String sheetName=month+"月销售榜单";
String titleName=year+"年"+month+"月销售榜单";
String[] columnName={"商品名称","商品销量"};
String[][] dataList =new String[tops.size()][2];
for(int i=0;i<tops.size();i++){
dataList[i][0]=tops.get(i).getProduct().getName();
dataList[i][1]=String.valueOf(tops.get(i).getBuynum());
}
HSSFWorkbook wb=new HSSFWorkbook();
HSSFSheet sheet=wb.createSheet(sheetName);
HSSFRow row1=sheet.createRow(0);
HSSFCell cell=row1.createCell(0);
sheet.addMergedRegion(new CellRangeAddress(0,0,0,1));
cell.setCellValue(titleName);
HSSFRow row=sheet.createRow(1);
for(int i=0;i<2;i++){
row.createCell(i).setCellValue(columnName[i]);
}
for(int i=0;i<dataList.length;i++){
row=sheet.createRow(i+2);
for(int j=0;j<2;j++){
row.createCell(j).setCellValue(dataList[i][j]);
}
}
String filename=fileName+".xls";
filename=processFileName(request,filename);
response.setContentType("application/ms-excel;charset=UTF-8");
response.setHeader("content-Disposition","attachment;filename="+filename);
OutputStream out=response.getOutputStream();
wb.write(out);
}
//解决浏览器乱码
public String processFileName(HttpServletRequest request, String fileNames) {
String codedfilename = null;
try {
String agent = request.getHeader("USER-AGENT");
if (null != agent && -1 != agent.indexOf("MSIE") || null != agent
&& -1 != agent.indexOf("Trident")) {// ie
String name = java.net.URLEncoder.encode(fileNames, "UTF8");
codedfilename = name;
} else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等