一個簡單的酒店專案【前臺和使用者和後臺】以及微信對接
阿新 • • 發佈:2018-11-05
這兩月我用了這麼久的時間寫的專案,無償分享給大家。首先,先申明這裡面程式碼非常多bug,還有很多功能沒有完成,緊靠一個學生實在太難了。那麼我先講講專案的bug,以及未完成的功能,避免大家找到又說壞話。還有專案有部分個人隱私,大家看到就當沒看到吧,反正我的資訊又不值幾個錢。哈哈~~~
一、如果出現斷網,後臺增加房間或修改房間資訊,可能會出現致命bug,事務未回滾,這個是我自己寫出來的bug,可以修改。將所有的sql封裝在一個方法裡,不要寫在其他DAO層。這個可解決,懶得改了。
二、登入按鈕這個指向的是個人域名,有需要的朋友下次再說。
三、這個使用者頁面是可以通過微信開啟,裡面有微信開發。不過登入好像有如果你在微信授權登入後,且不選擇繫結郵箱登入,很可能會出現bug,想要進行操作,一直要你登入。
- 封面設定點選後會出現心形符號,就是選中了封面。如果沒有選中圖片,預設第一張為封面。
- 郵箱可能傳送接收不到,有可能被視為垃圾郵箱或被退回郵件。
- 使用者頁面不相容電腦端,只能以手機端檢視,否則出現部分頁面無法正常顯示。請以移動端檢視。
- 使用者介面的圖片是可以點開檢視所有圖片,沒有提示內容,可以左滑動,滑不動就是隻有一張圖片。
- 標籤篩選是可以多選,有幾個沒有,所以為空。
- 新增房間有可能伺服器的穿透突然斷網,重新連線後,重複新增資料。造成重複資料新增異常。
- 新增的設施,分為便利設施和媒體科技,這個設施只是分類,需要同時選中,否則會出現空指標異常。
- 在微信對接使用,不可使用支付寶沙箱,微信會攔截,只能在網頁上充值餘額後,在微信上餘額支付訂單。
好了,大概就這樣吧!
下面我講講專案的流程以及專案的功能。
這個東西有想看,因為時間緊迫,就打包放在雲盤裡。
微信要用到穿透,以及域名的購買。
穿透軟體我這裡用的https://www.ngrok.cc/login.html,大家下好穿透軟體,當然這裡面有免費,但是網速非常慢,用花錢的好像也只是速度快了些,但是又有許多問題。
執行環境:ecplise+mysql+穿透+域名(最好使用伺服器,當然伺服器暫時沒有備案測試,可能會出現意外收穫bug)
穿透的使用
到這裡,穿透就可以使用了,不過域名得自己購買。訪問的使用就是域名加專案名。
下面就是程式碼了,因為程式碼過多,只發重要部分,其他部分大家可以直接看百度雲盤專案。
一個serlvet父類,可以簡化servlet程式碼
package com.lisonglin.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BaseServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
req.setCharacterEncoding("utf-8");
String uri = req.getRequestURI();
String method = uri.substring(uri.lastIndexOf("/")+1);
try {
Method m = this.getClass().getDeclaredMethod(method, HttpServletRequest.class,HttpServletResponse.class);
m.invoke(this, req,resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
protected void outPut(HttpServletRequest request, HttpServletResponse response, String jsonStr)
throws ServletException, IOException {
response.setContentType("application/json;charset=utf-8");// 指定返回的格式為JSON格式
response.setCharacterEncoding("UTF-8");// setContentType與setCharacterEncoding的順序不能調換,否則還是無法解決中文亂碼的問題
PrintWriter out = null;
out = response.getWriter();
out.write(jsonStr);
out.close();
}
}
這裡是主要的後臺管理實現
package com.lisonglin.web;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lisonglin.daomain.Bed;
import com.lisonglin.daomain.Easy;
import com.lisonglin.daomain.HotelLocal;
import com.lisonglin.daomain.Locals;
import com.lisonglin.daomain.Media;
import com.lisonglin.daomain.RoomArea;
import com.lisonglin.daomain.RoomLevel;
import com.lisonglin.daomain.Rooms;
import com.lisonglin.daomain.Window;
import com.lisonglin.service.BedService;
import com.lisonglin.service.EasyService;
import com.lisonglin.service.FacilitiesService;
import com.lisonglin.service.HotelLocalService;
import com.lisonglin.service.ImageService;
import com.lisonglin.service.LocalsService;
import com.lisonglin.service.MediaService;
import com.lisonglin.service.PreviewService;
import com.lisonglin.service.RoomAreaService;
import com.lisonglin.service.RoomEasyService;
import com.lisonglin.service.RoomHotelLocalService;
import com.lisonglin.service.RoomLevelService;
import com.lisonglin.service.RoomMediaService;
import com.lisonglin.service.RoomTitleService;
import com.lisonglin.service.RoomsService;
import com.lisonglin.service.WindowService;
import com.lisonglin.service.impl.BedImpl;
import com.lisonglin.service.impl.EasyImpl;
import com.lisonglin.service.impl.FacilitatiesImpl;
import com.lisonglin.service.impl.HotelLocalImpl;
import com.lisonglin.service.impl.ImageImpl;
import com.lisonglin.service.impl.LocalsImpl;
import com.lisonglin.service.impl.MediaImpl;
import com.lisonglin.service.impl.PreviewImpl;
import com.lisonglin.service.impl.RoomAreaImpl;
import com.lisonglin.service.impl.RoomEasyImpl;
import com.lisonglin.service.impl.RoomHotelLocalImpl;
import com.lisonglin.service.impl.RoomLevelImpl;
import com.lisonglin.service.impl.RoomMediaImpl;
import com.lisonglin.service.impl.RoomTitleImpl;
import com.lisonglin.service.impl.RoomsImpl;
import com.lisonglin.service.impl.WindowImpl;
import com.lisonglin.utils.DataUtil;
import com.lisonglin.utils.ProxyUtil;
import com.lisonglin.utils.UploadUtil;
@WebServlet("/rooms/*")
public class RoomServlet2 extends BaseServlet{
private static final long serialVersionUID = 1L;
protected void getAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//查詢全部房間
RoomsService rService= (RoomsService) ProxyUtil.getProxy(new RoomsImpl());
List<Rooms> room = rService.getAllRoom();
req.setAttribute("rooms", room);
//回顯到查詢出全部修改
getRooms(req);
//將圖片的base64碼新增進XML,再從前臺讀出XML中base64顯示在瀏覽器中
req.getRequestDispatcher("/admin/administration.jsp").forward(req, resp);
}
private void getRooms(HttpServletRequest req) {
//查詢房間級別
RoomLevelService roomLevelService=(RoomLevelService) ProxyUtil.getProxy(new RoomLevelImpl());
List<RoomLevel> roomLevels = roomLevelService.getRoomLevels();
//查詢床型別
BedService bService= (BedService) ProxyUtil.getProxy(new BedImpl());
List<Bed> beds = bService.getBeds();
//查詢窗型別
WindowService windowService=(WindowService) ProxyUtil.getProxy(new WindowImpl());
List<Window> windows=windowService.getWindows();
//查詢房間面積
RoomAreaService roomsService= (RoomAreaService) ProxyUtil.getProxy(new RoomAreaImpl());
List<RoomArea> roomArea = roomsService.getRoomArea();
//查詢便利設施
EasyService roomEasyService=(EasyService) ProxyUtil.getProxy(new EasyImpl());
List<Easy> roomEasies = roomEasyService.getRoomEasies();
//查詢媒體科技
MediaService mediaService=(MediaService) ProxyUtil.getProxy(new MediaImpl());
List<Media> medias = mediaService.getMedias();
//查詢酒店標籤
HotelLocalService hotelLocalService= (HotelLocalService) ProxyUtil.getProxy(new HotelLocalImpl());
List<HotelLocal> hotelLocal = hotelLocalService.getHotelLocal();
//查詢標題標籤
LocalsService lService=(LocalsService) ProxyUtil.getProxy(new LocalsImpl());
List<Locals> locals = lService.getLocals();
req.setAttribute("roomlevels", roomLevels);
req.setAttribute("beds", beds);
req.setAttribute("windows", windows);
req.setAttribute("area", roomArea);
req.setAttribute("easy", roomEasies);
req.setAttribute("medias", medias);
req.setAttribute("hotelLocal", hotelLocal);
req.setAttribute("locals", locals);
}
protected void updateRoom(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//對檔案的刪除和上傳,修改房間資訊
//上傳檔案
UploadUtil uploadUtil=new UploadUtil();
List upload = uploadUtil.upload(req);
boolean flag=true;
RoomsService rService= (RoomsService) ProxyUtil.getProxy(new RoomsImpl());
FacilitiesService fService=(FacilitiesService) ProxyUtil.getProxy(new FacilitatiesImpl());
RoomHotelLocalService roomHotelLocalService=(RoomHotelLocalService) ProxyUtil.getProxy(new RoomHotelLocalImpl());
PreviewService previewService=(PreviewService)ProxyUtil.getProxy(new PreviewImpl());
RoomMediaService rMediaService=(RoomMediaService) ProxyUtil.getProxy(new RoomMediaImpl());
RoomEasyService rEasyService=(RoomEasyService) ProxyUtil.getProxy(new RoomEasyImpl());
String easy = null,medias = null,hotellocal = null,price="";
String room="";
String path="",heart_img="";
try {
String level = null;
String local = null;
String window = null;
String bed = null;
String area = null;
Object id=null;
Object preview =null;
int roomHotelLocal=0;
for(int i=0;i<upload.size();i++) {
System.out.println(upload.get(i));
String rooms= String.valueOf(upload.get(i));
//使用者修改的表單資料
if(rooms.contains("room=")) {
String[] arr = rooms.split("&");
//根據表單資料,查詢出相應的id
for(int j=0;j<arr.length;j++) {
System.out.println("arr:"+arr[j]);
if(arr[j].contains("room")) {
room = arr[j].replaceAll("[^0-9]", "");
System.out.println("room:"+room);
//查詢要修改的設施id
id=fService.getFaciliteid(room);
//刪除原來的設施
fService.deleteFacilities(Integer.parseInt(room));
//查詢要修改的標籤id
roomHotelLocal = roomHotelLocalService.getRoomHotelLocal(room);
//刪除原來的標籤
roomHotelLocalService.deleteRoomHotelLocal(room);
System.out.println("roomHotelLocal:"+roomHotelLocal);
//查詢要修改的圖片id
preview = previewService.getPreview(room);
}else if(arr[j].contains("levels")) {
level = arr[j].replaceAll("[^0-9]", "");
}else if(arr[j].contains("local")) {
local=arr[j].replaceAll("[^0-9]", "");
}else if(arr[j].contains("window")) {
window=arr[j].replaceAll("[^0-9]", "");
}else if(arr[j].contains("bed")) {
bed=arr[j].replaceAll("[^0-9]", "");
}else if(arr[j].contains("area")) {
area=arr[j].replaceAll("[^0-9]", "");
}else if(arr[j].contains("price")) {
price=arr[j].replaceAll("[^0-9]", "");
}else if(arr[j].contains("easy")) {
easy=arr[j].replaceAll("[^0-9]", "");
System.out.println("roomid:"+room);
//新增設施
rEasyService.addEasy(Integer.parseInt(id+""), Integer.parseInt(easy));
}else if(arr[j].contains("medias=")) {
medias=arr[j].replaceAll("[^0-9]", "");
//新增設施
rMediaService.addRoomMedia(Integer.parseInt(id+""),Integer.parseInt(medias));
}
if(arr[j].contains("hotellocal")) {
hotellocal=arr[j].replaceAll("[^0-9]", "");
roomHotelLocalService.addRoomHotelLocal(roomHotelLocal, Integer.parseInt(hotellocal));
}
}
}
//刪除的圖片
if(rooms.contains("deleteImg=")) {
String deleteimg = rooms.substring(rooms.indexOf("=")+1,rooms.length());
previewService.deletePreview(preview+"", deleteimg);
}
//使用者上傳的圖片
if(rooms.contains("files=")) {
String uploadpath = rooms.substring(rooms.indexOf("=")+1,rooms.length());
String uploadimg = uploadpath.substring(uploadpath.lastIndexOf("/")+1,uploadpath.length());
previewService.addPreview(preview+"", uploadimg, uploadpath);
}
//封面
if(rooms.contains("heart_img=")) {
heart_img = rooms.substring(rooms.indexOf("=")+1,rooms.length());
String rowpath = req.getServletContext().getRealPath("/");
// 獲取當前時間
String xdPath = "images/";
path = rowpath + xdPath+heart_img;
}
}
rService.updateRoom(level, window, area, bed, Double.parseDouble(price), level, local, path, heart_img, room);
}catch (Exception e) {
e.printStackTrace();
flag=false;
}
resp.getWriter().write(flag==true?"success":"error");
}
protected void getAddRoom(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
getRooms(req);
req.getRequestDispatcher("/admin/add.jsp").forward(req, resp);
}
//新增房間
@SuppressWarnings("unlikely-arg-type")
protected void addRoom(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
req.setCharacterEncoding("utf-8");
//上傳檔案
UploadUtil uploadUtil=new UploadUtil();
List upload = uploadUtil.upload(req);
//增加房間(rooms)
RoomsService rService= (RoomsService) ProxyUtil.getProxy(new RoomsImpl());
ImageService imageService=(ImageService) ProxyUtil.getProxy(new ImageImpl());
RoomTitleService roomTitleService= (RoomTitleService) ProxyUtil.getProxy(new RoomTitleImpl());
RoomEasyService roomEasyService=(RoomEasyService) ProxyUtil.getProxy(new RoomEasyImpl());
FacilitiesService fService=(FacilitiesService) ProxyUtil.getProxy(new FacilitatiesImpl());
MediaService mediaService=(MediaService) ProxyUtil.getProxy(new MediaImpl());
RoomHotelLocalService roomHotelLocalService=(RoomHotelLocalService) ProxyUtil.getProxy(new RoomHotelLocalImpl());
RoomAreaService roomAreaService=(RoomAreaService) ProxyUtil.getProxy(new RoomAreaImpl());
//查詢最大的設施號
int facilite = fService.getFacilite();
//查詢最大的標籤號
int roomHotelLocal = roomHotelLocalService.getRoomHotelLocal();
//查詢最大的照片號
int iamges = imageService.getIamges();
String easy = null,medias = null,hotellocal = null,price="",newimg="",local="",roomlevel="";
String room="",level="",window="",bed="",area="",imgs="",oldimg="";
//查詢增加面積的對應id
int roomArea = roomAreaService.getRoomAreas();
//查詢最大的標題號
int roomTitle = roomTitleService.getRoomTitle();
try {
for(int i=0;i<upload.size();i++) {
//各類相應的資料
String rooms= String.valueOf(upload.get(i));
System.out.println("rooms:"+rooms);
if(rooms.contains("&")) {
System.out.println(rooms.contains("&"));
String[] arr = rooms.split("&");
//房間號
room = (arr[0]+"").replaceAll("[^0-9]", "");
//標題
local=(arr[1]+"").replaceAll("[^0-9]", "");
roomlevel=(arr[2]+"").replaceAll("[^0-9]", "");
//級別
level=(arr[3]+"").replaceAll("[^0-9]", "");
//窗
window=(arr[4]+"").replaceAll("[^0-9]", "");
//床
bed=(arr[5]+"").replaceAll("[^0-9]", "");
//面積
area=(arr[6]+"").replaceAll("[^0-9]", "");
for(int j = 0; j < arr.length;j++){
System.out.println("arr:"+arr[j]);
//設施(便利設施)
if(rooms.contains("easy")) {
if((arr[j]+"").contains("easy")) {
easy=(arr[j]+"").replaceAll("[^0-9]","");
// System.out.println("facilite:"+facilite);
//增加房間設施(room_easy)
roomEasyService.addEasy(facilite+1, Integer.parseInt(easy));
}
}else {
System.out.println("easyno");
resp.getWriter().write("no");
return;
}
//媒體科技
if(rooms.contains("medias")) {
if((arr[j]+"").contains("easy")) {
medias=(arr[j]+"").replaceAll("[^0-9]", "");
// System.out.println("medias:"+medias);
mediaService.addMedias(facilite+1, Integer.parseInt(medias));
}
}else {
System.out.println("no");
resp.getWriter().write("no");
return;
}
//標籤
if(rooms.contains("hotellocal")) {
if((arr[j]+"").contains("easy")) {
//增加酒店房間標籤(room_hotel_loc)
hotellocal=(arr[j]+"").replaceAll("[^0-9]", "");
// System.out.println("hotellocal:"+(roomHotelLocal+1));
roomHotelLocalService.addRoomHotelLocal(roomHotelLocal+1, Integer.parseInt(hotellocal));
}
}else {
System.out.println("hotelno");
resp.getWriter().write("no");
return;
}
//價格
if((arr[j]+"").contains("price")) {
price=(arr[j]+"").replaceAll("[^0-9]", "");
}
}
System.out.println(room+","+local+","+roomlevel+","+level+","+window+","+bed+","+area+","+easy+","+medias+","+hotellocal+","+price);
}
imgs =String.valueOf(upload.get(i));
// System.out.println("imgs:"+imgs);
if(String.valueOf(upload.get(0))!=null) {
if(imgs.contains("E://apache")) {
//直接擷取後面的檔名
oldimg = imgs.substring(imgs.lastIndexOf("//")+1,imgs.length());
System.out.println("imgok");
//增加房間照片(img_md5,preview)
imageService.addIamges(iamges+1,"", imgs, oldimg);
newimg=imgs.substring(0,imgs.lastIndexOf("//"));
System.out.println("room:"+room+"oldimg:"+oldimg);
//照片
}
}else {
System.out.println("imgno");
return;
}
}
//增加圖片的md5加密的資料庫
//最後新增設施關聯表
fService.addFacilite(facilite+1, facilite+1);
//增加房間封面
if(String.valueOf(upload.get(0)).equals("")) {
System.out.println("123imgno");
return;
}
imageService.addImages(iamges+1,newimg+"/"+String.valueOf(upload.get(0)), Integer.parseInt(room), String.valueOf(upload.get(0)));
System.out.println("roomTitle:"+roomTitle);
//增加房間標題(roomtitle)
roomTitleService.addRoomTitle(roomTitle+1,Integer.parseInt(local), Integer.parseInt(roomlevel));
//增加面積
if(area!=null) {
roomAreaService.addRoomArea(roomArea+1,Integer.parseInt(area));
}
//查詢設施id
int faciliteid = fService.getFaciliteid();
//增加房間
System.out.println("room:"+room+",level:"+level+",window:"+window+",rooomArea:"+roomArea+",bed:"+bed+",price:"+price+",roomTitle:"+roomTitle+",images:"+iamges+",faciliteid:"+faciliteid+",roomHotellocal:"+roomHotelLocal);
rService.addRoom(Integer.parseInt(room), Integer.parseInt(level),Integer.parseInt(window) ,
roomArea+1, Integer.parseInt(bed), Integer.parseInt(price), roomTitle+1, iamges+1,
faciliteid, roomHotelLocal+1);
//封面
//圖片的絕對路徑
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("其他異常");
}
//重定向
// resp.sendRedirect("/hotelSystem/room/getAll");
System.out.println("封面:"+upload.get(0));
System.out.println("upload:"+upload);
if(room!=null&&level!=null&&bed!=null) {
System.out.println("ok");
}else {
System.out.println("no");
}
//上面執行成功後,返回前臺成功
resp.getWriter().write(room!=null?"add":"no");
}
//後臺驗證房間號
protected void checkRoomId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//根據url傳過來的引數
String roomid = req.getParameter("roomid");
RoomsService rService= (RoomsService) ProxyUtil.getProxy(new RoomsImpl());
Object id = rService.checkRoomId(roomid);
resp.getWriter().write(id==null?"success":"error");
}
//查詢預覽圖片
protected void getIamges(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//根據封面id
String oldimg = req.getParameter("oldimg");
ImageService imageService=(ImageService) ProxyUtil.getProxy(new ImageImpl());
String imgpath=imageService.getIamgesPath(oldimg);
System.out.println("imgpath:"+imgpath);
req.setAttribute("imgpath", imgpath);
req.getRequestDispatcher("/admin/img.jsp").forward(req, resp);
}
//搜尋框輸入的內容
protected void checkRoomData(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String roomid = req.getParameter("data");
System.out.println(roomid);
RoomsService rService= (RoomsService) ProxyUtil.getProxy(new RoomsImpl());
if(roomid.equals("")) {
List<Rooms> room = rService.getAllRoom();
req.setAttribute("rooms", room);
resp.getWriter().write("all");
req.getRequestDispatcher("/admin/administration.jsp").forward(req, resp);
}else if(!DataUtil.isInteger(roomid)){
System.out.println("null");
resp.getWriter().write("null");
}else {
resp.getWriter().write("success");
List<Rooms> likeRoom = rService.getLikeRoom(roomid);
req.setAttribute("rooms", likeRoom);
req.getRequestDispatcher("/admin/administration.jsp").forward(req, resp);
}
System.out.println("roomid:"+roomid);
}
//刪除選中的房間
protected void deleteRoom(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
System.out.println("id:"+id);
RoomsService rService= (RoomsService) ProxyUtil.getProxy(new RoomsImpl());
try {
boolean deleteRoom = rService.deleteRoom(id);
if(deleteRoom) {
resp.getWriter().write("success");
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("其他異常");
}
}
//查詢窗戶和床
protected void bedorwindow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
WindowService windowService=(WindowService) ProxyUtil.getProxy(new WindowImpl());
List<Window> windows = windowService.getWindows();
BedService bedService=(BedService) ProxyUtil.getProxy(new BedImpl());
List<Bed> beds = bedService.getBeds();
req.setAttribute("windows", windows);
req.setAttribute("beds", beds);
req.getRequestDispatcher("/admin/bedorwindow.jsp").forward(req, resp);
}
//驗證窗戶和床
protected void checkbedorwindow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String result = req.getParameter("result");
if(result!=null) {
WindowService windowService=(WindowService) ProxyUtil.getProxy(new WindowImpl());
Object checkWindow = windowService.checkWindow(result);
resp.getWriter().write(checkWindow==null?"success":"error");
}
String result1=req.getParameter("result1");
if(result1!=null) {
String[] arr = result1.split(",");
String bedNumber=arr[0];
String bedWidth=arr[1];
String bedBed=arr[2];
BedService bedService=(BedService) ProxyUtil.getProxy(new BedImpl());
Object checkBed=bedService.checkBed(bedNumber,bedWidth,bedBed);
resp.getWriter().write((checkBed+"").equals("0")?"success":"error");
}
}
//增加窗戶和床
protected void addbedorwindow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String result = req.getParameter("result");
if(result!=null) {
WindowService windowService=(WindowService) ProxyUtil.getProxy(new WindowImpl());
boolean flag= windowService.addWindow(result);
resp.getWriter().write(flag==true?"bedorwindow":"error");
}
String bedNumStr=req.getParameter("bedNumStr");
String bedWidthStr=req.getParameter("bedWidthStr");
String bedNameStr=req.getParameter("bedNameStr");
if(bedNameStr!=null&&bedNumStr!=null&&bedWidthStr!=null) {
BedService bedService=(BedService) ProxyUtil.getProxy(new BedImpl());
boolean flag=bedService.addBed(bedNumStr,bedWidthStr,bedNameStr);
resp.getWriter().write(flag==true?"bedorwindow":"error");
}
}
//修改窗戶和床
protected void updatebedorwindow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
String result = req.getParameter("result");
if(id!=null&&result!=null) {
WindowService windowService=(WindowService) ProxyUtil.getProxy(new WindowImpl());
boolean flag=windowService.updateWindow(result,id);
resp.getWriter().write(flag==true?"bedorwindow":"error");
}
String bedid = req.getParameter("bedid");
String bedNumStr=req.getParameter("bedNumStr");
String bedWidthStr=req.getParameter("bedWidthStr");
String bedNameStr=req.getParameter("bedNameStr");
if(bedNameStr!=null&&bedNumStr!=null&&bedWidthStr!=null) {
BedService bedService=(BedService) ProxyUtil.getProxy(new BedImpl());
boolean flag=bedService.updateBed(bedNumStr,bedWidthStr,bedNameStr,bedid);
resp.getWriter().write(flag==true?"bedorwindow":"error");
}
}
//查詢設施和標籤
protected void facilitiesorlocal(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
MediaService mediaService=(MediaService) ProxyUtil.getProxy(new MediaImpl());
List<Media> medias = mediaService.getMedias();
EasyService roomEasyService=(EasyService) ProxyUtil.getProxy(new EasyImpl());
List<Easy> roomEasies = roomEasyService.getRoomEasies();
HotelLocalService hotelLocalService= (HotelLocalService) ProxyUtil.getProxy(new HotelLocalImpl());
List<HotelLocal> hotelLocal = hotelLocalService.getHotelLocal();
req.setAttribute("easy", roomEasies);
req.setAttribute("medias", medias);
req.setAttribute("hotelLocal", hotelLocal);
req.getRequestDispatcher("/admin/facilitiesorlocal.jsp").forward(req, resp);
}
//增加設施
protected void addfacilitiesorlocal(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String hotellocal = req.getParameter("hotellocal");
if(hotellocal!=null) {
HotelLocalService hotelLocalService= (HotelLocalService) ProxyUtil.getProxy(new HotelLocalImpl());
boolean flag= hotelLocalService.addHotelLocal(hotellocal);
resp.getWriter().write(flag==true?"facilitiesorlocal":"error");
}
String media = req.getParameter("media");
if(media!=null) {
MediaService mediaService=(MediaService) ProxyUtil.getProxy(new MediaImpl());
boolean flag= mediaService.addMedias(media);
resp.getWriter().write(flag==true?"facilitiesorlocal":"error");
}
String easy = req.getParameter("easy");
if(easy!=null) {
EasyService roomEasyService=(EasyService) ProxyUtil.getProxy(new EasyImpl());
boolean flag= roomEasyService.addEasy(easy);
resp.getWriter().write(flag==true?"facilitiesorlocal":"error");
}
}
//修改設施
protected void updatefacilitiesorlocal(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String hotellocal = req.getParameter("hotellocal");
String hotellocalid = req.getParameter("hotellocalid");
if(hotellocal!=null) {
HotelLocalService hotelLocalService= (HotelLocalService) ProxyUtil.getProxy(new HotelLocalImpl());
boolean flag= hotelLocalService.updateHotelLocal(hotellocal,hotellocalid);
resp.getWriter().write(flag==true?"facilitiesorlocal":"error");
}
String media = req.getParameter("media");
String mediaid = req.getParameter("mediaid");
if(media!=null) {
MediaService mediaService=(MediaService) ProxyUtil.getProxy(new MediaImpl());
boolean flag= mediaService.updateMedias(media,mediaid);
resp.getWriter().write(flag==true?"facilitiesorlocal":"error");
}
String easy = req.getParameter("easy");
String easyid = req.getParameter("easyid");
if(easy!=null) {
EasyService roomEasyService=(EasyService) ProxyUtil.getProxy(new EasyImpl());
boolean flag= roomEasyService.updateEasy(easy,easyid);
resp.getWriter().write(flag==true?"facilitiesorlocal":"error");
}
}
//驗證設施
protected void checkfacilitiesorlocal(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String hotellocal = req.getParameter("hotellocal");
if(hotellocal!=null) {
HotelLocalService hotelLocalService= (HotelLocalService) ProxyUtil.getProxy(new HotelLocalImpl());
Object checkHotelLocal= hotelLocalService.checkHotelLocal(hotellocal);
resp.getWriter().write(checkHotelLocal==null?"success":"error");
}
String media = req.getParameter("media");
if(media!=null) {
MediaService mediaService=(MediaService) ProxyUtil.getProxy(new MediaImpl());
Object checkMedia= mediaService.checkMedia(media);
resp.getWriter().write(checkMedia==null?"success":"error");
}
String easy = req.getParameter("easy");
if(easy!=null) {
EasyService roomEasyService=(EasyService) ProxyUtil.getProxy(new EasyImpl());
Object checkEasy= roomEasyService.checkEasy(easy);
resp.getWriter().write(checkEasy==null?"success":"error");
}
}
}
微信開發的servlet,其中有訊息回覆,二級選單,以及關注提示,還有微信授權登入
package com.lisonglin.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lisonglin.service.OrderService;
import com.lisonglin.service.RoomsService;
import com.lisonglin.service.UserService;
import com.lisonglin.service.impl.OrderImpl;
import com.lisonglin.service.impl.RoomsImpl;
import com.lisonglin.service.impl.UserImpl;
import com.lisonglin.utils.JdbcUtil;
import com.lisonglin.utils.MessageUtil;
import com.lisonglin.utils.ProxyUtil;
import com.lisonglin.weixin.daomin.Orders;
import com.lisonglin.weixin.daomin.Users;
@WebServlet("/weixin")
public class weixin extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final UserService us = (UserService) ProxyUtil.getProxy(new UserImpl());//使用者
private static final OrderService os= (OrderService) ProxyUtil.getProxy(new OrderImpl());
private static final RoomsService rs=(RoomsService) ProxyUtil.getProxy(new RoomsImpl());
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//驗證訊息的確來自微信伺服器 校驗四個引數
String signature = request.getParameter("signature"); //微信加密簽名
String timestamp = request.getParameter("timestamp"); //時間戳
String nonce = request.getParameter("nonce"); //隨機數
String echostr = request.getParameter("echostr"); //隨機字串
System.out.println("signature:"+signature);
System.out.println("timestamp:"+timestamp);
System.out.println("nonce:"+nonce);
System.out.println("echostr:"+echostr);
PrintWriter out = response.getWriter();
if(MessageUtil.checkSignature(signature, timestamp, nonce)){
System.out.println("連線成功");
out.print(echostr);
out.flush();
out.close();
}else {
System.out.println("連線失敗");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletInputStream sis = request.getInputStream();
request.setCharacterEncoding("utf8");
response.setCharacterEncoding("utf8");
Map<String, String> requestMap = MessageUtil.parseXml(sis);
String msg2Xml="";
String fromUserName = requestMap.get("FromUserName");
String toUserName = requestMap.get("ToUserName");
String createTime = requestMap.get("CreateTime");
String msgType = requestMap.get("MsgType");
String content = requestMap.get("Content");
String nsgId = requestMap.get("MsgId");
//判斷請求是否事件型別 event
if(MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(msgType)) {
String eventType = requestMap.get("Event");
//若是關注事件 subscribe
if(MessageUtil.EVENT_TYPE_SUBSCRIBE.equals(eventType)){
String mycontent = MessageUtil.menuText();
msg2Xml = MessageUtil.initText(toUserName, fromUserName, mycontent);
}else if(MessageUtil.EVENT_TYPE_UNSUBSCRIBE.equals(eventType)) {
// TODO 取消訂閱後用戶再收不到公眾號傳送的訊息,因此不需要回復訊息
} // 自定義選單點選事件
else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
// 事件KEY值,與建立自定義選單時指定的KEY值對應
String eventKey = requestMap.get("EventKey");
System.out.println("eventKey:"+eventKey);
Users user =us.getByOpenid(requestMap.get("FromUserName"));//使用者openid
if(user!=null) {
if(eventKey.equals("31")){
msg2Xml=MessageUtil.initText(toUserName, fromUserName,"您的餘額為:"+ user.getReserve()+"元");
}else if(eventKey.equals("32")){
/**
* 微信重複登入會出現錯誤
*/
List<Orders> orders = os.getByUserOrder(requestMap.get("FromUserName"));
int count=0;
if(orders.size()==0) {
msg2Xml=MessageUtil.initText(toUserName, fromUserName, "你還未開始行程!");
}else if(orders.size()<=8){
count=orders.size();
msg2Xml=MessageUtil.getImagesMessage(toUserName, fromUserName, orders, count);
}else {
count=8;
msg2Xml=MessageUtil.getImagesMessage(toUserName, fromUserName, orders, count);
}
}
}else {
msg2Xml=MessageUtil.initText(toUserName, fromUserName, "親愛的使用者,請你先"+JdbcUtil.prop.getProperty("a")+"!");
}
}
}else if(MessageUtil.REQ_MESSAGE_TYPE_TEXT.equals(msgType)) {
if(content.equals("訂房")) {
String orderText = MessageUtil.orderText();
msg2Xml = MessageUtil.initText(toUserName, fromUserName, orderText);
}else if(content.equals(rs.getLikeRooms(content))){
}
}
System.out.println("msg2Xml:"+msg2Xml);
PrintWriter out = response.getWriter();
out.write(msg2Xml);
out.flush();
out.close();
}
}
微信工具類
package com.lisonglin.utils;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.ServletInputStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.lisonglin.daomain.Rooms;
import com.lisonglin.weixin.daomin.AccessToken;
import com.lisonglin.weixin.daomin.Article;
import com.lisonglin.weixin.daomin.HikktyTextMsg;
import com.lisonglin.weixin.daomin.NewsMessage;
import com.lisonglin.weixin.daomin.Orders;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import net.sf.json.JSONObject;
/**
* @Description: 訊息工具類
* @author 12134
*
*/
public class MessageUtil {
/**
* 返回訊息型別:文字
*/
public static final String RESP_MESSAGE_TYPE_TEXT = "text";
/**
* 返回訊息型別:音樂
*/
public static final String RESP_MESSAGE_TYPE_MUSIC = "music";
/**
* 返回訊息型別:圖文
*/
public static final String RESP_MESSAGE_TYPE_NEWS = "news";
/**
* 返回訊息型別:圖片
*/
public static final String RESP_MESSAGE_TYPE_Image = "image";
/**
* 返回訊息型別:語音
*/
public static final String RESP_MESSAGE_TYPE_Voice = "voice";
/**
* 返回訊息型別:視訊
*/
public static final String RESP_MESSAGE_TYPE_Video = "video";
/**
* 請求訊息型別:文字
*/
public static final String REQ_MESSAGE_TYPE_TEXT = "text";
/**
* 請求訊息型別:圖片
*/
public static final String REQ_MESSAGE_TYPE_IMAGE = "image";
/**
* 請求訊息型別:連結
*/
public static final String REQ_MESSAGE_TYPE_LINK = "link";
/**
* 請求訊息型別:地理位置
*/
public static final String REQ_MESSAGE_TYPE_LOCATION = "location";
/**
* 請求訊息型別:音訊
*/
public static final String REQ_MESSAGE_TYPE_VOICE = "voice";
/**
* 請求訊息型別:視訊
*/
public static final String REQ_MESSAGE_TYPE_VIDEO = "video";
/**
* 請求訊息型別:推送
*/
public static final String REQ_MESSAGE_TYPE_EVENT = "event";
/**
* 事件型別:subscribe(訂閱)
*/
public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";
/**
* 事件型別:unsubscribe(取消訂閱)
*/
public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";
/**
* 事件型別:CLICK(自定義選單點選事件)
*/
public static final String EVENT_TYPE_CLICK = "CLICK";
/**
* 事件型別:VIEW(自定義選單URl檢視)
*/
public static final String EVENT_TYPE_VIEW = "VIEW";
/**
* 事件型別:LOCATION(上報地理位置事件)
*/
public static final String EVENT_TYPE_LOCATION = "LOCATION";
/**
* 事件型別:LOCATION(上報地理位置事件)
*/
public static final String EVENT_TYPE_SCAN = "SCAN";
public static final SAXReader reader = new SAXReader();
private static final XStream xstream = new XStream();
public static final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
'f' };
public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
// sha1加密
public static String getSHA1(String str) {
if (str == null || str.length() == 0) {
return null;
}
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA-1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
return null;
}
}
public static boolean checkSignature(String signature, String timestamp, String nonce) {
// 排序
String[] arr = new String[] { JdbcUtil.prop.getProperty("token"), timestamp, nonce };
// 將token、timestamp、nonce三個引數進行字典序排序
Arrays.sort(arr);
// 生成字串
StringBuffer content = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
// sha1 加密 java實現訊息摘要加密
String temp = getSHA1(content.toString());
// 和微信傳遞過來的引數進行校驗
return temp.equals(signature);
}
public static Map<String, String> parseXml(ServletInputStream sis) {
Map<String, String> map = new HashMap<>();
try {
Document document = reader.read(sis);
Element root = document.getRootElement();
// 獲取子節點的集合
@SuppressWarnings("unchecked")
List<Element> elements = root.elements();
for (Element e : elements) {
map.put(e.getName(), e.getStringValue());
}
} catch (DocumentException e) {
e.printStackTrace();
}
return map;
}
public static String textMessageToXml(HikktyTextMsg textMessage) {
xstream.alias("xml", textMessage.getClass());
xstream.processAnnotations(HikktyTextMsg.class);
return xstream.toXML(textMessage);
}
public static String newsMessageToXml(NewsMessage newsMessage) {
xstream.alias("xml", newsMessage.getClass());
xstream.alias("item", new Article().getClass());
xstream.processAnnotations(NewsMessage.class);
xstream.processAnnotations(Article.class);
return xstream.toXML(newsMessage);
}
public static String initText(String toUserName, String fromUserName, String content) {
HikktyTextMsg text = new HikktyTextMsg();
text.setFromUserName(toUserName);
text.setToUserName(fromUserName);
text.setMsgType(RESP_MESSAGE_TYPE_TEXT);
text.setCreateTime(String.valueOf(new Date().getTime()));
text.setContent(content);
return textMessageToXml(text);
}
public static String getImagesMessage(String toUserName,String fromUserName,List<Orders> orders,int count) {
NewsMessage news=new NewsMessage();
news.setFromUserName(toUserName);
news.setToUserName(fromUserName);
news.setMsgType(RESP_MESSAGE_TYPE_NEWS);
news.setCreateTime(String.valueOf(new Date().getTime()));
news.setArticleCount(count);
List<Article> articles=new ArrayList<>();
for(int i=0;i<count;i++) {
Orders o = orders.get(i);
Article article=new Article();
article.setTitle(o.getRoom().get(i).getDescribe().get(0).getLevel().getLevel()
+o.getRoom().get(i).getDescribe().get(0).getLocal().getLocalcontent());
article.setDescription(o.getPrice()+"元");
article.setPicUrl(JdbcUtil.prop.getProperty("addr")+"/images/"+o.getRoom().get(i).getImages().get(0).getOldimg());
article.setUrl(JdbcUtil.prop.getProperty("addr")+"/users/getOrder?orderid="+o.getOrderid());
articles.add(article);
news.setArticles(articles);
}
return newsMessageToXml(news);
}
public static String menuText() {
StringBuffer sb = new StringBuffer();
sb.append(" 你關注,\n");
sb.append(" 或者不關注,\n");
sb.append(" 【藍橋酒店】都在這裡!\n");
sb.append(" 不離,\n");
sb.append(" 不棄!\n\n");
sb.append("該公眾號已實現以下功能:\n");
sb.append("回覆“訂房”、“標籤”、“等級”、“設施” 將有該功能的介紹與使用,\n");
sb.append("如您在使用該公眾有任何寶貴意見,歡迎反饋!\n\n");
sb.append("反饋郵箱:[email protected]");
return sb.toString();
}
public static String orderText() {
StringBuilder sb = new StringBuilder();
sb.append("【藍橋酒店】\n");
sb.append("你想要房間應有盡有,\n");
sb.append("只有親你想不到的。\n");
sb.append("訂房連結:http://www.hikkty.com/hotelSystem/users/get \n");
return sb.toString();
}
public static String userText() {
StringBuilder sb = new StringBuilder();
sb.append("親愛的使用者,請你先"+JdbcUtil.prop.getProperty("a")+"!");
return sb.toString();
}
public static String localText() {
StringBuilder sb = new StringBuilder();
// 查詢出對應的房間號和房間標題以及房間圖片
sb.append("");
return sb.toString();
}
public static String getAccessToken() {
String urlString = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ JdbcUtil.prop.getProperty("APPID") + "&secret=" + JdbcUtil.prop.getProperty("SECERT");
//請求連線
String httpGet = httpGet(urlString);
System.out.println("result:"+httpGet);
JSONObject jsonObject = JSONObject.fromObject(httpGet);
String atStr = jsonObject.getString("access_token");
String ei = jsonObject.getString("expires_in");
AccessToken accessToken = new AccessToken();
accessToken.setToken(atStr);
accessToken.setExpiresIn(Integer.parseInt(ei));
if(accessToken.getToken()!=null) {
return accessToken.getToken();
}else {
return null;
}
}
public static String httpGet(String url) {
String reslut = null;
try {
URL reqURL = new URL(url);
HttpsURLConnection httpsConn = (HttpsURLConnection) reqURL
.openConnection();
InputStreamReader isr = new InputStreamReader(
httpsConn.getInputStream());
char[] chars = new char[1024];
reslut = "";
int len;
while ((len = isr.read(chars)) != -1) {
reslut += new String(chars, 0, len);
}
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
return reslut;
}
public static void httpPost(String url,String data) {
try {
// 建立一個url
URL reqURL = new URL(url);
// 拿取連結
HttpsURLConnection httpsConn = (HttpsURLConnection) reqURL.openConnection();
httpsConn.setDoOutput(true);
httpsConn.setDoInput(true);
// 取得該連線的輸出流,以讀取響應內容
OutputStreamWriter osr = new OutputStreamWriter(httpsConn.getOutputStream());
osr.write(data);// 使用本類外部方法getMenuJson()
osr.close();
// 返回結果
InputStreamReader isr = new InputStreamReader(httpsConn.getInputStream());
// 讀取伺服器的響應內容並顯示
char[] chars = new char[1024];
String reslut = "";
int len;
while ((len = isr.read(chars)) != -1) {
reslut += new String(chars, 0, len);
}
System.out.println("返回結果:" + reslut);
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 物件到xml的處理
*/
private static XStream xstreams = new XStream(new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 對所有xml節點的轉換都增加CDATA標記
boolean cdata = true;
@SuppressWarnings("rawtypes")
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
});
}
微信二級選單,只需要選中就可以run執行
package com.lisonglin.test;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.junit.Test;
import com.google.gson.Gson;
import com.lisonglin.utils.MessageUtil;
import com.lisonglin.weixin.daomin.Button;
import com.lisonglin.weixin.daomin.CommonButton;
import com.lisonglin.weixin.daomin.ComplexButton;
import com.lisonglin.weixin.daomin.Menu;
public class MyMenuDemo {
/*
* 建立自定義選單。
*/
@Test
public void createCommMenu() {
String ACCESS_TOKEN = MessageUtil.getAccessToken();// 獲取AccessToken,AccessTokenUtils是封裝好的類
System.out.println("ACCESS_TOKEN:"+ACCESS_TOKEN);
// 拼接api要求的httpsurl連結
String urlString = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + ACCESS_TOKEN;
MessageUtil.httpPost(urlString, getMenuJson());
}
public String getMenuJson() {
Gson gson = new Gson();// json處理工具
/**
* 二級選單
*/
CommonButton btn31 = new CommonButton();
btn31.setName("使用者餘額");
btn31.setType("click");
btn31.setKey("31");
CommonButton btn32 = new CommonButton();
btn32.setName("使用者行程");
btn32.setType("click");
btn32.setKey("32");
/**
* 選單基類
*/
CommonButton mainBtn1 = new CommonButton();
mainBtn1.setName("酒店首頁");
mainBtn1.setUrl("http://www.hikkty.com/hotelSystem/users/get");
mainBtn1.setType("view");//scancode_push:掃描二維碼,pic_weixin
CommonButton mainBtn2 = new CommonButton();
mainBtn2.setName("我的訂單");
mainBtn2.setUrl("http://www.hikkty.com/hotelSystem/users/skip");
mainBtn2.setType("view");
/**
* 二級選單基類
*/
ComplexButton mainBtn3 = new ComplexButton();
mainBtn3.setName("個人中心");
mainBtn3.setSub_button(new CommonButton[] { btn31, btn32});
/**
* 這是公眾號xiaoqrobot目前的選單結構,每個一級選單都有二級選單項<br>
*
* 在某個一級選單下沒有二級選單的情況,menu該如何定義呢?<br>
* 比如,第三個一級選單項不是“更多體驗”,而直接是“幽默笑話”,那麼menu應該這樣定義:<br>
* menu.setButton(new Button[] { mainBtn1, mainBtn2, btn33 });
*/
Menu menu = new Menu();
menu.setButton(new Button[] { mainBtn1,mainBtn2,mainBtn3 });
String json = gson.toJson(menu);
System.out.println(json);// 測試輸出
return json;
}
@Test
public void test() {
String menuJson = getMenuJson();
System.out.println(menuJson);
}
}
這裡是使用者介面,具有使用者訂房,餘額支付支付寶沙箱支付
package com.lisonglin.web;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TimerTask;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alipay.api.domain.GoodInfo;
import com.alipay.api.internal.util.codec.Base64;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lisonglin.daomain.HotelLocal;
import com.lisonglin.daomain.RoomLevel;
import com.lisonglin.daomain.Rooms;
import com.lisonglin.service.CustomersService;
import com.lisonglin.service.DatesService;
import com.lisonglin.service.HotelLocalService;
import com.lisonglin.service.LoginService;
import com.lisonglin.service.OrderService;
import com.lisonglin.service.RoomLevelService;
import com.lisonglin.service.RoomsService;
import com.lisonglin.service.UserService;
import com.lisonglin.service.impl.CustomersImpl;
import com.lisonglin.service.impl.DatesImpl;
import com.lisonglin.service.impl.HotelLocalImpl;
import com.lisonglin.service.impl.LoginImpl;
import com.lisonglin.service.impl.OrderImpl;
import com.lisonglin.service.impl.RoomLevelImpl;
import com.lisonglin.service.impl.RoomsImpl;
import com.lisonglin.service.impl.UserImpl;
import com.lisonglin.utils.DataUtil;
import com.lisonglin.utils.GsonUtil;
import com.lisonglin.utils.JdbcUtil;
import com.lisonglin.utils.MessageUtil;
import com.lisonglin.utils.ProxyUtil;
import com.lisonglin.weixin.daomin.AccessToken;
import com.lisonglin.weixin.daomin.Orders;
import com.lisonglin.weixin.daomin.Users;
import com.mysql.fabric.xmlrpc.base.Array;
import net.sf.json.JSONObject;
@WebServlet("/users/*")
public class RoomOrderServlet extends BaseServlet {
private static final long serialVersionUID = 1L;
private static final Random random = new Random();
UserService us = (UserService) ProxyUtil.getProxy(new UserImpl());
static OrderService orderService = (OrderService) ProxyUtil.getProxy(new OrderImpl());
// 根據型別查出不同的房間(房間標題,房間型別,價格,面積,房間標題)
protected void get(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String header = req.getHeader("User-Agent");
String requestPayload = getRequestPayload(req);
RoomsService rService = (RoomsService) ProxyUtil.getProxy(new RoomsImpl());
Map<String, Object> toMaps = GsonUtil.GsonToMaps(requestPayload);
List<Rooms> room = rService.getConditionRoom(toMaps);
System.out.println("room:" + room);
HotelLocalService hotelLocalService = (HotelLocalService) ProxyUtil.getProxy(new HotelLocalImpl());
List<HotelLocal> hotelLocal = hotelLocalService.getHotelLocal();
RoomLevelService roomLevelService = (RoomLevelService) ProxyUtil.getProxy(new RoomLevelImpl());
List<RoomLevel> roomLevels = roomLevelService.getRoomLevels();
System.out.println(roomLevels);
// 微信自動登入
if (header.contains("MicroMessenger")) {
String openid = (String) req.getSession().getAttribute("openid");
if(openid!=null) {
Users u = null;
try {
u = us.getByUserOpenid(openid);
} catch (Exception e) {
}
if(u!=null) {
System.out.println(u);
req.getSession().setAttribute("user", u);
}
}
}
Users user = (Users) req.getSession().getAttribute("user");
System.out.println("user:" + user);
// 根據使用者查詢全部訂單
if (user != null) {
// 查詢全部訂單
List<Orders> orders = orderService.getByUserId(user.getId());
List<String> str = new ArrayList<>();
List<String> imgPathStr = new ArrayList<>();
// 根據訂單查詢入住時間和離店時間
for (Orders order : orders) {
// 查詢房間名
List<String> roomtitle = orderService.getOrderTitle(order.getOrderid());
String rooms = roomtitle.get(0) + "" + roomtitle.get(1);
str.add(rooms);
String imgpath = orderService.getOrderImg(order.getOrderid());
imgPathStr.add(imgpath);
}
req.setAttribute("orders", orders);
req.setAttribute("roomtitle", str);
req.setAttribute("imgpath", imgPathStr);
}
destroys();
// 根據房間是否被訂單查詢,訂單日期來查詢房間資訊
// 對於房間標題不重複的房間資訊轉發
// List<Rooms> noRemoval = getRoomYesOrNoRemoval(room, "不重複");
// 查詢全部房間
req.setAttribute("rooms", room);
req.setAttribute("hotelLocal", hotelLocal);
req.setAttribute("roomLevels", roomLevels);
req.getRequestDispatcher("/user/app.jsp").forward(req, resp);
}
// 根據型別查出不同的房間
protected void accordingGetRoom(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String requestPayload = getRequestPayload(req);
String pyload = requestPayload.substring(0, requestPayload.length() - 1);
RoomsService rService = (RoomsService) ProxyUtil.getProxy(new RoomsImpl());
// 這裡沒有使用的功能
List<Rooms> room = rService.getAllRoom();
List<Rooms> yesRemoval = getRoomYesOrNoRemoval(room, "重複");
List<Rooms> duplicate = getDuplicate(yesRemoval, pyload);
// 將房間資訊轉成JSON傳送給頁面
Gson gson = new Gson();
String jsonResult = gson.toJson(duplicate, new TypeToken<List<Rooms>>() {
}.getType());
// outPut(req, resp, jsonResult.length()!=2?jsonResult:"");
PrintWriter out = resp.getWriter();
out.write(jsonResult.length() != 2 ? jsonResult : "");
out.close();
}
// 獲取瀏覽器提交的引數
private String getRequestPayload(HttpServletRequest req) {
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = req.getReader();) {
char[] buff = new char[1024];
int len = 0;
while ((len = reader.read(buff)) != -1) {
sb.append(buff, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
@SuppressWarnings("unused")
private List<Rooms> getRoomYesOrNoRemoval(List<Rooms> room, String removel) {
List<Rooms> repeatList = new ArrayList<Rooms>();
for (int i = 0; i < room.size(); i++) {
String level = room.get(i).getDescribe().get(0).getLevel().getLevel();
String localcontent = room.get(i).getDescribe().get(0).getLocal().getLocalcontent();
for (int j = room.size() - 1; j > i; j--) {
String level2 = room.get(j).getDescribe().get(0).getLevel().getLevel();
String localcontent2 = room.get(j).getDescribe().get(0).getLocal().getLocalcontent();
if ((level + localcontent).equals(level2 + localcontent2)) {
int id = room.get(i).getDescribe().get(0).getId();
repeatList.add(room.get(j));// 把相同元素加入list(找出相同的)
room.remove(j);// 刪除重複元素
}
}
}
if (removel.equals("不重複")) {
return room;
} else if (removel.equals("重複")) {
return repeatList;
} else {
return new ArrayList<>();
}
}
// 查詢出重複資料
public static List<Rooms> getDuplicate(List<Rooms> room, String requestPayload) {
List<Rooms> listTemp = new ArrayList<Rooms>();
for (int i = 0; i < room.size(); i++) {
String level = room.get(i).getDescribe().get(0).getLevel().getLevel();
String localcontent = room.get(i).getDescribe().get(0).getLocal().getLocalcontent();
if (requestPayload.equals(level + localcontent)) {
listTemp.add(room.get(i));
}
}
return listTemp;
}
// 根據條件查詢
protected void getConditionRooms(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String requestPayload = getRequestPayload(req);
RoomsService rService = (RoomsService) ProxyUtil.getProxy(new RoomsImpl());
Map<String, Object> toMaps = GsonUtil.GsonToMaps(requestPayload);
List<Rooms> conditionRooms = rService.getConditionRoom(toMaps);
if (conditionRooms != null) {
String jsonResult = GsonUtil.listToJsonArray(conditionRooms);
outPut(req, resp, jsonResult.length() > 2 ? jsonResult : "[]");
}
}
// 傳送驗證碼
protected void getCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String email = req.getParameter("email");
String code = random.nextInt(999999) + "";
System.out.println("code:" + code);
try {
DataUtil.sendCode(email, code);
req.getSession().setAttribute("code", code);
req.getSession().setAttribute("email", email);
resp.getWriter().write("ok");
} catch (Exception e) {
e.printStackTrace();
resp.getWriter().write("no");
}
}
/**
* 驗證驗證碼
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void checkCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String code = req.getParameter("code");
if (code != null) {
Object sCode = req.getSession().getAttribute("code");
if (code.equals(sCode + "")) {
resp.getWriter().write("success");
} else {
resp.getWriter().write("error");
}
} else {
resp.getWriter().write("null");
}
}
/**
* 登入
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String email = req.getParameter("email");
String backurl = req.getParameter("backurl");
System.out.println(email+","+backurl);
String sEmail = (String) req.getSession().getAttribute("email");
if (email.equals(sEmail)) {
if (backurl != null && backurl.contains("${param.backurl}")) {
backurl=backurl.replace("${param.backurl}", "users/bindEmail");
System.out.println(getServletContext().getContextPath() + backurl + "?email=" + email);
resp.sendRedirect(getServletContext().getContextPath() + "/"+backurl + "?email=" + email);
return;
}
Users user = us.getByEmail(email);
System.out.println("user:" + user);
if (user == null) {
Users u = new Users();
u.setEmail(email);
us.addEmail(email);
user = us.getByEmail(sEmail);
}
req.getSession().setAttribute("user", user);
if (backurl.length() != 0 && backurl != "") {
resp.sendRedirect(getServletContext().getContextPath() + "/users/get");
} else {
resp.sendRedirect(getServletContext().getContextPath() + backurl + "?email=" + email);
}
resp.getWriter().write("success");
} else {
resp.getWriter().write("error");
}
}
/**
* 註冊
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void addEmail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String email = req.getParameter("email");
Users byEmail = us.getByEmail(email);
if (byEmail == null) {
us.addEmail(email);
resp.getWriter().write("success");
} else {
resp.getWriter().write("no");
}
}
/**
* 餘額充值
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void change(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String amountStr = (String) req.getAttribute("total_amount");
double amount = Double.parseDouble(amountStr);
Users user = (Users) req.getSession().getAttribute("user");
int i = us.change(amount, user);
if (i == 1) {
user.setReserve(user.getReserve() + amount);
System.out.println("充值成功!");
req.getSession().setAttribute("rechargeOrPay", "1");
} else {
// 更新失敗
System.out.println("充值失敗!");
}
resp.sendRedirect(getServletContext().getContextPath() + "/users/get");
}
/**
* 支付(修改訂單狀態)
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void pay(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String args = req.getParameter("args");
String mima = req.getParameter("mima");
String price = req.getParameter("price");
String sNow = req.getParameter("sNow");
System.out.println(args + "," + mima + "," + price + "," + sNow);
String out_trade_no = (String) req.getAttribute("out_trade_no");
Users user = (Users) req.getSession().getAttribute("user");
Object status = orderService.getOrderStatus(sNow);
System.out.println("status:" + status);
if (user != null) {
if ("balance".equals(args)) {
if ("2".equals(status + "")) {
System.out.println(JdbcUtil.prop.getProperty("mima"));
if (JdbcUtil.prop.getProperty("mima").equals(mima)) {
System.out.println("餘額支付");
double balance = us.getBalance();
System.out.println(balance);
if (balance >= Integer.parseInt(price.substring(0,price.length()-1))) {
// 這裡將使用者的session重新裝
us.pay(price, user.getId());
int paid = Orders.ALREADY_PAID;// 已付款
int update