黑馬旅遊網

這幾天作了黑馬旅遊網這個web項目,對web的基礎知識進行了鞏固和實際應用,並解決了幾個項目自己存在的bug。有問題歡迎來交流~javascript

#1 技術選型css

  • Web層
    • Servlet:前端控制器
    • html:視圖
    • Filter:過濾器
    • BeanUtils:數據封裝
    • Jackson:json序列化工具
  • Service層
    • Javamail:java發送郵件工具
    • Redis:nosql內存數據庫
    • Jedis:java的redis客戶端
  • Dao層
    • Mysql:數據庫
    • Druid:數據庫鏈接池
    • JdbcTemplate:jdbc的工具

#2 建立數據庫html

-- 建立數據庫 CREATE DATABASE travel;前端

-- 使用數據庫 USE travel;java

--建立表 複製提供好的sqlweb

表結構ajax

#3 註冊功能redis

##3.1 頁面效果 sql

##3.2 功能分析 數據庫

##3.3 代碼實現 ###3.3.1 前臺代碼實現 ####3.3.1.1 表單校驗 提高用戶體驗,並減輕服務器壓力。

function checkUsername() {
	var username = $("#username").val();
	var reg_username = /^\w{8,20}$/;
	var flag = reg_username.test(username);
	if (flag){
		$("#username").css("border","");
	}else{
		$("#username").css("border","1px solid red");
	}
	return flag;
}
function checkPassword(){
	var password = $("#password").val();
	var reg_password = /^\w{8,20}$/;
	var flag = reg_password.test(password);
	if (flag){
		$("#password").css("border","");
	}else{
		$("#password").css("border","1px solid red");
	}
	return flag;
}
function checkEmail(){
	var email = $("#email").val();
	var reg_email = /^\w+@\w+\.\w+$/;
	var flag = reg_email.test(email);
	if (flag){
		$("#email").css("border","");
	}else{
		$("#email").css("border","1px solid red");
	}
	return flag;
}
function checkName(){
	var name = $("#name").val();
	var flag;
	if (name == null || name == ""){
		$("#name").css("border","1px solid red");
		flag = false;
	}else{
		$("#name").css("border","");
		flag = true;
	}
	return flag;
}
function checkTelephone(){
	var telephone = $("#telephone").val();
	var reg_telephone = /^1[3456789]\d{9}$/;
	var flag = reg_telephone.test(telephone);
	if (flag){
		$("#telephone").css("border","");
	}else{
		$("#telephone").css("border","1px solid red");
	}
	return flag;
}
function checkBirthday(){
	var birthday = $("#birthday").val();
	var flag;
	if (birthday == null || birthday == ""){
		$("#birthday").css("border","1px solid red");
		flag = false;
	}else{
		$("#birthday").css("border","");
		flag = true;
	}
	return flag;
}

$(function () {
	//當表單提交時,調用全部的校驗方法
	$("#registerForm").submit(function () {
		return checkUsername() && checkPassword() && checkEmail() && checkName() && checkTelephone() && checkBirthday();
	});
	//當某個組件失去焦點時,調用對應的校驗方法
	$("#username").blur(checkUsername);
	$("#password").blur(checkPassword);
	$("#email").blur(checkEmail);
	$("#name").blur(checkName);
	$("#telephone").blur(checkTelephone);
	$("#birthday").blur(checkBirthday);
});

####3.3.1.2 異步(ajax)提交表單 在此使用異步提交表單是爲了獲取服務器響應的數據。由於咱們前臺使用的是html做爲視圖層,不可以直接從servlet相關的域對象獲取值,只能經過ajax獲取響應數據,發送數據到服務器,成功的話跳轉到成功界面,錯誤給出提示信息。

$("#registerForm").submit(function () {
	if (checkUsername() && checkPassword() && checkEmail() && checkName() && checkTelephone() && checkBirthday()){
		$.post("registUserServlet",$(this).serialize(),function (data) {
			if (data.flag){
				location.href="register_ok.html";
			}else{
				$("#errorMsg").html(data.errorMsg);
			}
		});
	}
	return false;
});

###3.3.2 後臺代碼實現 ####3.3.2.1 編寫RegistUserServlet

@WebServlet("/registUserServlet")
public class RegistUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //驗證校驗
        String check = request.getParameter("check");
        //從sesion中獲取驗證碼
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");//爲了保證驗證碼只能使用一次
        //比較
        if(checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)){
            //驗證碼錯誤
            ResultInfo info = new ResultInfo();
            //註冊失敗
            info.setFlag(false);
            info.setErrorMsg("驗證碼錯誤");
            //將info對象序列化爲json
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(info);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return;
        }
        //1.獲取數據
        Map<String, String[]> map = request.getParameterMap();
        //2.封裝對象
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //3.調用service完成註冊
        UserService service = new UserServiceImpl();
        boolean flag = service.regist(user);
        ResultInfo info = new ResultInfo();
        //4.響應結果
        if(flag){
            //註冊成功
            info.setFlag(true);
        }else{
            //註冊失敗
            info.setFlag(false);
            info.setErrorMsg("註冊失敗!");
        }
        //將info對象序列化爲json
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(info);
        //將json數據寫回客戶端
        //設置content-type
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

####3.3.2.2 編寫UserService以及UserServiceImpl

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();
    /**
     * 註冊用戶
     * @param user
     * @return
     */
    @Override
    public boolean regist(User user) {
        //1.根據用戶名查詢用戶對象
        User u = userDao.findByUsername(user.getUsername());
        //判斷u是否爲null
        if(u != null){
            //用戶名存在,註冊失敗
            return false;
        }
        //2.保存用戶信息
        userDao.save(user);
        return true;
    }
}

####3.3.2.3 編寫UserDao以及UserDaoImpl

public class UserDaoImpl implements UserDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public User findByUsername(String username) {
        User user = null;
        try {
            //1.定義sql
            String sql = "select * from tab_user where username = ?";
            //2.執行sql
            user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username);
        } catch (Exception e) {

        }
        return user;
    }

    @Override
    public void save(User user) {
        //1.定義sql
        String sql = "insert into tab_user(username,password,name,birthday,sex,telephone,email,status,code) values(?,?,?,?,?,?,?,?,?)";
        //2.執行sql
        template.update(sql,user.getUsername(),
                user.getPassword(),
                user.getName(),
                user.getBirthday(),
                user.getSex(),
                user.getTelephone(),
                user.getEmail(),
                user.getStatus(),
                user.getCode()
        );
    }
}

3.3.3 郵件激活

爲何要進行郵件激活?爲了保證用戶填寫的郵箱是正確的。未來能夠推廣一些宣傳信息,到用戶郵箱中。

3.3.4 發送郵件

  1. 申請郵箱
  2. 開啓受權碼
  3. 在MailUtils中設置本身的郵箱帳號和密碼(受權碼)

郵件工具類:MailUtils,調用其中sendMail方法能夠完成郵件發送

3.3.5 用戶點擊郵件激活

通過分析發現,用戶激活其實就是修改用戶表中的status爲‘Y’。

分析:

發送郵件代碼:

@Override
    public boolean regist(User user) {
        //1.根據用戶名查詢用戶對象
        User u = userDao.findByUsername(user.getUsername());
        if (u != null){
            return false;
        }
        //2.保存用戶信息
        //2.1設置激活碼,惟一字符串
        user.setCode(UuidUtil.getUuid());
        //2.2設置激活狀態
        user.setStatus("N");
        userDao.save(user);
        //3.激活郵件發送,郵件正文
        String content = "<a href='http://localhost/travel/activeUserServlet?code="+user.getCode()+"'>點擊激活【黑馬旅遊網】</a>";
        MailUtils.sendMail(user.getEmail(),content,"激活郵件");
        return true;
    }

修改保存Dao代碼,加上存儲status和code的代碼邏輯。

激活代碼實現:

ActiveUserServlet主要邏輯:

String code = request.getParameter("code");
if (code != null){
    UserService service = new UserServiceImpl();
    boolean flag = service.active(code);
    String msg = null;
    if (flag){
        msg = "激活成功,請<a href='login.html'>登錄</a>";
    }else{
        msg = "激活失敗,請聯繫管理員";
    }
    response.setContentType("text/html;charset=utf-8");
    response.getWriter().write(msg);

UserService:active

@Override
public boolean active(String code) {
    //1.根據激活碼查詢用戶對象
    User user = userDao.findByCode(code);
    if (user != null){
        //2.調用dao的修改激活狀態方法
        userDao.updateStatus(user);
        return true;
    }else{
        return false;
    }
}

UserDao:findByCode updateStatus

@Override
public User findByCode(String code) {
    User user = null;
    try {
        String sql = "select * from tab_user where code = ?";
        user = template.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),code);
    } catch (DataAccessException e) {
        e.printStackTrace();
    }
    return user;
}
@Override
public void updateStatus(User user) {
    String sql = "update tab_user set status = 'Y' where uid = ?";
    template.update(sql,user.getUid());
}

#4 登錄功能

4.1 分析

4.2 代碼實現

4.2.1 前臺代碼

$(function(){
	//1.給登陸按鈕綁定單擊時間
	$("#btn_sub").click(function () {
		//2.發送ajax請求,提交表單數據
		$.post("loginServlet",$("#loginForm").serialize(),function (data) {
			//data:{flag:false,errorMsg:''}
			if (data.flag){
				location.href="index.html";
			}else{
				$("#errorMsg").html(data.errorMsg);
			}
		});
	});
});

4.2.2 後臺代碼

LoginServlet

Map<String, String[]> map = request.getParameterMap();
    //2.封裝User對象
    User user = new User();
    try {
        BeanUtils.populate(user,map);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    //3.調用Service查詢
    UserService service = new UserServiceImpl();
    User u = service.login(user);
    ResultInfo info = new ResultInfo();
    //4.判斷用戶對象是否爲null
    if (u == null){
        info.setFlag(false);
        info.setErrorMsg("用戶名或密碼錯誤!");
    }
    //5.判斷用戶是否激活
    if (u != null && !"Y".equals(u.getStatus())){
        info.setFlag(false);
        info.setErrorMsg("您還沒有激活,請激活");
    }
    //6.判斷登錄成功
    if (u != null && "Y".equals(u.getStatus())){
        info.setFlag(true);
        request.getSession().setAttribute("user",u);//登陸成功標記
    }
    //響應數據
    ObjectMapper mapper = new ObjectMapper();
    response.setContentType("application/json;charset=utf-8");
    mapper.writeValue(response.getOutputStream(),info);

UserService

public User login(User user) {
    return userDao.findByUsernameAndPassword(user.getUsername(),user.getPassword());
}

}

UserDao

public User findByUsernameAndPassword(String username, String password) {
    User user = null;
    try {
        //1.定義sql
        String sql = "select * from tab_user where username = ? and password = ? ";
        //2.執行sql
        user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username,password);
    } catch (Exception e) {

    }
    return user;
}

4.2.3 index頁面中用戶姓名的提示信息功能

效果:

header.html代碼

$(function () {
    $.get("findUserServlet",{},function (data) {
        //{uid:1,name:'平醬'}
        var msg = "歡迎回來,"+data.name;
        $("#span_username").html(msg);
    });
});

Servlet代碼

//從session中獲取登陸用戶
Object user = request.getSession().getAttribute("user");
//將user寫回客戶端

ObjectMapper mapper = new ObjectMapper();
response.setContentType("application/json;charset=utf-8");
mapper.writeValue(response.getOutputStream(),user);

5 退出功能

什麼叫作登陸了?session中有user對象。

實現步驟:

  1. 訪問servlet,將session銷燬
  2. 跳轉到登陸頁面

代碼實現:

退出標籤添加屬性href="javascript:location.href='exitServlet';"

Servlet

//1.銷燬session
request.getSession().invalidate();

//2.跳轉登陸頁面
response.sendRedirect(request.getContextPath()+"/login.html");

6 優化Servlet

6.1 目的

減小Servlet的數量,如今是一個功能一個Servlet,將其優化爲一個模塊一個Servlet,至關於在數據庫中一張表對應一個Servlet,在Servlet中提供不一樣的方法,完成用戶的請求。

6.2 BaseServlet編寫

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //完成方法分發
        //1.獲取請求路徑
        String uri = req.getRequestURI(); //   /travel/user/add
        //2.獲取方法名稱
        String methodName = uri.substring(uri.lastIndexOf('/') + 1);
        System.out.println("方法名稱:"+methodName);
        //3.獲取方法對象Method
        //誰調用我?我表明誰
        System.out.println(this);//UserServlet的對象cn.itcast.travel.web.servlet.UserServlet@4903d97e
        try {
            //獲取方法
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //4.執行方法
            //暴力反射
            //method.setAccessible(true);
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

6.3 UserServlet改寫

將以前的Servlet實現的功能,抽取到UserServlet中的不一樣方法中實現,而且將UserService建立抽取到成員變量位置。

@WebServlet("/user/*") // /user/add /user/find
public class UserServlet extends BaseServlet {
    //聲明UserService業務對象
    private UserService service = new UserServiceImpl();

    /**
     * 註冊功能
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //驗證校驗
        String check = request.getParameter("check");
        //從sesion中獲取驗證碼
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");//爲了保證驗證碼只能使用一次
        //比較
        if(checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)){
            //驗證碼錯誤
            ResultInfo info = new ResultInfo();
            //註冊失敗
            info.setFlag(false);
            info.setErrorMsg("驗證碼錯誤");
            //將info對象序列化爲json
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(info);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return;
        }
        //1.獲取數據
        Map<String, String[]> map = request.getParameterMap();
        //2.封裝對象
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //3.調用service完成註冊
        //UserService service = new UserServiceImpl();
        boolean flag = service.regist(user);
        ResultInfo info = new ResultInfo();
        //4.響應結果
        if(flag){
            //註冊成功
            info.setFlag(true);
        }else{
            //註冊失敗
            info.setFlag(false);
            info.setErrorMsg("註冊失敗!");
        }
        //將info對象序列化爲json
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(info);
        //將json數據寫回客戶端
        //設置content-type
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }

    /**
     * 登陸功能
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.獲取用戶名和密碼數據
        Map<String, String[]> map = request.getParameterMap();
        //2.封裝User對象
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //3.調用Service查詢
       // UserService service = new UserServiceImpl();
        User u  = service.login(user);
        ResultInfo info = new ResultInfo();
        //4.判斷用戶對象是否爲null
        if(u == null){
            //用戶名密碼或錯誤
            info.setFlag(false);
            info.setErrorMsg("用戶名密碼或錯誤");
        }
        //5.判斷用戶是否激活
        if(u != null && !"Y".equals(u.getStatus())){
            //用戶還沒有激活
            info.setFlag(false);
            info.setErrorMsg("您還沒有激活,請激活");
        }
        //6.判斷登陸成功
        if(u != null && "Y".equals(u.getStatus())){
            request.getSession().setAttribute("user",u);//登陸成功標記
            //登陸成功
            info.setFlag(true);
        }
        //響應數據
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        mapper.writeValue(response.getOutputStream(),info);
    }

    /**
     * 查詢單個對象
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void findOne(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //從session中獲取登陸用戶
        Object user = request.getSession().getAttribute("user");
        //將user寫回客戶端

        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        mapper.writeValue(response.getOutputStream(),user);
    }

    /**
     * 退出功能
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.銷燬session
        request.getSession().invalidate();
        //2.跳轉登陸頁面
        response.sendRedirect(request.getContextPath()+"/login.html");
    }

    /**
     * 激活功能
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.獲取激活碼
        String code = request.getParameter("code");
        if(code != null){
            //2.調用service完成激活
            //UserService service = new UserServiceImpl();
            boolean flag = service.active(code);
            //3.判斷標記
            String msg = null;
            if(flag){
                //激活成功
                msg = "激活成功,請<a href='login.html'>登陸</a>";
            }else{
                //激活失敗
                msg = "激活失敗,請聯繫管理員!";
            }
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(msg);
        }
    }
}

6.4 頁面路徑改寫

將register.html、login.html、header.html、UserServiceImpl中的Servlet路徑修改優化後對應的路徑。

如: registServlet -> user/regist

7 分類數據展現

7.1 效果

從數據庫讀取真正的分類信息展現在頁面上

7.2 分析

7.3 代碼實現

7.3.1 後臺代碼

由於序列化json的操做常常須要使用,因此在BaseServlet中封裝了序列化json的方法便於複用。

/**
 * 直接將傳入的對象序列化爲json,而且寫回客戶端
 * @param obj
 */
public void writeValue(Object obj,HttpServletResponse response) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    response.setContentType("application/json;charset=utf-8");
    mapper.writeValue(response.getOutputStream(),obj);
}

/**
 * 將傳入的對象序列化爲json,返回
 * @param obj
 * @return
 */
public String writeValueAsString(Object obj) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(obj);
}

CategoryServlet

@WebServlet("/category/*")
public class CategoryServlet extends BaseServlet {
    private CategoryService service = new CategoryServiceImpl();

    /**
     * 查詢全部
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.調用service查詢全部
        List<Category> cs = service.findAll();
        //2.序列化json返回
       /* ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        mapper.writeValue(response.getOutputStream(),cs);*/
       writeValue(cs,response);
    }
}

CategoryService

public class CategoryServiceImpl implements CategoryService {
    private CategoryDao categoryDao = new CategoryDaoImpl();
    @Override
    public List<Category> findAll() {
        return categoryDao.findAll();
    }
}

CategoryDao

public class CategoryDaoImpl implements CategoryDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public List<Category> findAll() {
        String sql = "select * from tab_category ";
        return template.query(sql,new BeanPropertyRowMapper<Category>(Category.class));
    }
}

7.3.2 前臺代碼

hader.html加載後,發送ajax請求,請求category/findAll

//查詢分類數據
 $.get("category/findAll",{},function (data) {
     //[{cid:1,cname:國內遊},{},{}]
     var lis = '<li class="nav-active"><a href="index.html">首頁</a></li>';
     //遍歷數組,拼接字符串(<li>)
     for (var i = 0; i < data.length; i++) {
         var li = '<li><a href="route_list.html">'+data[i].cname+'</a></li>';
         lis += li;
     }
     //拼接收藏排行榜的li,<li><a href="favoriterank.html">收藏排行榜</a></li>
     lis+= '<li><a href="favoriterank.html">收藏排行榜</a></li>';
     //將lis字符串,設置到ul的html內容中
     $("#category").html(lis);
 });

7.4 對分類數據進行緩存優化

分析發現,分類的數據在每一次頁面加載後都會從新請求數據庫來加載對數據庫的壓力比較大,並且分類的數據不會常常產生變化,全部可使用redis來緩存這個數據。

分析:

7.5 優化代碼實現

指望數據中存儲的順序就是未來展現的順序,使用redis的sortedset。

@Override
public List<Category> findAll() {
    //1.從redis中查詢
    //1.1獲取jedis客戶端
    Jedis jedis = JedisUtil.getJedis();
    //1.2可以使用sortedset排序查詢
    Set<String> categorys = jedis.zrange("category", 0, -1);
    List<Category> cs = null;
    //2.判斷查詢的集合是否爲空
    if (categorys == null || categorys.size() == 0) {
        System.out.println("從數據庫查詢....");
        //3.若是爲空,須要從數據庫查詢,在將數據存入redis
        //3.1 從數據庫查詢
        cs = categoryDao.findAll();
        //3.2 將集合數據存儲到redis中的 category的key
        for (int i = 0; i < cs.size(); i++) {
            jedis.zadd("category", cs.get(i).getCid(), cs.get(i).getCname());
        }
    } else {
        System.out.println("從redis中查詢.....");
        //4.若是不爲空,將set的數據存入list
        cs = new ArrayList<Category>();
        for (String name : categorys) {
            Category category = new Category();
            category.setCname(name);
            cs.add(category);
        }
    }
    return cs;
}

8 旅遊線路的分頁展現

點擊了不一樣的分類後,未來看到的旅遊線路不同的。經過分析數據庫表結構,發現旅遊線路表和分類表時一個多對一的關係。

查詢不一樣分類的旅遊線路sql

Select * from tab_route where cid = ?;

8.1 類別id的傳遞

Redis中查詢score(cid)

public class CategoryServiceImpl implements CategoryService {
    private CategoryDao categoryDao = new CategoryDaoImpl();
    @Override
    public List<Category> findAll() {
        //1.從redis中查詢
        //1.1獲取jedis客戶端
        Jedis jedis = JedisUtil.getJedis();
        //1.2可以使用sortedset排序查詢
        //Set<String> categorys = jedis.zrange("category", 0, -1);
        //1.3查詢sortedset中的分數(cid)和值(cname)
        Set<Tuple> categorys = jedis.zrangeWithScores("category", 0, -1);
        List<Category> cs = null;
        //2.判斷查詢的集合是否爲空
        if (categorys == null || categorys.size() == 0) {

            System.out.println("從數據庫查詢....");
            //3.若是爲空,須要從數據庫查詢,在將數據存入redis
            //3.1 從數據庫查詢
            cs = categoryDao.findAll();
            //3.2 將集合數據存儲到redis中的 category的key
            for (int i = 0; i < cs.size(); i++) {

                jedis.zadd("category", cs.get(i).getCid(), cs.get(i).getCname());
            }
        } else {
            System.out.println("從redis中查詢.....");

            //4.若是不爲空,將set的數據存入list
            cs = new ArrayList<Category>();
            for (Tuple tuple : categorys) {
                Category category = new Category();
                category.setCname(tuple.getElement());
                category.setCid((int)tuple.getScore());
                cs.add(category);

            }
        }
        return cs;
    }
}

頁面傳遞cid

header.html傳遞cid

var li = '<li><a href="route_list.html?cid='+data[i].cid+'">'+data[i].cname+'</a></li>';

獲取cid

$(function () {
   var search = location.search;
   //alert(search);//?id=5
    // 切割字符串,拿到第二個值
    var cid = search.split("=")[1];
});

8.2 根據id查詢不一樣類別的旅遊線路數據

分頁展現旅遊線路數據

8.2.1 分析

8.2.2 編碼

1.客戶端代碼編寫

$(function () {
    var search = location.search;
        // 切割字符串,拿到第二個值
    var cid = search.split("=")[1];
    //當頁碼加載完成後,調用load方法,發送ajax請求加載數據
    load(cid);
});
function load(cid ,currentPage){
    //發送ajax請求,請求route/pageQuery,傳遞cid
    $.get("route/pageQuery",{cid:cid,currentPage:currentPage},function (pb) {
        //解析pagebean數據,展現到頁面上

        //1.分頁工具條數據展現
        //1.1 展現總頁碼和總記錄數
        $("#totalPage").html(pb.totalPage);
        $("#totalCount").html(pb.totalCount);

        var lis = "";

        var fristPage = '<li onclick="javascipt:load('+cid+')"><a href="javascript:void(0)">首頁</a></li>';

        //計算上一頁的頁碼
        var beforeNum =  pb.currentPage - 1;
        if(beforeNum <= 0){
            beforeNum = 1;
        }

        var beforePage = '<li  onclick="javascipt:load('+cid+','+beforeNum+')" class="threeword"><a href="javascript:void(0)">上一頁</a></li>';

        lis += fristPage;
        lis += beforePage;
        //1.2 展現分頁頁碼
        /*
            1.一共展現10個頁碼,可以達到前5後4的效果
            2.若是前邊不夠5個,後邊補齊10個
            3.若是後邊不足4個,前邊補齊10個
        */

        // 定義開始位置begin,結束位置 end
        var begin; // 開始位置
        var end ; //  結束位置

        //1.要顯示10個頁碼
        if(pb.totalPage < 10){
            //總頁碼不夠10頁
            begin = 1;
            end = pb.totalPage;
        }else{
            //總頁碼超過10頁
            begin = pb.currentPage - 5 ;
            end = pb.currentPage + 4 ;

            //2.若是前邊不夠5個,後邊補齊10個
            if(begin < 1){
                begin = 1;
                end = begin + 9;
            }

            //3.若是後邊不足4個,前邊補齊10個
            if(end > pb.totalPage){
                end = pb.totalPage;
                begin = end - 9 ;
            }
        }

        for (var i = begin; i <= end ; i++) {
            var li;
            //判斷當前頁碼是否等於i
            if(pb.currentPage == i){
                li = '<li class="curPage" onclick="javascipt:load('+cid+','+i+')"><a href="javascript:void(0)">'+i+'</a></li>';
            }else{
                //建立頁碼的li
                li = '<li onclick="javascipt:load('+cid+','+i+')"><a href="javascript:void(0)">'+i+'</a></li>';
            }
            //拼接字符串
            lis += li;
        }

		var lastPage = '<li onclick="javascipt:load('+cid+','+pb.totalPage+')" class="threeword"><a href="javascript:void(0);">末頁</a></li>';
        var nextNum = pb.currentPage + 1;
            if (nextNum >= pb.totalPage){
                nextNum = pb.totalPage;
            }
        var nextPage = '<li onclick="javascipt:load('+cid+','+nextNum+')" class="threeword"><a href="javascript:void(0);">下一頁</a></li>';

        lis += nextPage;
        lis += lastPage;


        //將lis內容設置到 ul
        $("#pageNum").html(lis);
        
        //2.列表數據展現
        var route_lis = "";

        for (var i = 0; i < pb.list.length; i++) {
            //獲取{rid:1,rname:"xxx"}
            var route = pb.list[i];

            var li = '<li>\n' +
                '                        <div class="img"><img src="'+route.rimage+'" style="width: 299px;"></div>\n' +
                '                        <div class="text1">\n' +
                '                            <p>'+route.rname+'</p>\n' +
                '                            <br/>\n' +
                '                            <p>'+route.routeIntroduce+'</p>\n' +
                '                        </div>\n' +
                '                        <div class="price">\n' +
                '                            <p class="price_num">\n' +
                '                                <span>&yen;</span>\n' +
                '                                <span>'+route.price+'</span>\n' +
                '                                <span>起</span>\n' +
                '                            </p>\n' +
                '                            <p><a href="route_detail.html">查看詳情</a></p>\n' +
                '                        </div>\n' +
                '                    </li>';
            route_lis += li;
        }
        $("#route").html(route_lis);
        //定位到頁面頂部
        window.scrollTo(0,0);
    });
}

2.服務器端代碼編寫

a) 建立PageBean對象

public class PageBean<T> {

    private int totalCount;//總記錄數
    private int totalPage;//總頁數
    private int currentPage;//當前頁碼
    private int pageSize;//每頁顯示的條數

    private List<T> list;//每頁顯示的數據集合
	//getter and setter...省略
}

b) RouteServlet

@WebServlet("/route/*")
public class RouteServlet extends BaseServlet {
    private RouteService routeService = new RouteServiceImpl();

    /**
     * 分頁查詢
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void pageQuery(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接受參數
        String currentPageStr = request.getParameter("currentPage");
        String pageSizeStr = request.getParameter("pageSize");
        String cidStr = request.getParameter("cid");

        int cid = 0;//類別id
        //2.處理參數
        if(cidStr != null && cidStr.length() > 0){
            cid = Integer.parseInt(cidStr);
        }
        int currentPage = 0;//當前頁碼,若是不傳遞,則默認爲第一頁
        if(currentPageStr != null && currentPageStr.length() > 0){
            currentPage = Integer.parseInt(currentPageStr);
        }else{
            currentPage = 1;
        }

        int pageSize = 0;//每頁顯示條數,若是不傳遞,默認每頁顯示5條記錄
        if(pageSizeStr != null && pageSizeStr.length() > 0){
            pageSize = Integer.parseInt(pageSizeStr);
        }else{
            pageSize = 5;
        }

        //3. 調用service查詢PageBean對象
        PageBean<Route> pb = routeService.pageQuery(cid, currentPage, pageSize);

        //4. 將pageBean對象序列化爲json,返回
        writeValue(pb,response);
    }
}

c) RouteService

public class RouteServiceImpl implements RouteService {
    private RouteDao routeDao = new RouteDaoImpl();
    @Override
    public PageBean<Route> pageQuery(int cid, int currentPage, int pageSize) {
        //封裝PageBean
        PageBean<Route> pb = new PageBean<Route>();
        //設置當前頁碼
        pb.setCurrentPage(currentPage);
        //設置每頁顯示條數
        pb.setPageSize(pageSize);
        
        //設置總記錄數
        int totalCount = routeDao.findTotalCount(cid);
        pb.setTotalCount(totalCount);
        //設置當前頁顯示的數據集合
        int start = (currentPage - 1) * pageSize;//開始的記錄數
        List<Route> list = routeDao.findByPage(cid,start,pageSize);
        pb.setList(list);

        //設置總頁數 = 總記錄數/每頁顯示條數
        int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize :(totalCount / pageSize) + 1 ;
        pb.setTotalPage(totalPage);
        return pb;
    }
}

d) RouteDao

public class RouteDaoImpl implements RouteDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public int findTotalCount(int cid) {
        String sql = "select count(*) from tab_route where cid = ?";
        return template.queryForObject(sql,Integer.class,cid);
    }

    @Override
    public List<Route> findByPage(int cid, int start, int pageSize) {
        String sql = "select * from tab_route where cid = ? limit ? , ?";
        return template.query(sql,new BeanPropertyRowMapper<Route>(Route.class),cid,start,pageSize);
    }
}

9 旅遊線路名稱查詢

9.1 查詢參數的傳遞

在header.html中

$("#search-button").click(function () {
    //線路名稱
    var rname = $("#search_input").val();
    var cid = getParameter("cid");
    // 跳轉路徑 http://localhost/travel/route_list.html?cid=5,拼接上rname=xxx
    location.href="http://localhost/travel/route_list.html?cid="+cid+"&rname="+rname;
});

在route_list.html

var cid = getParameter("cid");
//獲取rname的參數值
var rname = getParameter("rname");
//判斷rname若是不爲null或者""
if(rname){
    //url解碼
    rname = window.decodeURIComponent(rname);
}else{
	rname = "";	//沒有搜索時
}

9.2 修改後臺代碼

Servlet

@WebServlet("/route/*")
public class RouteServlet extends BaseServlet {
    private RouteService routeService = new RouteServiceImpl();

    /**
     * 分頁查詢
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void pageQuery(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接受參數
        String currentPageStr = request.getParameter("currentPage");
        String pageSizeStr = request.getParameter("pageSize");
        String cidStr = request.getParameter("cid");

        //接受rname 線路名稱
        String rname = request.getParameter("rname");
        rname = new String(rname.getBytes("iso-8859-1"),"utf-8");


        int cid = 0;//類別id
        //2.處理參數
        if(cidStr != null && cidStr.length() > 0){
            cid = Integer.parseInt(cidStr);
        }
        int currentPage = 0;//當前頁碼,若是不傳遞,則默認爲第一頁
        if(currentPageStr != null && currentPageStr.length() > 0){
            currentPage = Integer.parseInt(currentPageStr);
        }else{
            currentPage = 1;
        }

        int pageSize = 0;//每頁顯示條數,若是不傳遞,默認每頁顯示5條記錄
        if(pageSizeStr != null && pageSizeStr.length() > 0){
            pageSize = Integer.parseInt(pageSizeStr);
        }else{
            pageSize = 5;
        }
        //3. 調用service查詢PageBean對象
        PageBean<Route> pb = routeService.pageQuery(cid, currentPage, pageSize,rname);
        //4. 將pageBean對象序列化爲json,返回
        writeValue(pb,response);
    }
}

Service

public PageBean<Route> pageQuery(int cid, int currentPage, int pageSize,String rname ) {
    //封裝PageBean
    PageBean<Route> pb = new PageBean<Route>();
    //設置當前頁碼
    pb.setCurrentPage(currentPage);
    //設置每頁顯示條數
    pb.setPageSize(pageSize);
    
    //設置總記錄數
    int totalCount = routeDao.findTotalCount(cid,rname);
    pb.setTotalCount(totalCount);
    //設置當前頁顯示的數據集合
    int start = (currentPage - 1) * pageSize;//開始的記錄數
    List<Route> list = routeDao.findByPage(cid,start,pageSize,rname);
    pb.setList(list);

    //設置總頁數 = 總記錄數/每頁顯示條數
    int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize :(totalCount / pageSize) + 1 ;
    pb.setTotalPage(totalPage);
    return pb;
}

Dao

@Override
public int findTotalCount(int cid,String rname) {
    //String sql = "select count(*) from tab_route where cid = ?";
    //1.定義sql模板
    String sql = "select count(*) from tab_route where 1=1 ";
    StringBuilder sb = new StringBuilder(sql);

    List params = new ArrayList();//條件們
    //2.判斷參數是否有值
    if(cid != 0){
        sb.append( " and cid = ? ");

        params.add(cid);//添加?對應的值
    }

    if(rname != null && rname.length() > 0){
        sb.append(" and rname like ? ");

        params.add("%"+rname+"%");
    }

    sql = sb.toString();

    return template.queryForObject(sql,Integer.class,params.toArray());
}

@Override
public List<Route> findByPage(int cid, int start, int pageSize,String rname) {
    //String sql = "select * from tab_route where cid = ? and rname like ?  limit ? , ?";
    String sql = " select * from tab_route where 1 = 1 ";
    //1.定義sql模板
    StringBuilder sb = new StringBuilder(sql);

    List params = new ArrayList();//條件們
    //2.判斷參數是否有值
    if(cid != 0){
        sb.append( " and cid = ? ");

        params.add(cid);//添加?對應的值
    }
    if(rname != null && rname.length() > 0){
        sb.append(" and rname like ? ");

        params.add("%"+rname+"%");
    }
    sb.append(" limit ? , ? ");//分頁條件
    sql = sb.toString();
    params.add(start);
    params.add(pageSize);
    return template.query(sql,new BeanPropertyRowMapper<Route>(Route.class),params.toArray());
}

9.4 修改前臺代碼

$(function () {
   //獲取cid的參數值
   var cid = getParameter("cid");
    //獲取rname的參數值
    var rname = getParameter("rname");
    //判斷rname若是不爲null或者""
    if(rname){
        //url解碼
        rname = window.decodeURIComponent(rname);
    }else{
		rname = 「」;
	}

    //當頁碼加載完成後,調用load方法,發送ajax請求加載數據
    load(cid,null,rname);
});

function load(cid ,currentPage,rname){
    //發送ajax請求,請求route/pageQuery,傳遞cid
    $.get("route/pageQuery",{cid:cid,currentPage:currentPage,rname:rname},function (pb) {
        //解析pagebean數據,展現到頁面上

        //1.分頁工具條數據展現
        //1.1 展現總頁碼和總記錄數
        $("#totalPage").html(pb.totalPage);
        $("#totalCount").html(pb.totalCount);

        var lis = "";

        var fristPage = '<li onclick="javascipt:load('+cid+',1,\''+rname+'\')"><a href="javascript:void(0)">首頁</a></li>';

        //計算上一頁的頁碼
        var beforeNum =  pb.currentPage - 1;
        if(beforeNum <= 0){
            beforeNum = 1;
        }

        var beforePage = '<li  onclick="javascipt:load('+cid+','+beforeNum+',\''+rname+'\')" class="threeword"><a href="javascript:void(0)">上一頁</a></li>';

        lis += fristPage;
        lis += beforePage;
        //1.2 展現分頁頁碼
        /*
            1.一共展現10個頁碼,可以達到前5後4的效果
            2.若是前邊不夠5個,後邊補齊10個
            3.若是後邊不足4個,前邊補齊10個
        */

        // 定義開始位置begin,結束位置 end
        var begin; // 開始位置
        var end ; //  結束位置


        //1.要顯示10個頁碼
        if(pb.totalPage < 10){
            //總頁碼不夠10頁
            begin = 1;
            end = pb.totalPage;
        }else{
            //總頁碼超過10頁
            begin = pb.currentPage - 5 ;
            end = pb.currentPage + 4 ;

            //2.若是前邊不夠5個,後邊補齊10個
            if(begin < 1){
                begin = 1;
                end = begin + 9;
            }

            //3.若是後邊不足4個,前邊補齊10個
            if(end > pb.totalPage){
                end = pb.totalPage;
                begin = end - 9 ;
            }
        }

        for (var i = begin; i <= end ; i++) {
            var li;
            //判斷當前頁碼是否等於i
            if(pb.currentPage == i){
                li = '<li class="curPage" onclick="javascipt:load('+cid+','+i+',\''+rname+'\')"><a href="javascript:void(0)">'+i+'</a></li>';
            }else{
                //建立頁碼的li
                li = '<li onclick="javascipt:load('+cid+','+i+',\''+rname+'\')"><a href="javascript:void(0)">'+i+'</a></li>';
            }
            //拼接字符串
            lis += li;
        }
	
        var lastPage = '<li onclick="javascipt:load('+cid+','+pb.totalPage+',\''+rname+'\')" class="threeword"><a href="javascript:void(0)">末頁</a></li>';
        var nextNum = pb.currentPage + 1;
        if (nextNum >= pb.totalPage){
            nextNum = pb.totalPage;
        }
        var nextPage = '<li onclick="javascipt:load('+cid+','+nextNum+',\''+rname+'\')" class="threeword"><a href="javascript:void(0)">下一頁</a></li>';
        lis += nextPage;
        lis += lastPage;

        //將lis內容設置到 ul
        $("#pageNum").html(lis);

        //2.列表數據展現
        var route_lis = "";

        for (var i = 0; i < pb.list.length; i++) {
            //獲取{rid:1,rname:"xxx"}
            var route = pb.list[i];

            var li = '<li>\n' +
                '                        <div class="img"><img src="'+route.rimage+'" style="width: 299px;"></div>\n' +
                '                        <div class="text1">\n' +
                '                            <p>'+route.rname+'</p>\n' +
                '                            <br/>\n' +
                '                            <p>'+route.routeIntroduce+'</p>\n' +
                '                        </div>\n' +
                '                        <div class="price">\n' +
                '                            <p class="price_num">\n' +
                '                                <span>&yen;</span>\n' +
                '                                <span>'+route.price+'</span>\n' +
                '                                <span>起</span>\n' +
                '                            </p>\n' +
                '                            <p><a href="route_detail.html">查看詳情</a></p>\n' +
                '                        </div>\n' +
                '                    </li>';
            route_lis += li;
        }
        $("#route").html(route_lis);

        //定位到頁面頂部
        window.scrollTo(0,0);
    });
}

10 旅遊線路的詳情展現

10.1 分析

10.2 代碼實現

10.2.1 後臺代碼

Servlet

/**
 * 根據id查詢一個旅遊線路的詳細信息
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
public void findOne(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //1.接收id
    String rid = request.getParameter("rid");
    //2.調用service查詢route對象
    Route route = routeService.findOne(rid);
    //3.轉爲json寫回客戶端
    writeValue(route,response);
}

Service

@Override
public Route findOne(String rid) {
    //1.根據id去route表中查詢route對象
    Route route = routeDao.findOne(Integer.parseInt(rid));

    //2.根據route的id 查詢圖片集合信息
    List<RouteImg> routeImgList = routeImgDao.findByRid(route.getRid());
    //2.2將集合設置到route對象
    route.setRouteImgList(routeImgList);
    //3.根據route的sid(商家id)查詢商家對象
    Seller seller = sellerDao.findById(route.getSid());
    route.setSeller(seller);
    return route;
}

SellerDao

public class SellerDaoImpl implements SellerDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public Seller findById(int id) {
        String sql = "select * from tab_seller where sid = ? ";
        return template.queryForObject(sql,new BeanPropertyRowMapper<Seller>(Seller.class),id);
    }
}

RouteDao

@Override
public Route findOne(int rid) {
    String sql = "select * from tab_route where rid = ?";
    return template.queryForObject(sql,new BeanPropertyRowMapper<Route>(Route.class),rid);
}

RouteImgDao

public class RouteImgDaoImpl implements RouteImgDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<RouteImg> findByRid(int rid) {
        String sql = "select * from tab_route_img where rid = ? ";
        return template.query(sql,new BeanPropertyRowMapper<RouteImg>(RouteImg.class),rid);
    }
}

10.2.2 前臺代碼

Route_detail.html中加載後

  1. 獲取rid

  2. 發送ajax請求,獲取route對象

  3. 解析對象的數據

    //1.獲取rid
    var rid = getParameter("rid");
    //2.發送請求請求 route/findOne
     $.get("route/findOne",{rid:rid},function (route) {
         //3.解析數據填充html
         $("#rname").html(route.rname);
         $("#routeIntroduce").html(route.routeIntroduce);
         $("#price").html("¥"+route.price);
         $("#sname").html(route.seller.sname);
         $("#consphone").html(route.seller.consphone);
         $("#address").html(route.seller.address);
    
         //圖片展現
         var ddstr = '<a class="up_img up_img_disable"></a>';
    
         //遍歷routeImgList
         for (var i = 0; i < route.routeImgList.length; i++) {
             var astr ;
             if(i >= 4){
                 astr = '<a title="" class="little_img" data-bigpic="'+route.routeImgList[i].bigPic+'" style="display:none;">\n' +
                     '                        <img src="'+route.routeImgList[i].smallPic+'">\n' +
                     '                    </a>';
             }else{
                 astr = '<a title="" class="little_img" data-bigpic="'+route.routeImgList[i].bigPic+'">\n' +
                     '                        <img src="'+route.routeImgList[i].smallPic+'">\n' +
                     '                    </a>';
             }
             ddstr += astr;
         }
         ddstr+='<a class="down_img down_img_disable" style="margin-bottom: 0;"></a>';
    
         $("#dd").html(ddstr);
         //圖片展現和切換代碼調用
         goImg();
     });

11 旅遊線路收藏功能

11.1 分析

判斷當前登陸用戶是否收藏過該線路

當頁面加載完成後,發送ajax請求,獲取用戶是否收藏的標記。

根據標記,展現不一樣的按鈕樣式

11.2 編寫代碼

11.2.1 後臺代碼

RouteServlet

public void isFavorite(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //1. 獲取線路id
    String rid = request.getParameter("rid");
    //2. 獲取當前登陸的用戶 user
    User user = (User) request.getSession().getAttribute("user");
    int uid;//用戶id
    if(user == null){
        //用戶還沒有登陸
        uid = 0;
    }else{
        //用戶已經登陸
        uid = user.getUid();
    }
    //3. 調用FavoriteService查詢是否收藏
    boolean flag = favoriteService.isFavorite(rid, uid);
    //4. 寫回客戶端
    writeValue(flag,response);
}

FavoriteService

@Override
public boolean isFavorite(String rid, int uid) {
    Favorite favorite = favoriteDao.findByRidAndUid(Integer.parseInt(rid), uid);
    retur favorite != null;//若是對象有值,則爲true,反之則爲false
}

FavoriteDao

@Override
public Favorite findByRidAndUid(int rid, int uid) {
    Favorite favorite = null;
    try {
        String sql = " select * from tab_favorite where rid = ? and uid = ?";
        favorite = template.queryForObject(sql, new BeanPropertyRowMapper<Favorite>(Favorite.class), rid, uid);
    } catch (DataAccessException e) {
        e.printStackTrace();
    }
    return favorite;
}

11.2.2 前臺代碼

route_detail.html

$(function () {
   // 發送請求,判斷用戶是否收藏過該線路
    var rid = getParameter("rid");
    $.get("route/isFavorite",{rid:rid},function (flag) {
        if(flag){
            // 用戶已經收藏過
            //<a  class="btn already" disabled="disabled">
            //設置收藏按鈕的樣式
            $("#favorite").addClass("already");
            $("#favorite").prop("disabled",disabled);
        }else{
            // 用戶沒有收藏
        }
    });

11.3 收藏次數的動態展現

前臺:

//設置收藏次數
$("#favoriteCount").html("已收藏"+route.count+"次");

後臺:

RouteService

//查詢收藏次數
int count = favoriteDao.findCountByRid(route.getRid());
route.setCount(count);

FavoriteDao

@Override
public int findCountByRid(int rid) {
    String sql = "SELECT COUNT(*) FROM tab_favorite WHERE rid = ?";
    return template.queryForObject(sql,Integer.class,rid);
}

11.4 點擊按鈕收藏線路

11.4.1 分析

11.4.2 編碼

前臺代碼

$(function () {
   // 發送請求,判斷用戶是否收藏過該線路
    var rid = getParameter("rid");
    $.get("route/isFavorite",{rid:rid},function (flag) {
        if(flag){
            // 用戶已經收藏過
            //<a  class="btn already" disabled="disabled">
            //設置收藏按鈕的樣式
            $("#favorite").addClass("already");
            $("#favorite").attr("disabled","disabled");

            //刪除按鈕的點擊事件
            $("#favorite").removeAttr("onclick");
        }else{
            // 用戶沒有收藏
        }
    });
});

//點擊收藏按鈕觸發的方法
function addFavorite(){
    var rid = getParameter("rid");
    //1. 判斷用戶是否登陸
    $.get("user/findOne",{},function (user) {
       if(user){
           //用戶登陸了
            //添加功能
            $.get("route/addFavorite",{rid:rid},function () {
                //代碼刷新頁面
                location.reload();
            });
       }else{
           //用戶沒有登陸
           alert("您還沒有登陸,請登陸");
           location.href="http://localhost/travel/login.html";
       }
    });
}

後臺代碼

RouteServlet

public void addFavorite(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //1. 獲取線路rid
    String rid = request.getParameter("rid");
    //2. 獲取當前登陸的用戶
    User user = (User) request.getSession().getAttribute("user");
    int uid;//用戶id
    if(user == null){
        //用戶還沒有登陸
        return ;
    }else{
        //用戶已經登陸
        uid = user.getUid();
    }
    //3. 調用service添加
    favoriteService.add(rid,uid);
}

FavoriteService

@Override
public void add(String rid, int uid) {
    favoriteDao.add(Integer.parseInt(rid),uid);
}

FavoriteDao

@Override
public void add(int rid, int uid) {
    String sql = "insert into tab_favorite values(?,?,?)";

    template.update(sql,rid,new Date(),uid);
}

#總結

此案例由於用的是html展現頁面,因此大部分都用ajax異步交互,在後臺處理完數據封裝回json格式再發送到前臺再處理,後臺的代碼邏輯比較簡單,主要是前臺的處理json數據略爲繁瑣。

  • 用maven建立的項目在讀取resources下的配置文件時不須要加/,不然會讀取不到報空指針異常。

  • sql交互時不肯定參數是否存在時,JdbcTemplate能夠用數組模糊傳參。

原文出處:https://www.cnblogs.com/p1ng/p/12455600.html

相關文章
相關標籤/搜索