天天看點

SSH網上商城項目,附代碼

SSH指的是spring+struts+hibernate

spring用于項目之間松散耦合,整合後端

struts使用mvc模式,作用前端頁面使用dispatchservlet與後端進行互動

hibernate對象持久化架構,将實體類與資料庫表進行關聯,除此之外還有mybatis也較為常用,避免了JDBC帶來的手寫SQL的麻煩和不便于維護。

功能:

展示商城界面,添加圖書至購物車,送出訂單,選擇位址,使用者登入注冊,管理者背景管理書籍,訂單發貨,管理使用者賬号等。

SSH網上商城項目,附代碼
SSH網上商城項目,附代碼
SSH網上商城項目,附代碼
SSH網上商城項目,附代碼
SSH網上商城項目,附代碼

環境搭建

JDK:java運作時環境,自行百度配置方法即可,本項目使用java1.8

JDK1.8下載下傳連結

tomcat:web應用伺服器,存放servlet服務。本項目使用tomcat8.5

tomcat8.5下載下傳連結

SSH網上商城項目,附代碼

MySql:資料庫,存放資料。MySql下載下傳位址

MySql的可視化工具Navicat:Navicat下載下傳位址

SSH網上商城項目,附代碼

好的,開始搭建項目

1.建立項目

點選file->New->Other

SSH網上商城項目,附代碼

選擇javaweb項目即可

SSH網上商城項目,附代碼

輸入項目名,選擇tomcat版本,下面的随便選

SSH網上商城項目,附代碼

項目結構

SSH網上商城項目,附代碼

編寫配置檔案

application.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:mvc="http://www.springframework.org/schema/mvc"
     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-4.3.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
        <context:component-scan base-package="com"/>
        <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">
		</bean>
</beans>
           

編寫web.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>NewLife</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>filter1</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>filter1</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/application.xml</param-value>
  </context-param>
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/application.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>
           

編寫hibernate.cfg.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/newlife</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password">root</property>
  <property name="hibernate.connection.characterEncoding">UTF-8</property>
  <property name="hibernate.show_sql">true</property>
  <property name="hibernate.format_sql">true</property>
  <mapping resource="com/bean/Address.hbm.xml"/>
  <mapping resource="com/bean/Admin.hbm.xml"/>
  <mapping resource="com/bean/Book.hbm.xml"/>
  <mapping resource="com/bean/Cart.hbm.xml"/>
  <mapping resource="com/bean/User.hbm.xml"/>
  <mapping resource="com/bean/kind.hbm.xml"/>
  <mapping resource="com/bean/Orders.hbm.xml"/>
  <mapping resource="com/bean/User.hbm.xml"/>
 
 </session-factory>
</hibernate-configuration>
           

2.控制層代碼

package com;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.hibernate.criterion.Order;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.bean.Address;
import com.bean.Book;
import com.bean.Orders;
import com.bean.Page;
import com.bean.User;
import com.paging.Paging;
import com.service.AdminService;
import com.service.UserService;

@Controller
public class AdminAction {
	
@Autowired
private AdminService adminService;
@Autowired
private UserService userService;

//adminLogin
@RequestMapping(value="/AdminLogin",method=RequestMethod.POST)
public String adminLogin(Model model,String username,String password) {
	System.out.println("在AdminAction中使用者輸入的賬号密碼是"+username+password);
	boolean flag=adminService.adminLogin(username,password);
	if(flag) {
		return "adminInterFace";
	}else {
		model.addAttribute("errormsg", "username or password is wrong");
		return "AdminError";
		}	
	}

//******  show book list
@RequestMapping("/bookList")
public String booklist(Model model,Integer pageS) {
	Long totalCount = adminService.getCount();
	System.out.println(totalCount);
	Paging paging = new Paging();
	Page page = paging.checkByPage(totalCount, pageS);
	List<Book> list=adminService.showBook(page);
	model.addAttribute("page",page);
	model.addAttribute("booklist", list);
	return "bookList";
}

//show book list (user)
@RequestMapping("/userBookList")
public String booklist2(Model model,Integer pageS) {
	Long totalCount = adminService.getCount();
	System.out.println(totalCount);
	Paging paging = new Paging();
	Page page = paging.checkByPage(totalCount, pageS);
	
	List<Book> list=adminService.showBook(page);
	
	model.addAttribute("page",page);
	model.addAttribute("booklist", list);
	return "shop";
}

@RequestMapping("/userBookList1")
public String booklist3(Model model,Integer pageS) {
	Long totalCount = adminService.getCount();
	System.out.println(totalCount);
	Paging paging = new Paging();
	Page page = paging.checkByPage(totalCount, pageS);
	
	List<Book> list=adminService.showBook1(page);
	
	model.addAttribute("page",page);
	model.addAttribute("booklist", list);
	return "Hotshop";
}

@RequestMapping("/userBookList2")
public String booklist4(Model model,Integer pageS) {
	Long totalCount = adminService.getCount();
	System.out.println(totalCount);
	Paging paging = new Paging();
	Page page = paging.checkByPage(totalCount, pageS);
	List<Book> list=adminService.showBook2(page);
	model.addAttribute("page",page);
	model.addAttribute("booklist", list);
	return "Newshop";
}

//******  update Book
@RequestMapping("/updateBook")
public String updateBook(Model model,Integer id) {
	Book book=adminService.selectBookId(id);
	model.addAttribute("book", book);
	return "updatebook";
}


//***** update book submit
@RequestMapping("/updateBooksubmit")
public String updatesubmit(Book book,@RequestParam(value="files") MultipartFile file,HttpServletRequest request) {
	 if (!file.isEmpty()) {  
            try {  
               //update imgUrl
                String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"  
                        + file.getOriginalFilename();  
                System.out.println("檔案上傳到"+filePath);
                file.transferTo(new File(filePath));  
                
                book.setImgUrl(filePath);
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        } 
	boolean flag=adminService.updateBook(book);
	if(flag) {
	return "ShopList";
	}
	else {
		return "error";
	}
	}

//*****delete book
@RequestMapping("/deleteBook")
public String deleteBook(Integer id) {		
	boolean flag=adminService.deleteBook(id);
	if(flag) {
		return "redirect:/bookList.do";
		}
		else {
			return "error";
		}
		
}

//***** insert book 
@RequestMapping("/insertBook")
public String insertBook(Book book,@RequestParam(value="files") MultipartFile file,HttpServletRequest request) {
	 if (!file.isEmpty()) {  
           try {  
            
               String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"  
                       + file.getOriginalFilename();  
              
               file.transferTo(new File(filePath));  
               book.setImgUrl(filePath);
           } catch (Exception e) {  
               e.printStackTrace();  
           }  
       } 
	 boolean flag=adminService.insertBook(book);
		if(flag) {
			return "ShopList";
			}
			else {
				return "error";
			}
}

//***** show userlist
@RequestMapping("/userList")
public String userlist(Model model) {
	System.out.println("AdminAction.userlist運作成功!");
	List<User> list=adminService.showUser();
	model.addAttribute("userlist", list);
	return "userList";
}

//***** insert user
@RequestMapping("/insertUser")
public String insertUser(User user,@RequestParam(value="files") MultipartFile file,HttpServletRequest request) {
	 if (!file.isEmpty()) {  
         try {  
          
             String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"  
                     + file.getOriginalFilename();  
            
             file.transferTo(new File(filePath));  
             user.setImgUrl(filePath);
         } catch (Exception e) {  
             e.printStackTrace();  
         }  
     } 
	 boolean flag=adminService.insertUser(user);
		if(flag) {
			return "user";
			}
			else {
				return "error";
			}
}

//*****delete user
@RequestMapping("/deleteUser")
public String deleteUser(Integer id) {		
	boolean flag=adminService.deleteUser(id);
	if(flag) {
		return "redirect:/userList.do";
		}
		else {
			return "error";
		}
		
}

@RequestMapping("/ordersList")
public String adminShowAddress(Model model,Integer pageS) {
	
	
	Long totalCount = adminService.getCount();
	Paging paging = new Paging();
	Page page = paging.checkByPage(totalCount, pageS);
	
	List<Orders> list=adminService.showOrders(page);
	model.addAttribute("page",page);
	model.addAttribute("orderslist",list);
	
	return "orders";
	
}
@RequestMapping("/confirmOrders")
public String confirmOrders(Integer id) {
	System.out.println("檢視訂單詳情控制器已運作orderid為"+id);
	boolean flag = adminService.confirmOrders(id);
	if(flag) {

		return "redirect:/ordersList.do";
	}else {
		return "error";
	}
	
	
	
}

@RequestMapping("/adminFindBookId")
public String findBookId(Model model,int bookId)
{

	List<Book> list = adminService.findBookId(bookId);  //通過傳進來的bookid擷取該書本
	model.addAttribute("booklist", list);
	return "bookList";

}
@RequestMapping("/detailsOrders")
public String detailsOrders(HttpServletRequest request,Model model,HttpSession session) 
{
	int orderId = Integer.parseInt(request.getParameter("id"));
	Orders orders = new Orders();
	orders = adminService.selectOrder(orderId);
	User user = adminService.selectUser(orders.getUserId());
	Address address = new Address();
	address = adminService.lookAddress(orders.getAddressId());
	System.out.println("查到位址了嗎"+address.getProvince());
	System.out.println("查到使用者"+user.getName());
	model.addAttribute("orders",orders);
	model.addAttribute("address",address);
	model.addAttribute("user",user);
	return "detailsOrders";
}

@RequestMapping("/adminFindName")
public String adminFindName(Model model,String name)
{

	List<Orders> list = adminService.findName(name);  //通過傳進來的bookid擷取該書本
	model.addAttribute("orderslist", list);
	return "orders";

}

@RequestMapping("/findUser")
public String findUser(Model model,HttpServletRequest request)
{
	System.out.println("管理者輸入的是"+request.getParameter("name"));
	String username = request.getParameter("name");
	//int userId = Integer.parseInt(request.getParameter("name"));
	
	//User u1 = adminService.selectUser(userId);	
	User u2 = new User();
	u2 = adminService.selectUserName(username);
		if(u2 != null) {
			model.addAttribute("user",u2);
			return "userList2";
		}else {
			return "userList2";
		}
//	if(u1 == null) {
//	User u2 = new User();
//	u2 = adminService.selectUserName(username);
//		if(u2 != null) {
//			model.addAttribute("user",u2);
//			return "userList2";
//		}else {
//			return "userList2";
//		}
//	
//	}else {
//		model.addAttribute("user",u1);
//		return "userList2";
//	}

}
}

           

@RequestMapping注解對應接收dispatchServlet配置設定過來的請求,并傳回資料給指定頁面

3.bean層

package com.bean;

public class Address {
	private int addressId;
	private String province;
	private String city;
	private String town;
	private String street;
	private User user;
	private int userId;
	
	
	public String getProvince() {
		return province;
	}
	public void setProvince(String province) {
		this.province = province;
	}
	public String getTown() {
		return town;
	}
	public void setTown(String town) {
		this.town = town;
	}
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public int getAddressId() {
		return addressId;
	}
	public void setAddressId(int addressId) {
		this.addressId = addressId;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getStreet() {
		return street;
	}
	public void setStreet(String street) {
		this.street = street;
	}
	
}

           

和資料庫中類型一緻即可

4.hibernate映射檔案

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.bean">
	<class name="Address">
		<id name="addressId">
			<generator class="increment"/> 
		</id> 
		<property name="userId"/>
		<property name="province"/>
		<property name="city"/>
		<property name="town"/>
		<property name="street"/>		
	
	</class> 
</hibernate-mapping>
           

名字一定要和資料庫一一對應

5.DAO層方法

package com.Dao;

import java.util.List;

import com.bean.Address;
import com.bean.Book;
import com.bean.Orders;
import com.bean.Page;
import com.bean.User;

public interface AdminDao {
	public boolean select(String username,String password);
	
	//show all book
	public List<Book> selectAllBook(Page page);
	public List<Book> selectAllBook1(Page page);
	public List<Book> selectAllBook2(Page page);
	
	//operate book 
	public Book selectBookId(int id);
	public boolean updatebook(Book book);
	public boolean deleteBook(int id);
	public boolean insertBook(Book book);
	
	//show all user
	public List<User> selectAllUser();
	public boolean insertUser(User user);
	public boolean deleteUser(int id);

	public List<Orders> showOrders(Page page);

	public boolean confirmOrders(int orderId);

	public List<Book> findBookId(int bookId);
	public List<Orders> findName(String name);

	public Orders selectOrder(int orderId);

	public Address lookAddress(int addressId);

	public User selectUser(int userId);

	public Long getCount();

	public User selectUserName(String name);
	
}

           

6.實作類

package com.Dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import com.bean.Address;
import com.bean.Admin;
import com.bean.Book;
import com.bean.Orders;
import com.bean.Page;
import com.bean.User;
import com.hibernate.hibernateUtil;
@Repository 
public class AdminDaoImpl  implements AdminDao{
	
	@Override
	public boolean select(String username,String password) {
		Session session = hibernateUtil.openSession();
        Transaction tran = session.beginTransaction();
        
        System.out.println("使用者輸入的賬号密碼是"+username+password);
		Query query = session.createQuery("from Admin where name=? and password=?");
        query.setParameter(0, username);
        query.setParameter(1, password);
        List<Admin> list = query.list();
        
        tran.commit();
        session.close();
        
        if(list.size()>0) {
        	System.out.println("登入背景成功!");
        	return true;
        }else {
        	System.out.println("使用者名或密碼錯誤,登入背景失敗。");
        	return false;
        }
		
	}
	}
           

7.hibernate架構

package com.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class hibernateUtil {
	private static SessionFactory sessionFactory =null;
	static {
		StandardServiceRegistry registry 
	    = new StandardServiceRegistryBuilder()
	        .configure()
	        .build();
		
		 try {
	            sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
	        } catch (Exception e) {
	            StandardServiceRegistryBuilder.destroy(registry);
	            e.printStackTrace();
	        }
	}
	public static Session openSession() {
		return sessionFactory.openSession();

	}

}

           

8.分頁功能

package com.paging;

import com.bean.Page;

public class Paging {
		public Page checkByPage(Long totalCount,Integer pageS) {
			Integer dpage = 1;
			if (pageS != null) {
				dpage = pageS;
			}
			Page page = new Page();
			page.setTotalcount(totalCount);
			page.setTotalpage();
			page.setDpage(dpage);
			return page;
		}
}

           

9.service層

package com.service;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//這個servlet裡是所有方法的聲明,其具體實作在接口類裡
import com.Dao.AdminDao;
import com.bean.Address;
import com.bean.Book;
import com.bean.Orders;
import com.bean.Page;
import com.bean.User;
@Service
public class AdminService {
	@Autowired
	private AdminDao adminDao;
	
	public AdminDao getAdminrDao() {
		return adminDao;
	}
	
	//*****	admin login function
	public boolean adminLogin(String username,String password) {	
		boolean flag=adminDao.select(username, password);
		
		return flag;
	}
	}
           

以上代碼均為節選,一個小demo罷了,記錄學校的實訓項目。

繼續閱讀