servlet

Wesley13
• 阅读 772

思路分析:
1. 根据需求抽象出业务对象
User{
usrename;
password;
}

ShoppingCarItem{
product;
num;
}

ShoppingCar{
List
}

2. 写Servlet处理请求
...

domain:

Java代码 servlet servletservlet

  1. package cn.itcast.cd.domain;

  2. import java.util.ArrayList;

  3. import java.util.List;

  4. import java.util.UUID;

  5. public class ShoppingCar {

  6. private List list = new ArrayList();

  7. /**

  8. * 根据货品和数量往购物车中添加

  9. * @param product

  10. * @param num

  11. */

  12. public void add(String product,Integer num){

  13. ShoppingCarItem carItem = new ShoppingCarItem();

  14. carItem.setNum(num);

  15. carItem.setProduct(product);

  16. carItem.setId(UUID.randomUUID().toString());

  17. list.add(carItem);

  18. }

  19. /**

  20. * 根据唯一的标示删除购物车中对应的明细

  21. * @param id

  22. */

  23. public void remove(String id){

  24. for (ShoppingCarItem item : list) {

  25. if(id.equals(item.getId())){

  26. list.remove(item);

  27. break;

  28. }

  29. }

  30. }

  31. public List getList() {

  32. return list;

  33. }

  34. }

  35. package cn.itcast.cd.domain;

  36. public class ShoppingCarItem {

  37. private String product;

  38. private Integer num;

  39. private String id; //给每一个明细生成一个唯一的id

  40. public String getProduct() {

  41. return product;

  42. }

  43. public void setProduct(String product) {

  44. this.product = product;

  45. }

  46. public Integer getNum() {

  47. return num;

  48. }

  49. public void setNum(Integer num) {

  50. this.num = num;

  51. }

  52. public String getId() {

  53. return id;

  54. }

  55. public void setId(String id) {

  56. this.id = id;

  57. }

  58. }

  59. package cn.itcast.cd.domain;

  60. public class User {

  61. private String username;

  62. private String password;

  63. public String getUsername() {

  64. return username;

  65. }

  66. public void setUsername(String username) {

  67. this.username = username;

  68. }

  69. public String getPassword() {

  70. return password;

  71. }

  72. public void setPassword(String password) {

  73. this.password = password;

  74. }

  75. }

package cn.itcast.cd.domain;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ShoppingCar {
    private List<ShoppingCarItem> list = new ArrayList<ShoppingCarItem>();
    
    /**
     * 根据货品和数量往购物车中添加
     * @param product
     * @param num
     */
    public void add(String product,Integer num){
        ShoppingCarItem carItem = new ShoppingCarItem();
        carItem.setNum(num);
        carItem.setProduct(product);
        carItem.setId(UUID.randomUUID().toString());
        list.add(carItem);
    }
    
    /**
     * 根据唯一的标示删除购物车中对应的明细
     * @param id
     */
    public void remove(String id){
        for (ShoppingCarItem item : list) {
             if(id.equals(item.getId())){
                 list.remove(item);
                 break;
             }
        }
    }    
    
    public List<ShoppingCarItem> getList() {
        return list;
    }
    
}

package cn.itcast.cd.domain;

public class ShoppingCarItem {
    private String product;
    private Integer  num;
    private String id;  //给每一个明细生成一个唯一的id
    public String getProduct() {
        return product;
    }
    public void setProduct(String product) {
        this.product = product;
    }
    public Integer getNum() {
        return num;
    }
    public void setNum(Integer num) {
        this.num = num;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    
}

package cn.itcast.cd.domain;

public class User {
    private String username;
    private String password;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

servlet:

Java代码 servlet servletservlet

  1. package cn.itcast.cd.servlet;

  2. import java.io.IOException;

  3. import java.io.PrintWriter;

  4. import javax.servlet.ServletException;

  5. import javax.servlet.http.HttpServlet;

  6. import javax.servlet.http.HttpServletRequest;

  7. import javax.servlet.http.HttpServletResponse;

  8. import javax.servlet.http.HttpSession;

  9. import cn.itcast.cd.domain.ShoppingCar;

  10. public class BuyServlet extends HttpServlet {

  11. @Override

  12. protected void service(HttpServletRequest request, HttpServletResponse response)

  13. throws ServletException, IOException {

  14. request.setCharacterEncoding("UTF-8");

  15. response.setContentType("text/html;charset=utf-8");

  16. //1. 获取请求中的参数.

  17. String product = request.getParameter("product");

  18. String num = request.getParameter("num");

  19. //2. 获取到购物车

  20. //2.1 首先要到session中找一下是否已经有了购物车. 如果有的话就不需要创建了... 直接把货品放到购物车中就可以了

  21. HttpSession httpSession = request.getSession();

  22. ShoppingCar shoppingCar = (ShoppingCar)httpSession.getAttribute("SHOPINGCAR_IN_SESSION");

  23. if(shoppingCar==null){ //说明是第一次购物. 还没有购物车的

  24. //2.2 如果从session中没有找到购物车. 需要新创建一个购物车并且放到session中.为了下次购物使用这个购物车

  25. shoppingCar = new ShoppingCar();

  26. httpSession.setAttribute("SHOPINGCAR_IN_SESSION", shoppingCar);

  27. }

  28. shoppingCar.add(product, Integer.parseInt(num));

  29. PrintWriter pw = response.getWriter();

  30. pw.println("添加成功
    ");

  31. pw.println("继续购物
    ");

  32. pw.println("管理购物
    ");

  33. }

  34. }

  35. package cn.itcast.cd.servlet;

  36. import java.io.IOException;

  37. import java.io.PrintWriter;

  38. import javax.servlet.ServletException;

  39. import javax.servlet.http.HttpServlet;

  40. import javax.servlet.http.HttpServletRequest;

  41. import javax.servlet.http.HttpServletResponse;

  42. import javax.servlet.http.HttpSession;

  43. import cn.itcast.cd.domain.ShoppingCar;

  44. import cn.itcast.cd.domain.ShoppingCarItem;

  45. import cn.itcast.cd.domain.User;

  46. public class ListServlet extends HttpServlet {

  47. @Override

  48. protected void service(HttpServletRequest request, HttpServletResponse response)

  49. throws ServletException, IOException {

  50. request.setCharacterEncoding("UTF-8");

  51. response.setContentType("text/html;charset=utf-8");

  52. HttpSession httpSession = request.getSession();

  53. //1. 先获取session中的User

  54. User user = (User) httpSession.getAttribute("USER_IN_SESSION");

  55. PrintWriter pw = response.getWriter();

  56. pw.println("当前用户为:"+user.getUsername()+"
    ");

  57. //2. 获取session的购物车

  58. ShoppingCar shoppingCar = (ShoppingCar) httpSession.getAttribute("SHOPINGCAR_IN_SESSION");

  59. //2.1 如果在session中购物车的话,列出购物车中的明细

  60. if(shoppingCar!=null){

  61. for (ShoppingCarItem item : shoppingCar.getList()) {

  62. pw.println("货品:"+item.getProduct()+" 数量:"+item.getNum()+"
    ");

  63. }

  64. }else{

  65. //2.2 在session中没有购物车的话.提示用户没有当前用户名购物车

  66. pw.println("当前用户没有购物车.");

  67. }

  68. }

  69. }

  70. package cn.itcast.cd.servlet;

  71. import java.io.IOException;

  72. import java.io.PrintWriter;

  73. import javax.servlet.ServletException;

  74. import javax.servlet.http.HttpServlet;

  75. import javax.servlet.http.HttpServletRequest;

  76. import javax.servlet.http.HttpServletResponse;

  77. import javax.servlet.http.HttpSession;

  78. import cn.itcast.cd.domain.User;

  79. public class LoginServlet extends HttpServlet {

  80. @Override

  81. protected void service(HttpServletRequest request, HttpServletResponse response)

  82. throws ServletException, IOException {

  83. request.setCharacterEncoding("UTF-8");

  84. response.setContentType("text/html;charset=utf-8");

  85. //1. 接收请求中的数据封装对象

  86. String username = request.getParameter("username");

  87. String password = request.getParameter("password");

  88. User user = new User();

  89. user.setPassword(password);

  90. user.setUsername(username);

  91. //2. 将用户方到session中供ListServlet从session中访问到User

  92. HttpSession httpSession = request.getSession();

  93. httpSession.setAttribute("USER_IN_SESSION", user);

  94. PrintWriter pw = response.getWriter();

  95. pw.println("欢迎:"+username+"
    ");

  96. pw.println("购物
    ");

  97. pw.println("管理购物
    ");

  98. }

  99. }

package cn.itcast.cd.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.itcast.cd.domain.ShoppingCar;

public class BuyServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
     //1.  获取请求中的参数.
        String product = request.getParameter("product");
        String num     = request.getParameter("num");
     //2. 获取到购物车
           //2.1  首先要到session中找一下是否已经有了购物车. 如果有的话就不需要创建了... 直接把货品放到购物车中就可以了
            HttpSession httpSession = request.getSession();
            ShoppingCar shoppingCar = (ShoppingCar)httpSession.getAttribute("SHOPINGCAR_IN_SESSION");
            if(shoppingCar==null){ //说明是第一次购物. 还没有购物车的
                //2.2  如果从session中没有找到购物车. 需要新创建一个购物车并且放到session中.为了下次购物使用这个购物车
                shoppingCar = new ShoppingCar();
                httpSession.setAttribute("SHOPINGCAR_IN_SESSION", shoppingCar);
            }
            shoppingCar.add(product, Integer.parseInt(num));
            PrintWriter pw = response.getWriter();
            pw.println("添加成功<br/>");
            pw.println("<a href='/buy.html'>继续购物</a><br/>");
            pw.println("<a href='/list'>管理购物</a><br/>");
        
    }
}

package cn.itcast.cd.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.itcast.cd.domain.ShoppingCar;
import cn.itcast.cd.domain.ShoppingCarItem;
import cn.itcast.cd.domain.User;

public class ListServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        
        HttpSession httpSession = request.getSession();
        //1. 先获取session中的User
         User user  = (User) httpSession.getAttribute("USER_IN_SESSION");
         PrintWriter pw = response.getWriter();
         pw.println("当前用户为:"+user.getUsername()+"<br/>");
        //2. 获取session的购物车
                 ShoppingCar shoppingCar = (ShoppingCar) httpSession.getAttribute("SHOPINGCAR_IN_SESSION");
              //2.1  如果在session中购物车的话,列出购物车中的明细
                if(shoppingCar!=null){
                    for (ShoppingCarItem item : shoppingCar.getList()) {
                        pw.println("货品:"+item.getProduct()+"  数量:"+item.getNum()+"<br/>");
                    }
                }else{
                    //2.2 在session中没有购物车的话.提示用户没有当前用户名购物车
                     pw.println("当前用户没有购物车.");
                }
        
        
        
    }
}

package cn.itcast.cd.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.itcast.cd.domain.User;

public class LoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        
        //1. 接收请求中的数据封装对象
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User();
        user.setPassword(password);
        user.setUsername(username);
        
        //2. 将用户方到session中供ListServlet从session中访问到User
        HttpSession  httpSession = request.getSession();
        httpSession.setAttribute("USER_IN_SESSION", user);
        
        PrintWriter pw = response.getWriter();
        pw.println("欢迎:"+username+"<br/>");
        pw.println("<a href='/buy.html'>购物</a><br/>");
        pw.println("<a href='/list'>管理购物</a><br/>");
    }

    
}

用户登录页面:

Html代码 servlet servletservlet

  1. <html>

  2. <head>

  3. <title>用户登录</title>

  4. </head>

  5. <body>

  6. 用户名:<input type="text" name="username">

  7. 密码:<input type="text" name="password">

  8. <input type="submit" value="登录">

  9. </form>

  10. </body>

  11. </html>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户登录</title>
</head>
<body>

<form action="/login" method="post">
    用户名:<input type="text" name="username"><br/>
    密码:<input type="text" name="password"><br/>
    <input type="submit" value="登录">
</form>
</body>
</html>

购买页面:

Html代码 servlet servletservlet

  1. <html>

  2. <head>

  3. <title>购物货品</title>

  4. </head>

  5. <body>

  6. 货品:<select name="product">

  7. </select>

  8. 数量:<input type="text" name="num">

  9. <input type="submit" value="购买">

  10. </form>

  11. </body>

  12. </html>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>购物货品</title>
</head>
<body>

<form action="/buy" method="post">
    货品:<select name="product">
        <option value="鼠标">鼠标</option>
        <option value="键盘">键盘</option>
        <option value="内存">内存</option>
                  <option value="显示器">显示器</option>
    </select>  <br/>
    数量:<input type="text" name="num"><br/>
    <input type="submit" value="购买">
</form>
</body>
</html>

web.xml配置:

Xml代码 servlet servletservlet

  1. <web-app xmlns="http://java.sun.com/xml/ns/javaee"

  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  3. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app\_2\_5.xsd"

  4. version="2.5">

  5. <servlet>

  6. <servlet-name>LoginServlet</servlet-name>

  7. <servlet-class>cn.itcast.cd.servlet.LoginServlet</servlet-class>

  8. </servlet>

  9. <servlet-mapping>

  10. <servlet-name>LoginServlet</servlet-name>

  11. <url-pattern>/login</url-pattern>

  12. </servlet-mapping>

  13. <servlet>

  14. <servlet-name>BuyServlet</servlet-name>

  15. <servlet-class>cn.itcast.cd.servlet.BuyServlet</servlet-class>

  16. </servlet>

  17. <servlet-mapping>

  18. <servlet-name>BuyServlet</servlet-name>

  19. <url-pattern>/buy</url-pattern>

  20. </servlet-mapping>

  21. <servlet>

  22. <servlet-name>ListServlet</servlet-name>

  23. <servlet-class>cn.itcast.cd.servlet.ListServlet</servlet-class>

  24. </servlet>

  25. <servlet-mapping>

  26. <servlet-name>ListServlet</servlet-name>

  27. <url-pattern>/list</url-pattern>

  28. </servlet-mapping>

  29. </web-app>

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
35岁是技术人的天花板吗?
35岁是技术人的天花板吗?我非常不认同“35岁现象”,人类没有那么脆弱,人类的智力不会说是35岁之后就停止发展,更不是说35岁之后就没有机会了。马云35岁还在教书,任正非35岁还在工厂上班。为什么技术人员到35岁就应该退役了呢?所以35岁根本就不是一个问题,我今年已经37岁了,我发现我才刚刚找到自己的节奏,刚刚上路。
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这