赞
踩
SSH指的是spring+struts+hibernate
spring用于项目之间松散耦合,整合后端
struts使用mvc模式,作用前端页面使用dispatchservlet与后端进行交互
hibernate对象持久化框架,将实体类与数据库表进行关联,除此之外还有mybatis也较为常用,避免了JDBC带来的手写SQL的麻烦和不便于维护。
功能:
展示商城界面,添加图书至购物车,提交订单,选择地址,用户登录注册,管理员后台管理书籍,订单发货,管理用户账号等。
环境搭建
JDK:java运行时环境,自行百度配置方法即可,本项目使用java1.8
JDK1.8下载链接
tomcat:web应用服务器,存放servlet服务。本项目使用tomcat8.5
tomcat8.5下载链接
MySql:数据库,存放数据。MySql下载地址
MySql的可视化工具Navicat:Navicat下载地址
好的,开始搭建项目
1.新建项目
点击file->New->Other
选择javaweb项目即可
输入项目名,选择tomcat版本,下面的随便选
项目结构
编写配置文件
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罢了,记录学校的实训项目。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。