day-28 商城業務1歷史記錄,返回,validate自定義

  • 歷史記錄可以session,可以cookie也可以redis,,在cookies時候是拼一個字符串記錄所在商品id用符號隔開,然后在返回原來頁面取出來,需要的參數沒有在上級找,再沒有繼續向上
----取出cookie---
protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 獲得cid
        String cid = request.getParameter("cid");
        String currentPageStr = request.getParameter("currentPage");
        if (currentPageStr == null)
            currentPageStr = "1";
        int currentPage = Integer.parseInt(currentPageStr);
        int currentCount = 12;
        ProductService service = new ProductService();
        PageBean pageBean = service.findProductListByCid(cid, currentPage, currentCount);
        request.setAttribute("pageBean", pageBean);
        request.setAttribute("cid", cid);
        // 定義一個記錄歷史商品信息的集合
        List<Product> historyProductList = new ArrayList<Product>();
        // 獲得客戶端攜帶名字叫pids的cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("pids".equals(cookie.getName())) {
                    String pids = cookie.getValue();// 3-2-1
                    String[] split = pids.split("-");
                    for (String pid : split) {
                        Product pro = service.findProductByPid(pid);
                        historyProductList.add(pro);
                    }
                }
            }
        }

        // 將歷史記錄的集合放到域中
        request.setAttribute("historyProductList", historyProductList);
        request.getRequestDispatcher("/product_list.jsp").forward(request, response);
}
-------------在詳情頁放入cookie---------------
// 獲得客戶端攜帶cookie---獲得名字是pids的cookie
        String pids = pid;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("pids".equals(cookie.getName())) {
                    pids = cookie.getValue();
                    // 1-3-2 本次訪問商品pid是8----->8-1-3-2
                    // 1-3-2 本次訪問商品pid是3----->3-1-2
                    // 1-3-2 本次訪問商品pid是2----->2-1-3
                    // 將pids拆成一個數組
                    String[] split = pids.split("-");// {3,1,2}
                    List<String> asList = Arrays.asList(split);// [3,1,2]
                    LinkedList<String> list = new LinkedList<String>(asList);// [3,1,2]
                    // 判斷集合中是否存在當前pid
                    if (list.contains(pid)) {
                        // 包含當前查看商品的pid
                        list.remove(pid);
                        list.addFirst(pid);
                    } else {
                        // 不包含當前查看商品的pid 直接將該pid放到頭上
                        list.addFirst(pid);
                    }
                    // 將[3,1,2]轉成3-1-2字符串
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < list.size() && i < 7; i++) {
                        sb.append(list.get(i));
                        sb.append("-");// 3-1-2-
                    }
                    // 去掉3-1-2-后的-
                    pids = sb.substring(0, sb.length() - 1);
                }   }   }
        Cookie cookie_pids = new Cookie("pids", pids);
        response.addCookie(cookie_pids);
        request.getRequestDispatcher("/product_info.jsp").forward(request, response);
    }
  • 腳本:在jsp中寫<%java代碼%>?;ajax,在script中異步加載數據$.post
  • 動態引入時候在加載時候就將數據返回給頁面其余加載時候便會統一加載到數據(使用ajax加載header中的目錄條)
  • 不經常改變的可以放在緩存,讀取快比如分類
-----------redis工具包---
-----配置
redis.maxIdle=30
redis.minIdle=10
redis.maxTotal=100
redis.url=localhost
redis.port=6379
------
public class JedisPoolUtils {
    private static JedisPool pool = null;
    static {
        // 加載配置文件
        InputStream in = JedisPoolUtils.class.getClassLoader().getResourceAsStream("redis.properties");
        Properties pro = new Properties();
        try {
            pro.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 獲得池子對象
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(Integer.parseInt(pro.get("redis.maxIdle").toString()));// 最大閑置個數
        poolConfig.setMinIdle(Integer.parseInt(pro.get("redis.minIdle").toString()));// 最小閑置個數
    poolConfig.setMaxTotal(Integer.parseInt(pro.get("redis.maxTotal").toString()));// 最大連接數
        pool = new JedisPool(poolConfig, pro.getProperty("redis.url"),
                Integer.parseInt(pro.get("redis.port").toString()));
    }
    // 獲得jedis資源的方法
    public static Jedis getJedis() {
        return pool.getResource();  }
    public static void main(String[] args) {
        Jedis jedis = getJedis();
        System.out.println(jedis.get("xxx"));
    }
}
------------------ajax綁定數據到jsp
<script type="text/javascript">
            //header.jsp加載完畢后 去服務器端獲得所有的category數據
            $(function(){
                var content = "";
                $.post(
                    "${pageContext.request.contextPath}/categoryList",
                    function(data){
                        //[{"cid":"xxx","cname":"xxxx"},{},{}]
                        //動態創建<li><a href="#">${category.cname }</a></li>
                        for(var i=0;i<data.length;i++){
                            content+="<li><a href='${pageContext.request.contextPath}/productListByCid?cid="+data[i].cid+"'>"+data[i].cname+"</a></li>";
                        }
                        
                        //將拼接好的li放置到ul中
                        $("#categoryUl").html(content);
                    },
                    "json"
                );
            });
        </script>
--------------------categoryListservlet中的返回數據操作---gson轉json
protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        ProductService service = new ProductService();
        
        //先從緩存中查詢categoryList 如果有直接使用 沒有在從數據庫中查詢 存到緩存中
        //1、獲得jedis對象 連接redis數據庫
        Jedis jedis = JedisPoolUtils.getJedis();
        String categoryListJson = jedis.get("categoryListJson");
        //2、判斷categoryListJson是否為空
        if(categoryListJson==null){
            System.out.println("緩存沒有數據 查詢數據庫");
            //準備分類數據
            List<Category> categoryList = service.findAllCategory();
            Gson gson = new Gson();
            categoryListJson = gson.toJson(categoryList);
            jedis.set("categoryListJson", categoryListJson);
        }
        
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(categoryListJson);
    }
  • Long is=0L;
  • servlet找錯可以先在servlet中查看進去沒有以區別錯誤位置
  • select * from product order by pdate desc limit 0,9排序(降)要9條
  • 重定向response,轉發requset
  • jstl需要導包 prefix:c
  • 默認歡迎界面在xml中只留一個,然后單獨建頁面使<%使用response跳轉%>
Paste_Image.png
Paste_Image.png
  • 自定義validate
------只能使用同步,異步會是返回值flag 無法賦值
<script src="js/jquery.validate.min.js" type="text/javascript"></script>
//自定義校驗規則
    $.validator.addMethod(
    //規則的名稱
    "checkUsername",
    //校驗的函數
    function(value, element, params) {

        //定義一個標志
        var flag = false;
        //value:輸入的內容
        //element:被校驗的元素對象
        //params:規則對應的參數值
        //目的:對輸入的username進行ajax校驗
        $.ajax({
            "async" : false,
            "url" : "${pageContext.request.contextPath}/checkUsername",
            "data" : {
                "username" : value
            },
            "type" : "POST",
            "dataType" : "json",
            "success" : function(data) {
                flag = data.isExist;
            }
        });
        //返回false代表該校驗器不通過
        return !flag;
    }
    );

1.解決也面向servlet傳中文-method=post,request.setCharacterEncoding("UTF-8");連用
2.validate導包前臺驗證注冊(看內存源碼)錯誤信息會先看原來代碼中有沒有(以class=error和for=sex來確定是為name=sex準備的)

<label class="error" for="sex" style="display:none ">您沒有第三種選擇</label>

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,527評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,687評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,640評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,957評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,682評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,011評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,009評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,183評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,714評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,435評論 3 359
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,665評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,148評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,838評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,251評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,588評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,379評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,627評論 2 380

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,830評論 18 139
  • 一. Java基礎部分.................................................
    wy_sure閱讀 3,831評論 0 11
  • 這部分主要是與Java Web和Web Service相關的面試題。 96、闡述Servlet和CGI的區別? 答...
    雜貨鋪老板閱讀 1,424評論 0 10
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,737評論 18 399
  • 文/葉子 有一個男孩,喜歡一個女孩。 雖然那個女孩已經有男朋友,但是那個女孩也背著男朋友找到男孩聊天,即便話題很曖...
    簡書_小葉子閱讀 366評論 1 2