zoukankan      html  css  js  c++  java
  • 关于java web的笔记2018-01-12

    需求:1、写一个商品类,有商品编号、商品名称、商品分类、商品单价属性。2、写一个商品条目信息类,有商品和数量两个属性,有商品总价格方法。
    3、写一个购物车类,有添加商品方法、查看订单信息,删除商品,修改商品,清空购物车,求购物车中所有商品总金额方法。4、写一个测试类,测试上述方法。
    商品类:
    [java] view plain copy
    public class Product {
    private int productId;// 商品编号
    private String productName;// 商品名称
    private String category;// 商品分类
    private double price;// 单价

    public Product() {// 无参构造
    super();
    }

    public Product(int productId, String productName, String category,
    double price) {
    super();
    this.productId = productId;
    this.productName = productName;
    this.category = category;
    this.price = price;
    }

    public String toString() {
    return "Product [productId=" + productId + ", productName="
    + productName + ", category=" + category + ", price=" + price
    + "]";
    }

    public int getProductId() {
    return productId;
    }

    public void setProductId(int productId) {
    this.productId = productId;
    }

    public String getProductName() {
    return productName;
    }

    public void setProductName(String productName) {
    this.productName = productName;
    }

    public String getCategory() {
    return category;
    }

    public void setCategory(String category) {
    this.category = category;
    }

    public double getPrice() {
    return price;
    }

    public void setPrice(double price) {
    this.price = price;
    }

    }
    商品条目信息类:
    [java] view plain copy
    public class ProductItem {
    private Product product;//购买的商品
    private int count;//商品数量
    public double totalMoney(){//小计
    double price=product.getPrice();//获取商品单价
    return price*count;
    }

    public ProductItem() {
    super();
    }

    public ProductItem(Product product, int count) {
    super();
    this.product = product;
    this.count = count;
    }

    public Product getProduct() {
    return product;
    }
    public void setProduct(Product product) {
    this.product = product;
    }
    public int getCount() {
    return count;
    }
    public void setCount(int count) {
    this.count = count;
    }

    }

    购物车类:
    [java] view plain copy
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.LinkedHashMap;
    import java.util.Map;
    public class ShoppingCart {//购物车
    //key:商品编号 value:商品条目
    private Map<Integer,ProductItem> map=new LinkedHashMap<Integer,ProductItem>();

    public void addProduct(Product p){//添加商品
    int productId=p.getProductId();
    if(map.containsKey(productId)){
    ProductItem productItem=map.get(productId);
    productItem.setCount(productItem.getCount()+1);
    }else{
    map.put(productId, new ProductItem(p,1));
    }
    }
    public void showAll(){//查看订单信息
    Collection<ProductItem> productItems = map.values();
    Iterator<ProductItem> iterator = productItems.iterator();
    while(iterator.hasNext()){
    ProductItem productItem = iterator.next();
    Product product = productItem.getProduct();
    System.out.println("商品编号:"+product.getProductId()+",商品名称:"
    +product.getProductName()+",单价:"+product.getPrice()+",数量:"+productItem.getCount()
    +",小计:"+productItem.totalMoney());
    }
    }
    public boolean deleteProduct(int productId){//删除商品
    if(map.containsKey(productId)){
    map.remove(productId);
    return true;
    }
    return false;
    }
    public boolean modifyProduct(int productId,int count){//修改
    if(map.containsKey(productId)){
    if(count>=1){
    ProductItem productItem = map.get(productId);
    productItem.setCount(count);
    return true;
    }else if(count==0){//删除
    deleteProduct(productId);
    return true;
    }
    }
    return false;
    }

    public void clearCart(){//清空购
    map.clear();
    }

    public double totalAllMoney(){//



    double total=0;
    Collection<ProductItem> productItems = map.values();
    Iterator<ProductItem> iterator = productItems.iterator();
    while(iterator.hasNext()){
    ProductItem productItem = iterator.next();
    double money=productItem.totalMoney();
    total+=money;
    }
    return total;
    }
    }


    jsp=html中写java代码
    jsp中的内容就是对应着java中的内容,最终要编译成class文件
    把jsp页面中的html排版标签输出到浏览器:out.write("<br>");//是一个字符输出流输出的
    jsp中的java代码是如何执行的:jsp中的java代码被原封不动地被翻译到了servlet的service方法中
    服务器在调用jsp时,会给jsp传递的对象:request,response,pageContext,config,session,page,out
    指令是给服务器用的,告诉服务器应当如何对待jsp页面
    <%@include file="/a.jsp"%>
    动作指令:
    <jsp:include page="/a.jsp">
    </jsp:include>
    请求转发,指向被转发的页面
    <jsp:forward page="/a.jsp">
    <%--传递请求参数,供其他标签使用--%>
    <jsp:param name="a" value="123"></jsp:param>
    <jsp:param name="b" value="456"></jsp:param>
    </jsp:forword>
    Statement:代表SQL语句,向数据库发送并执行SQL语句
    ResultSet executeQuery(String sql):仅仅执行数据库的查询操作,返回查询的结果集
    int executeUpdate(String sql):执行DML,返回影响操作数据记录的行数
    int num = stmt.executeUpdate("update users set id='111'");
    boolean execute(String sql):执行sql语句,如果有返回值则返回true,没有返回值返回false
    遍历的结果集打印到控制台没有鸟用,应该封装到JavaBean中
    List<Users> user = new ArrayList<Users>();
    while(rs.next()){
    Users u = new Users();
    u.setId(rs.getInt("id"));
    u.setName(rs.getString("name"));
    u.setEmail(rs.getString("email"));
    u.setBirthday(rs.getDate("birthday"));
    user.add(u);
    }
    jdbc的编码规范和工具类的抽取
    1.编写配置文件dbcpfg.properties
    2.工具类:JdbcUtil.java,直接拿来用
    3.编写自己的代码
    Connction conn = null;
    Statment stmt = null;
    ResultSet rs = null;
    try{
    conn = JdbcUtil.getConnection();
    stmt = conn.createStatement();
    // your code
    }catch(Exception e){
    throw new RuntimeException(e);
    }finally{
    JdbcUtil.release(rs, stmt, conn);
    }

    JDBC的CRUD
    public void myAdd(){
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try{
    conn = JdbcUtil.getConnection();
    stmt = conn.createStatement();
    // 添加没有结果集
    stmt.executeUpdate("insert into users(iname, password, email, birthday) values ('tom','123', 'boshi.cn','1990-02-10')");
    }catch(Exception e){
    throw new RuntimeException(e);
    }finally{
    JdbcUtil.release(null, stmt, conn);
    }
    }
    public void myDel(){
    Connction conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try{
    conn = JdbcUtil.getConnection();
    stmt = conn.createStatement();
    // 删除没有结果集
    stmt.executeUpdate("delete from users where id='12'");
    }catch(Exception e){
    throw new RuntimeException(e);
    }finally{

    JdbcUtil.release(rs, stmt, conn);
    }
    }
    public void myModify(){
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try{
    conn = JdbcUtil.getConnection();
    stmt = conn.createStatement();
    stmt.executeUpdate("update users set name='deng' where id = 111");// id是整数,不用引号
    }catch(Exception e){
    throw new RuntimeException(e);
    }finally{
    JdbcUtil.release(null,stmt,conn);
    }
    }
    // 从user中获取数据
    public void mySave(User user){
    Connection conn = null;
    PreparedStatement stmt = null;
    try{
    conn = JdbcUtil.getConnection();
    // 预编译指令
    stmt = conn.PrepareStatement("insert into users(name, pass, email) values (?,?,?,?)");
    stmt.setString(1, user.getName());// 1代表预编译指令中的第一个问号,之后一次类推
    stmt.setString(2, user.getPass());
    stmt.setString(3, user.getEmail());
    stmt.executeUpdate();
    }catch(Exception e){
    throw new RuntimeException(e);
    }finally{
    JdbcUtil.release(null,stmt,conn);
    }
    }
    分页
    select * from customer limit 0,10
    对客户信息的查询结果集进行分页
    // 设计page类,封装与分页有关的信息
    public class Page{
    private int pageSize = 10; // 每页显示的记录条数
    private List records; // 每页显示的记录,dao传过来
    private int pageNum=1; // 当前页码,由用户传进来
    private int totalPage; // 总共的页数,计算出来

    private int pageIndex; // 每页开始记录的索引,计算出来
    private int totalRecords; // 总共的记录个数,dao传过来
    public Page(int pageNum, int totalRecords){
    this.pageNum = pageNum;
    this.totalRecords = totalRecords;
    // 计算总页数
    this.totalPage = totalRecords%page/Size==0?totalRecords/page/Size:totalRecords/page/Size+1;
    // 当前页的开始记录索引
    this.pageIndex = (pageNum-1)*pageSize;
    }
    }
    // dao中的方法
    // 获取记录的总条目数
    int getTotalRecordsNum();
    // 根据索引查询分页记录,pageIndex:开始查询的位置;size:每页显示的记录条数
    List<Customer> findPageRecords(int pageIndex, int size);

    // dao 实现
    public int getTotalRecordsNum(){
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try{
    conn = JdbcUtil.getConnection();
    stmt = conn.PrepareStatement("select count(*) from Customer");
    rs = stmt.executeQuery();
    if(rs.next()){
    return rs.getInt(1);
    }
    }catch(Exception e){
    throw new RuntimeException(e);
    }finally{
    JdbcUtil.release(null,stmt,conn);
    }
    }
    // 每一个记录为一个对象,把记录保存起来就是要把这些对象存起来.当前页的索引,每页显示的索引个数
    public List<Customer> findPageRecords(int offset, int size){
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try{
    conn = JdbcUtil.getConnection();
    stmt = conn.PrepareStatement("select * from Customer");
    rs = stmt.executeQuery();// 保存了所有的记录
    List<Customer> cs = new ArrayList<Customer>();
    // 迭代把这些东东取出来
    while(rs.next()){
    Customer customer = new Customer();
    customer.setId(rs.getInt("id"));
    customer.setName(rs.getString("name"));
    customer.setPassword(rs.getString("password"));
    customer.setEmail(rs.getString("email"));
    customer.setBirthday(rs.gteDate("birthday"));
    cs.add(customer);
    }
    return cs;

    }catch(Exception e){
    throw new RuntimeException(e);
    }finally{
    JdbcUtil.release(null,stmt,conn);
    }
    }

    // 根据用户查询的页码,返回有关该页面数据的page对象
    Page fingPage(String pageNum);
    实现:
    public Page findPage(String num){
    private int pageNum = 1;// 默认值1
    if(num!=null){
    pageNum = Integer.parseInt(num);
    }
    // 从dao获取总的记录
    int pageRecords = dao.getTotalRecordsNum();
    // 目前有的数据,当前页码;总记录。建立一个Page对象
    Page page = new Page(pageNum,pageRecords);// 该对象已经初始化了,包含了所有的信息
    // 获取记录数据
    List<Customer> cs = dao.findPageRecords(page.getPageIndex(),page.getPageSize());
    // 大方向是一个list
    page.setRecords(cs);
    return page;

    }

    // 改造servlet
    public void showAllCustomers(HttpServleRequest request, HttpServletResponse response){
    // 获取用户要看的页码
    String pageNum = request.getParameter("num");
    Page page = s.findPage(pageNum);
    request.setAttribute("page",page);
    // 让其在别的页面显示出来
    request.getRequestDispacther("/abc/1.jsp").forward(request,response);
    }
    -------------------------
    ${param.name}等价于request.getParameter("name");// 用于服务器从浏览器或客户端取数据
    ${requestScope.name}等价于request.getAttribute("name"); // 服务器传递结果到页面,在页面获取服务器保存的值

    <c:forEach items="${userList}" var="user" varStatus="status" begin="0" end="${userList.size}" step="1">
    </c:forEach>
    -------------------------
    改造jsp页面
    <c:forEach items="${page.records}" var="c" varStatus="vs">
    <tr class="${vs.index%2==0?'odd':'even'}">
    <td>
    <input tyep="checkbox" name="ids" value="${c.id}"
    </td>
    <td>
    ${c.name}
    </td>
    <td>
    ${c.email}
    </td>
    <td>
    ${{c.birthday}
    </td>
    <td>
    <a href="${pageContext.request.contextPath}/servlet/Controller?op=editCustoerUI&customerId=${c.id}">修改</a>
    <a href="javaScript:deleOne('${c.id}')">删除</a>
    </td>
    </tr>
    <c:forEach>
    分页:
    第${page.pageNum}页&nbsp;&nbsp;总共${page.totalPage}页&nbsp;&nbsp;
    <a href="${pageContext.request.contextPath}/servlet/Controller?op=showAllCustomers&num=${page.pageNum-1<1?1:page.pageNum-1}">上一页</a>
    <a href="${pageContext.request.contextPath}/servlet/Controller?op=showAllCustomers&num=${page.pageNum+1>page.totalPage?page.totalPage:page.pageNum+1}">下一页</a>

    jstl标签
    <c:forEach items="${userList}" var="user" varStatus="status" begin="0" end="${userList.size}" step="1" >
    //循环体
    <c:out value="${status.index}"></c:out>
    <c:out value="${status.count}"></c:out>
    <c:out value="${ user.name }"></c:out>
    <c:out value="${ user.age }"></c:out>
    </c:forEach>

    参数说明:
    1)items:是集合,用EL表达式;
    2)var:变量名,存放items各个项 ,代表集合中每一条数据
    3)varStatus: 显示循环状态的变量,有一下几个属性:
    ①index:从0开始; 显示当前迭代的索引值
    ②count:元素位置,从1开始; 显示当前迭代显示的行位置,通过配合判断语句,实现给奇、偶行着不同的色,以进行分区
    ③first:如果是第一个元素则显示true;
    ④last:如果是最后一个元素则显示true;
    4)begin:循环的初始值(整型);
    5)end: 循环结束(整型);
    6)step:步长,循环间隔的数值(整型);

  • 相关阅读:
    疯狂秀才基本权限管理框架2012新版
    保存网站或系统的全局配置使用JSON格式保存到文件更轻便!
    ASP.NET MVC3 学习笔记(一)MVC模式简介
    疯狂秀才基本权限管理框架2012(国庆版)
    使用Knockout 绑定简单 json 对象
    jquery.Validate API 中文CHM版 疯狂秀才整理
    EasyUI 中 MenuButton 的使用方法
    Javascript Object的使用方法
    Javascript 定义二维数组的方法
    HTML5 Web存储的localStorage和sessionStorage的使用方法【图文说明】
  • 原文地址:https://www.cnblogs.com/demo-deng/p/8276328.html
Copyright © 2011-2022 走看看