1. 程式人生 > 其它 >楊校老師課堂之Java EE框架實訓寵歸於好專案開發(二)

楊校老師課堂之Java EE框架實訓寵歸於好專案開發(二)

技術標籤:Java EE

1. 編碼


1.1 建立程式包名
  • cn.javabs.pet.entity
  • cn.javabs.pet.mapper
  • cn.javabs.pet.service.impl
  • cn.javabs.pet.service
  • cn.javabs.pet.controller
  • cn.javabs.pet.util
  • cn.javabs.pet.test

客戶模組:

1.2 建立實體類
package cn.javabs.entity;

public class Users {
    // 客戶編號
    private Integer id;
   // 客戶使用者名稱
    private
String username; // 客戶密碼 private String password; // 客戶名稱 private String name; // 客戶電話 private String phone; // 客戶地址 private String address; private String passwordNew; public String getPasswordNew() { return passwordNew; } public void setPasswordNew(String passwordNew)
{ this.passwordNew = passwordNew; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username ==
null ? null : username.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone == null ? null : phone.trim(); } public String getAddress() { return address; } public void setAddress(String address) { this.address = address == null ? null : address.trim(); } }

1.3 建立業務邏輯介面
public interface UserService {
	 //驗證使用者密碼
	 boolean checkUser(String username, String password);
	 //使用者是否存在
	 boolean isExist(String username);
	 //新增
	 boolean add(Users user);
	 //通過id獲取
	 Users get(int userId);
	 //通過username獲取
	 Users get(String username);
	 //列表
	 List<Users> getList(int page, int rows);
	 //總數
	 long getTotal();
	 //更新
	 boolean update(Users user);
	 //刪除
	 boolean delete(Users user);
}

1.4 建立業務邏輯實現類
package cn.javabs.pet.service;

import java.util.List;

import cn.javabs.pet.entity.Users;
import cn.javabs.pet.mapper.UsersMapper;
import cn.javabs.pet.util.SafeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 使用者服務
 */
@Service	// 註解為service層spring管理bean
@Transactional	// 註解此類所有方法加入spring事務, 具體設定預設
public class UserService {

	@Autowired		//spring注入類物件
	private UsersMapper userMapper;
	
	/**
	 * 驗證使用者密碼
	 * @param username
	 * @param password
	 * @return
	 */
	public boolean checkUser(String username, String password){
		return userMapper.getByUsernameAndPassword(username, SafeUtil.encode(password)) != null;
	}

	/**
	 * 使用者是否存在
	 * @param username
	 * @return
	 */
	public boolean isExist(String username) {
		return userMapper.getByUsername(username) != null;
	}

	/**
	 * 新增
	 * @param user
	 * @return
	 */
	public boolean add(Users user) {
		user.setPassword(SafeUtil.encode(user.getPassword()));
		return userMapper.insert(user) > 0;
	}
	
	/**
	 * 通過id獲取
	 * @param userid
	 * @return
	 */
	public Users get(int userid){
		return userMapper.selectById(userid);
	}
	
	/**
	 * 通過username獲取
	 * @param username
	 * @return
	 */
	public Users get(String username){
		return userMapper.getByUsername(username);
	}
	
	/**
	 * 列表
	 * @param page
	 * @param rows
	 * @return
	 */
	public List<Users> getList(int page, int rows) {
		return userMapper.getList(rows * (page-1), rows);
	}

	/**
	 * 總數
	 * @return
	 */
	public long getTotal() {
		return userMapper.getTotal();
	}

	/**
	 * 更新
	 * @param user
	 */
	public boolean update(Users user) {
		return userMapper.updateById(user) > 0;
	}

	/**
	 * 刪除
	 * @param user
	 */
	public boolean delete(Users user) {
		return userMapper.deleteById(user.getId()) > 0;
	}
}

1.5 建立工具類
package cn.javabs.pet.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.springframework.util.Base64Utils;


/**
 * 安全工具類
 */
public class SafeUtil {
	
	/**
	 * md5加密字串
	 * @param str
	 * @return
	 */
	public final static String md5(String str){
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		messageDigest.update(str.getBytes());
		return Base64Utils.encodeToString(messageDigest.digest());
	}
	
	/**
	 * sha1加密字串
	 * @param str
	 * @return
	 */
	public final static String sha1(String str){
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		messageDigest.update(str.getBytes());
		return Base64Utils.encodeToString(messageDigest.digest());
	}

	/**
	 * 使用特定加密正規化加密
	 * @param str
	 * @return
	 */
	public final static String encode(String str){
		return md5(sha1(md5(str)));
	}
	
}

1.6 建立資料持久化介面
package cn.javabs.pet.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import cn.javabs.pet.entity.Users;
import org.springframework.stereotype.Repository;

@Repository
public interface UsersMapper {
    int deleteById(Integer id);

    int insert(Users record);

    int insertSelective(Users record);

    Users selectById(Integer id);

    int updateByIdSelective(Users record);

    int updateById(Users record);    
    
    // 以上為mybatis generator自動生成介面, 具體實現在mapper.xml中
    
    // ------------------------------------------------------------
    
    // 以下方法使用mybatis註解實現
    
	/**
	 * 通過使用者名稱查詢使用者
	 * @return 無記錄返回null
	 */
    @Select("select * from users where username=#{username}")
	public Users getByUsername(String username);
	
	/**
	 * 通過使用者名稱和密碼查詢
	 * @param username
	 * @param password
	 * @return 無記錄返回null
	 */
    @Select("select * from users where username=#{username} and password=#{password}")
	public Users getByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
	
	/**
	 * 獲取列表
	 * @param page
	 * @param rows
	 * @return 無記錄返回空集合
	 */
    @Select("select * from users order by id desc limit #{begin}, #{size}")
	public List<Users> getList(@Param("begin") int begin, @Param("size") int size);

	/**
	 * 總數
	 * @return
	 */
    @Select("select count(*) from users")
	public long getTotal();
}

1.7 建立控制器
package cn.javabs.pet.controller;

import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.javabs.pet.entity.Goods;
import cn.javabs.pet.entity.Items;
import cn.javabs.pet.entity.Orders;
import cn.javabs.pet.entity.Users;
import cn.javabs.pet.service.GoodService;
import cn.javabs.pet.service.OrderService;
import cn.javabs.pet.service.TypeService;
import cn.javabs.pet.service.UserService;
import cn.javabs.util.SafeUtil;

/**
 * 使用者相關介面
 */
@Controller
@RequestMapping("/index")
public class UserController{
	
	private static final String INDENT_KEY = "order";
	
	@Resource
	private UserService userService;
	@Resource
	private OrderService orderService;
	@Resource
	private GoodService goodService;
	@Resource
	private TypeService typeService;

	
	/**
	 * 註冊使用者
	 * @return
	 */
	@RequestMapping("/register")
	public String register(@RequestParam(required=false, defaultValue="0")int flag, Users user, Model model){
		model.addAttribute("typeList", typeService.getList());
		if(flag==-1) {
			model.addAttribute("flag", 5); // 註冊頁面
			return "/index/register.jsp";
		}
		if (user.getUsername().isEmpty()) {
			model.addAttribute("msg", "使用者名稱不能為空!");
			return "/index/register.jsp";
		}else if (userService.isExist(user.getUsername())) {
			model.addAttribute("msg", "使用者名稱已存在!");
			return "/index/register.jsp";
		}else {
			String password = user.getPassword();
			userService.add(user);
			user.setPassword(password);
			return "redirect:login?flag=-1"; // 註冊成功後轉去登入
		}
	}
	
	/**
	 * 使用者登入
	 * @return
	 */
	@RequestMapping("/login")
	public String login(@RequestParam(required=false, defaultValue="0")int flag, Users user, HttpSession session, Model model) {
		model.addAttribute("typeList", typeService.getList());
		if(flag==-1) {
			flag = 6; // 登入頁面
			return "/index/login.jsp";
		}
		if(userService.checkUser(user.getUsername(), user.getPassword())){
			session.setAttribute("user", userService.get(user.getUsername()));
			return "redirect:index";
		} else {
			model.addAttribute("msg", "使用者名稱或密碼錯誤!");
			return "/index/login.jsp";
		}
	}

	/**
	 * 登出登入
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		session.removeAttribute("user");
		session.removeAttribute("order");
		return "/index/login.jsp";
	}
	
	/**
	 * 檢視購物車
	 * @return
	 */
	@RequestMapping("/cart")
	public String cart(Model model) {
		model.addAttribute("typeList", typeService.getList());
		return "/index/cart.jsp";
	}
	
	/**
	 * 購買
	 * @return
	 */
	@RequestMapping("/buy")
	public @ResponseBody String buy(int goodid, HttpSession session){
		Goods goods = goodService.get(goodid);
		if (goods .getStock() <= 0) { // 庫存不足
			return "empty";
		}
		Orders order = (Orders) session.getAttribute(INDENT_KEY);
		if (order==null) {
			session.setAttribute(INDENT_KEY, orderService.add(goods));
		}else {
			session.setAttribute(INDENT_KEY, orderService.addOrderItem(order, goods));
		}
		return "ok";
	}
	
	/**
	 * 減少
	 */
	@RequestMapping("/lessen")
	public @ResponseBody String lessen(int goodid, HttpSession session){
		Orders order = (Orders) session.getAttribute(INDENT_KEY);
		if (order != null) {
			session.setAttribute(INDENT_KEY, orderService.lessenIndentItem(order, goodService.get(goodid)));
		}
		return "ok";
	}
	
	/**
	 * 刪除
	 */
	@RequestMapping("/delete")
	public @ResponseBody String delete(int goodid, HttpSession session){
		Orders order = (Orders) session.getAttribute(INDENT_KEY);
		if (order != null) {
			session.setAttribute(INDENT_KEY, orderService.deleteIndentItem(order, goodService.get(goodid)));
		}
		return "ok";
	}
	
	
	/**
	 * 提交訂單
	 * @return
	 */
	@RequestMapping("/save")
	public String save(ServletRequest request, HttpSession session, Model model){
		model.addAttribute("typeList", typeService.getList());
		Users user = (Users) session.getAttribute("user");
		if (user == null) {
			request.setAttribute("msg", "請登入後提交訂單!");
			return "/index/login.jsp";
		}
		Orders sessionOrder = (Orders) session.getAttribute(INDENT_KEY);
		if (sessionOrder != null) {
			if (sessionOrder != null) {
				for(Items item : sessionOrder.getItemList()){ // 檢測商品庫存(防止庫存不足)
					Goods product = goodService.get(item.getGoodId());
					if(item.getAmount() > product.getStock()){
						request.setAttribute("msg", "商品 ["+product.getName()+"] 庫存不足! 當前庫存數量: "+product.getStock());
						return "/index/cart.jsp";
					}
				}
			}
			sessionOrder.setUserId(user.getId());
			sessionOrder.setUser(userService.get(user.getId()));
			int orderid = orderService.save(sessionOrder);	// 儲存訂單
			session.removeAttribute(INDENT_KEY);	// 清除購物車
			return "redirect:topay?orderid="+orderid;
		}
		request.setAttribute("msg", "處理失敗!");
		return "/index/cart.jsp";
	}
	
	/**
	 * 支付頁面
	 * @return
	 */
	@RequestMapping("/topay")
	public String topay(int orderid, ServletRequest request, Model model) {
		model.addAttribute("typeList", typeService.getList());
		request.setAttribute("order", orderService.get(orderid));
		return "/index/pay.jsp";
	}
	
	/**
	 * 支付(模擬)
	 * @return
	 */
	@RequestMapping("/pay")
	public String pay(Orders order, Model model) {
		model.addAttribute("typeList", typeService.getList());
		orderService.pay(order);
		return "redirect:payok?orderid="+order.getId();
	}
	
	/**
	 * 支付成功
	 * @return
	 */
	@RequestMapping("/payok")
	public String payok(int orderid, ServletRequest request, Model model) {
		model.addAttribute("typeList", typeService.getList());
		Orders order = orderService.get(orderid);
		int paytype = order.getPaytype();
		if(paytype == Orders.PAYTYPE_WECHAT || paytype == Orders.PAYTYPE_ALIPAY) {
			request.setAttribute("msg", "訂單["+orderid+"]支付成功");
		}else {
			request.setAttribute("msg", "訂單["+orderid+"]貨到付款");
		}
		return "/index/payok.jsp";
	}
	
	/**
	 * 檢視訂單
	 * @return
	 */
	@RequestMapping("/order")
	public String order(HttpSession session, Model model){
		model.addAttribute("flag", 3);
		model.addAttribute("typeList", typeService.getList());
		Users user = (Users) session.getAttribute("user");
		if (user == null) {
			model.addAttribute("msg", "請登入後檢視訂單!");
			return "/index/login.jsp";
		}
		List<Orders> orderList = orderService.getListByUserid(user.getId());
		if (orderList!=null && !orderList.isEmpty()) {
			for(Orders order : orderList){
				order.setItemList(orderService.getItemList(order.getId()));
			}
		}
		model.addAttribute("orderList", orderList);
		return "/index/order.jsp";
	}
	
	
	/**
	 * 個人資訊
	 * @return
	 */
	@RequestMapping("/my")
	public String my(Users user, HttpSession session, Model model){
		model.addAttribute("flag", 4);
		model.addAttribute("typeList", typeService.getList());
		Users userLogin = (Users) session.getAttribute("user");
		if (userLogin == null) {
			model.addAttribute("msg", "請先登入!");
			return "/index/login.jsp";
		}
		// 進入個人中心
		if (Objects.isNull(user) || Objects.isNull(user.getId())) {
			return "/index/my.jsp";
		}
		Users u = userService.get(user.getId());
		// 修改資料
		u.setName(user.getName());
		u.setPhone(user.getPhone());
		u.setAddress(user.getAddress());
		userService.update(u);  // 更新資料庫
		session.setAttribute("user", u); // 更新session
		model.addAttribute("msg", "資訊修改成功!");
		// 修改密碼
		if(user.getPasswordNew()!=null && !user.getPasswordNew().trim().isEmpty()) {
			if (user.getPassword()!=null && !user.getPassword().trim().isEmpty() 
					&& SafeUtil.encode(user.getPassword()).equals(u.getPassword())) {
				if (user.getPasswordNew()!=null && !user.getPasswordNew().trim().isEmpty()) {
					u.setPassword(SafeUtil.encode(user.getPasswordNew()));
				}
				userService.update(u);  // 更新資料庫
				session.setAttribute("user", u); // 更新session
				model.addAttribute("msg", "密碼修改成功!");
			}else {
				model.addAttribute("msg", "原密碼錯誤!");
			}
		}
		return "/index/my.jsp";
	}
}

前臺頁面展示: