欢迎光临散文网 会员登陆 & 注册

Java web:含个人详细总结,EL表达式param,JSP,servlet作业【诗书画唱】

2020-09-21 15:08 作者:诗书画唱  | 我要投稿




实现珠宝店购物车功能:


package com.Servlet;


import java.io.IOException;

import java.util.HashMap;

import java.util.Map;


import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;


/**

 * Servlet implementation class CartServlet

 */

@WebServlet("/CartServlet")

public class CartServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public CartServlet() {

        super();

        // TODO Auto-generated constructor stub

    }


/**

* @see HttpServlet#doGet(HttpServletRequest request,

*  HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, 

HttpServletResponse response) throws 

ServletException, IOException {

// TODO Auto-generated method stub

this.doPost(request, response);

}


/**

* @see HttpServlet#doPost(HttpServletRequest

*  request, HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request,

HttpServletResponse response) 

throws ServletException, IOException {

// TODO Auto-generated method stub

//获取商品名称和价格:

String name = request.getParameter("name");

name = new String(name.getBytes("iso8859-1"),"utf-8");

String strPrice = request.getParameter("price");

//将strPrice转换成数字:

Double price = 0.0;

if(strPrice != null && strPrice.length() > 0) {

price = Double.parseDouble(strPrice);

}

// System.out.println(name);

// System.out.println(strPrice);

//封装数据:

Product p = new Product();

p.setName(name);

p.setPrice(price);


//获取session对象:

HttpSession session = request.getSession();

//尝试着从session中获取购物车对象(_cart):

Object objCart = session.getAttribute("_cart");

//什么样的情况下就是第一次添加购物车:

if(objCart == null) {

//如果是第一次添加购物车,就必须new出这个购物车

//个人的总结:因为session.getAttribute("_cart")获取自要用

// session.setAttribute("_cart", cart);发送到的

// cartShow.jsp文件。:

Map<String,Integer>cart = new HashMap<String,Integer>();

cart.put(name, 1);

System.out.println(cart);

//将cart放到session中去:

session.setAttribute("_cart", cart);

} else {

//如果是第n次添加购物车,将objCat转换成Map:

Map<String,Integer>cart = (HashMap<String,Integer>)objCart;

//判断选中的商品在map中是否已经存在:

//contain:包含【英[kənˈteɪnz] 】

if(cart.containsKey(name)){//如果选中的商品已经存在

//数量加1:

Integer count = cart.get(name);

count ++;

//将加1以后的数量放回map中

cart.put(name, count);

} else {

cart.put(name, 1);

}

System.out.println(cart);

//将cart放回session中:

session.setAttribute("_cart", cart);

}

//跳转回shopping.jsp:

request.getRequestDispatcher("shoppingStart.jsp")

    .forward(request, response);

}


}




package com.Servlet;


public class Product {

    private Integer id;

    private String name;

    private Double price;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Double getPrice() {

return price;

}

public void setPrice(Double price) {

this.price = price;

}

}



package com.Servlet;


import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


/**

 * Servlet implementation class shoppingServ

 */

@WebServlet("/shoppingServlet")

public class shoppingServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public shoppingServlet() {

        super();

        // TODO Auto-generated constructor stub

    }


/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// TODO Auto-generated method stub

this.doPost(request, response);

}


/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// TODO Auto-generated method stub

//商品名称:

String name = request.getParameter("name");

//中文乱码处理:

name = new String(name.getBytes("iso8859-1"),"utf-8");

// String strPrice = request.getParameter("price");

// //商品价格

// Double price = 0.0;

// //如果strPrice不为空,就转换成Double类型

// if(strPrice != null && strPrice.length() > 0) {

// price = Double.parseDouble(strPrice);

// }

// //商品图片路径:

// String src = request.getParameter("src");


request.setCharacterEncoding("gbk");

request.getRequestDispatcher("detailShow.jsp?name=" + name)

    .forward(request, response);


}


}


<%@page import="java.util.Iterator"%>

<%@page import="java.util.Set"%>

<%@page import="java.util.HashMap"%>

<%@page import="java.util.Map"%>

<%@ page language="java" contentType="text/html;

 charset=UTF-8" pageEncoding="UTF-8"%>

<%

    String path = request.getContextPath();

    String basePath = request.getScheme()

    +"://"+request.getServerName()

    +":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

        <base hreff="<%=basePath%>">

        <title></title>

        <meta http-equiv="pragma" content="no-cache">

        <meta http-equiv="cache-control" content="no-cache">

        <meta http-equiv="expires" content="0">

        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

        <meta http-equiv="description" content="This is my page">

        <style type="text/css">

            * {

                font-size:50px;

            }

        </style>

    </head>

    <body>

        <h1>购物车列表</h1>

        <ul>

      <%--自己的总结:

      

    当点击“添加商品按钮后”,触发方法addCart,通过

    “addCart('${param.name}',${param.price})”  

    传值给CartServlet.java文件中。

    在CartServlet.java文件中用

    request.getParameter("name")等获取。

用session.setAttribute("_cart", cart);

将cart放回session中。 --%>

        <%

            // 因为在CartServlet.java

           // 文件中有session.setAttribute("_cart", cart);

   ///  所以可以用 session.getAttribute("_cart");获取购物车cart:

            Object objCart = session.getAttribute("_cart");

            Map<String,Integer>cart = new HashMap<String,Integer>();

            if(objCart != null) {

            cart = (HashMap<String,Integer>)objCart;

            }

            Set<String>keys = cart.keySet();

            

            //下面是用迭代器遍历添加到购物车中的内容:

            Iterator<String> it = keys.iterator();

            while(it.hasNext()) {

            //商品名称:

            String name = it.next();    

            //商品数量:

            Integer count = cart.get(name);

            %>

            <li><%=name %>:<%=count %></li>

            <%

            }

        %>

        </ul>

        <a hreff="shoppingStart.jsp">返回</a>

    </body>

</html>



<%@ page language="java" contentType="text/html;

 charset=UTF-8" pageEncoding="UTF-8"%>

<%

    String path = request.getContextPath();

    String basePath = request.getScheme()

    +"://"+request.getServerName()

    +":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

        <base hreff="<%=basePath%>">

        <title></title>

        <meta http-equiv="pragma" content="no-cache">

        <meta http-equiv="cache-control" content="no-cache">

        <meta http-equiv="expires" content="0">

        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

        <meta http-equiv="description" content="This is my page">

        <script type="text/javascript">

            //添加到购物车功能

            function addCart(name,price){

            window.location.hreff = 'CartServlet?name=' + name 

            + '&price=' + price;

            }

        </script>

    </head>

    <body>

        <h1>显示珠宝详情</h1>

        <%--

        个人的总结:

        如果用“?XXX=YYY”等的格式地址栏等传参,

        那么可以用${param.XXX }获取YYY的值

         --%>

        <h1>商品名称:${param.name }</h1>

        <h1><img src="${param.src }" /></h1>

        <h1>¥${param.price }</h1>

        <input id="btn" type="button" value="加入购物车"

            onclick="addCart('${param.name}',${param.price});" />

    </body>

</html>



<%@ page language="java" contentType="text/html;

 charset=UTF-8" pageEncoding="UTF-8"%>

<%

    String path = request.getContextPath();

    String basePath = request.getScheme()

    +"://"+request.getServerName()

    +":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

        <base hreff="<%=basePath%>">

        <title></title>

        <meta http-equiv="pragma" content="no-cache">

        <meta http-equiv="cache-control" content="no-cache">

        <meta http-equiv="expires" content="0">

        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

        <meta http-equiv="description" content="This is my page">

        <style type="text/css">

            * {

                font-size:52px;

                

            }

            

        </style>

      <%-- 个人的总结:

        如果路径名为XXX格式,那么XXX是servlet文件中

        用@WebServlet("/shoppingServlet")声明的路径;

               如果路径名为XXX.jsp格式,那么XXX是jsp文件

        的路径,在同级目录下相对路径为“文件名+后缀”;

         --%> 

        <script type="text/javascript">

            function detail(name,price,src){

            window.location.hreff = 'shoppingServlet?name=' + name 

            + '&price=' + price + '&src=' + src;

            }

            

            function viewCart(){

            window.location.hreff= 'cartShow.jsp';

            }

            

        </script>

    </head>

    <body>

        <table border="1" align="center">

            <tr>

                <th>珠宝名称</th>

                <th>珠宝图片</th>

                <th>珠宝价格</th>

                <th><a hreff="javascript:viewCart();">查看购物车</a></th>

            </tr>

            <tr>

                <td>橙宝石</td>

                <td><img src="img/14.png" /></td>

                <td>¥200000</td>

                <td><a hreff="javascript:detail

                ('橙宝石',200000,'img/14.png');">查看详情</a></td>

            </tr>

            <tr>

                <td>紫晶</td>

                <td><img src="img/16.png" /></td>

                <td>¥300000</td>

                <td><a hreff="javascript:detail

                ('紫晶',300000,'img/16.png');">查看详情</a></td>

            </tr>

            <tr>

                <td>红宝石</td>

                <td><img src="img/41.png" /></td>

                <td>¥500000</td>

                <td><a hreff="javascript:

                detail('红宝石',500000,'img/41.png');">查看详情</a></td>

            </tr>

            <tr>

                <td>紫宝石</td>

                <td><img src="img/5.png" /></td>

                <td>¥100000</td>

                <td><a hreff="javascript:

                detail('紫宝石',100000,'img/5.png');">查看详情</a></td>

            </tr>

        </table>

    </body>

</html>


Java web:含个人详细总结,EL表达式param,JSP,servlet作业【诗书画唱】的评论 (共 条)

分享到微博请遵守国家法律