2022年Jsp课程课时八——案例(Servlect常用对象)

简介: 2022年Jsp课程课时八——案例(Servlect常用对象)

常用方法

1 设置编码格式response.setCharacterEncoding("UTF-8");

2 设置浏览访问的是htmlresponse.setContentType("text/html;charset=UTF-8");

3 ServletConfig对象

获取静态数据

@WebServlet(urlPatterns = "/ServletA",initParams = {

@WebInitParam(name="name", value = "张三,李四,王五")})

//创建ServletConfig 对象应用

ServletConfig config=getServletConfig();

//创建静态数据 name sex age heught weight

String name=config.getInitParameter("name");

System.out.println("恭喜你成功获得名字对象"+name);

4 response.getWriter() 在浏览中显示浏览数据

String info="<h1>HELLOW WORLD JSP</h1>";

PrintWriter pw=response.getWriter();

pw.print(info);    

5每隔五秒刷新浏览器界面

response.setHeader("refresh", "5");

6 servlet的跳转。response.sendRedirect("ServletB");

重定向:属于浏览器的跳转

浏览地址发生改变

重定向为二次请求。

重定向可以访问不同服务器的跳转。

7实现共享静态数据,动态数据,共享文件数据。

//创建ServletContext对象

ServletContext sa = getServletContext();

// 创建动态动态数据

sa.setAttribute("pq", "篮球");

response.getWriter().append("<h1>ServletB获得动态数据篮球</h1><hr>" + a);

* 删除对象 sc.removeAttribute("pq");

8//图片下载设置响应头

response.setHeader("content-disposition", "attachment;filenname=flower.jpg");

9

HttpServletReques对象(请求发送作用在服务器)

//得到url地址请求
        String AA=request.getRequestURI().toString();
        System.out.println("使用的方法request.getRequestURI().toString()");
        System.out.println(AA);
        //得到请求数据
        String BB=request.getRequestURI();
        System.out.println("使用的方法getRequestURI()");
        System.out.println(BB);
        //得到请求的url地址中附加参数
        String CC=request.getQueryString();
        System.out.println(CC);
        System.out.println("使用的方法request.getQueryString()");
        //得到来访者的IP地址
        String DD=request.getLocalAddr();
        System.out.println(DD);
        System.out.println("使用的方法request.getLocalAddr()");
        //得到来访者的主机名
        String EE=request.getRemoteHost();
        System.out.println(EE);
        System.out.println("使用的方法request.getRemoteHost()");
        //得到来访者端口号
        int FF=request.getRemotePort();
        System.out.println(FF);
        System.out.println("使用的方法request.getRemotePort()");
        //得到请求url地址使用方法(重要)
        String GG=request.getMethod();
        System.out.println("GG");
        System.out.println("使用的方法request.getMethod()");
        //获取web服务器的主机名
        String HH=request.getLocalAddr();
        System.out.println("使用的方法request.getLocalAddr()");
        //获取web的服务·端口号
        int II =request.getLocalPort();
        System.out.println(II);
        System.out.println("使用的方法request.getLocalPort()");
request.getRequestDispatcher("/Servlect4").forward(request, response);

实现服务里面的跳转

HttpServletResponse对象    (作用在浏览器)

作用一

String info="hellow world java";
//使用response获得输出
OutputStream  os =response.getOutputStream();
os.write(info.getBytes());
os.write(info1.getBytes());

作用二

图片的下载

response.setHeader("content-disposition", "attachment;filenname=flower.jpg");
        ServletContext sa=getServletContext();
        String path=sa.getRealPath("下载文件的路径");
        InputStream is =new FileInputStream(path);
        byte [] bytes =new byte[1024];
        int count=-1;
        OutputStream os=response.getOutputStream();
        while((count=is.read(bytes))!=-1) {
            os.write(bytes,0,count);

//作用三

实现servlet的跳转

response.sendRedirect("Servlet2");


综合案例


package Com.Com.As_2.com.HuBin;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
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 ServletA
 */
@WebServlet(urlPatterns = "/ServletA",initParams = {
    @WebInitParam(name="name", value = "张三,李四,王五"),
    @WebInitParam(name="sex", value = "男,女,男"),
    @WebInitParam(name="age", value = "23,34,69"),
    @WebInitParam(name="height", value = "178cm,156cm,180cm"),
    @WebInitParam(name="weight", value = "50kg,45kg,60kg")
})
public class ServletA extends HttpServlet {
  private static final long serialVersionUID = 1L;
    /**
     * Default constructor. 
     */
    public ServletA() {
        System.out.println("项目Com.Com.As_2/com.hubin真在运行中,com on");
    }
    /*
     *Servlet inint()方法
     */
    @Override
    public void init() throws ServletException {
      // TODO Auto-generated method stub
      super.init();
      //创建ServletConfig 对象
      ServletConfig config=getServletConfig();
      //创建静态数据 name sex age heught weight
      String name=config.getInitParameter("name");
      String sex=config.getInitParameter("sex");
      String age=config.getInitParameter("age");
      String height=config.getInitParameter("height");
      String weight=config.getInitParameter("weight");
      System.out.println("恭喜你成功获得名字对象"+name);
      System.out.println("恭喜你成功获得性别对象"+sex);
      System.out.println("恭喜你成功获得年龄对象"+age);
      System.out.println("恭喜你成功获得身高对象"+height);
      System.out.println("恭喜你成功获得体重对象"+weight);
    }
    public void destroy() {
    // TODO Auto-generated method stub
    super.destroy();
    System.out.println("执行完毕后进行释放cpu的内存");
  }
  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //浏览器默认是get ====doget的方法
    //设置编码格式
    response.setCharacterEncoding("UTF-8");
    //设置浏览访问的是html
    response.setContentType("text/html;charset=UTF-8");
    //.getAttribute获得动态数据
    HttpSession session =request.getSession();
    Object oj =session.getAttribute("time");
    //有number代表时间
    //定义一个变量来说明你要到计时多少时间;
    int number=5;
    /*
     * 采用if(){}else()if()语句
     */
        if (oj==null) {
          session.setAttribute("time", number);
        } else {
          number =Integer.parseInt(oj+"");
          session.setAttribute("time", number!=0?number-1:5);
          /*
           * 浏览器要跳转的那个页面
           * response.sendRedirect("ServletB");
           */
          if(number==0)response.sendRedirect("ServletB");
        }
        /*
         * response.getWriter().write("<h1>还剩下"+number+"S</h1>");
          response.getWriter().write("还有多少时间可以跳转页面呀");
          在浏览器上哟显示
         */
        response.getWriter().write("<h1>还剩下"+number+"S</h1>");
        response.getWriter().write("<h1>还有多少时间可以跳转页面呀</h1>");
        //页面每秒刷一次页面
        response.addHeader("refresh", "1");
  }
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }
}
package Com.Com.As_2.com.HuBin;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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 ServletB
 */
@WebServlet("/ServletB")
public class ServletB extends HttpServlet {
  private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletB() {
        super();
       System.out.println("ServlectA=====ServlectB");
       System.out.println("已完成跳转的页面");
    }
  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // response  回复  当浏览器根据地址发送请求servlet.servlet
        //使用response对象回复对象
        //设置servlet发送的数据支撑HTML格式
        response.setContentType("text/html");
        //设置发送servlet 浏览html格式 utf-8
        response.setCharacterEncoding("UTF-8");
        //response  回复  内容/数据/消息
        String info="<h1>HELLOW WORLD JSP</h1>";
        String info1="<h1 style='color:red'>页面跳转成功哦</h1>"
            + "<h1 style='color:geeen;font-size:45px'>你好,欢迎来到servletA正在运行中"
            + "\"<span style='color:red'> java jsp</span></h1>"
            +"<h1>作业内容</h1>\r\n" + 
            "<h1>新建一个项目</h1>"
            + "<h1>创建两个Servlet:<h1><hr>"
            + "<h2>ServletAA,ServletBB</h2>\r\n" + 
            "<h1>当浏览器访问ServletA的时候,ServletA5秒之后跳转至ServletB</h1>,\r\n" + 
            "<h1 style='color:red'>浏览器上要显示五秒的倒计时过程</h1>\r\n" + 
            "<h1>思路:《1》首先建立一个项目为Day05,在这个项目中建立servlectA,servlectB.<hr>"
            + "《2》这个案例的重点在于SevlectA五秒后跳转ServlectB.那要用什么方法呢<hr>"
            + "《3》有二种方案:方案一,控制台打印倒计时五秒输入过程。<hr>"
            + "方案二,在ServlectA中设置以下内容" 
            +"<1>创建项目后设置 \r\\n"
            + "1 response.setCharacterEncoding(\"UTF-8\")设置编码格式;<br>\r\n" + 
            " 2 response.setContentType(\"text/html;charset=UTF-8\")设置浏览的html格式;<br>"+"r"
            +" 3 response.sendRedirect(\"Servlet1\");跳转到那个Servlect<br>"
            + " 4 response.addHeader(\"refresh\", \"1\");每隔1秒去将页面刷新页面<hr></h1>"
            +"本案例还可以实现连续页面的跳转 从servletD--servletA--servletB";
        /*
         * //方法一 OutputStream os =response.getOutputStream(); os.write(info.getBytes());
         * os.write(info1.getBytes());
         */
        //方法二
        PrintWriter pw=response.getWriter();
        pw.print(info);
        pw.print(info1);
  }
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }
}
package Com.Com.As_2.com.HuBin;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.Random;
import javax.servlet.ServletContext;
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 ServletD
 */
@WebServlet("/ServletD")
public class ServletD extends HttpServlet {
  private static final long serialVersionUID = 1L;
  /**
   * @see HttpServlet#HttpServlet()
   */
  public ServletD() {
    super();
    // TODO Auto-generated constructor stub
  }
  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // 使用response对象回复对象
    // 设置servlet发送的数据支撑HTML格式
    response.setContentType("text/html");
    // 设置发送servlet 浏览html格式 utf-8
    response.setCharacterEncoding("UTF-8");
    // 获取动态数据 ServletContext 共享静态数据 动态数据
    // sa=getServletContext();
    ServletContext sa = getServletContext();
    // 设置动态数据
    sa.setAttribute("pq", "篮球");
    sa.setAttribute("zq", "足球");
    String a = (String) sa.getAttribute("pq");
    String b = (String) sa.getAttribute("zq");
    response.getWriter().append("<h1>ServletB获得动态数据篮球</h1><hr>" + a);
    response.getWriter().append("<h1>ServletB获得动态数据足球球</h1><hr>" + b);
    /*
     * response.sendRedirect("Servlet1"); int i=(int)(Math.random()*900000+100000);
     * int r=(int)(Math.random()*9000+1000); int c=(int)(Math.random()*900+100);
     * System.out.println("@@@@"+(new Random().nextInt(900000)+100000));
     * 
     * 设置随机
     * 
     * System.out.println(new Random().nextInt(100));
     * System.out.println(Math.random());
     * 
     * PrintWriter pw =response.getWriter(); pw.
     * print("你的支付宝到账1000000元,需要的码号为:<h1 style='color:red ;background-color:yellow; font-size:34px'>"
     * +i+"</h1>,打死也不说   \"<hr>\";"); pw.
     * print("你的QQ到账1000万元,需要的码号为:<h2 style='color:red ;background-color:yellow'>"
     * +c+"</h2>,打死也不说   \"<hr>\";");
     * pw.print("你的微信到账100万元,需要的码号为:<span style='color:green'>"+r+"</span>,打死也不说");
     * pw.print("你的手机支付宝到账1000万<span style='color :red'>"+i+"</span>");
     */
    response.sendRedirect("ServletA");
    try {
      Thread.sleep(5000);
      Connection conn = Time.time();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }
}
package Com.Com.As_2.com.HuBin;
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 ServletE
 */
@WebServlet("/ServletE")
public class ServletE extends HttpServlet {
  private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletE() {
        super();
        System.out.println("ServletE 案例使用HttpServletRequest对象让我们去学习吧!");
    }
  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //设置编码格式 ===UTF-8
    //设置浏览器访问html格式
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");
    //得到url地址请求
    String AA=request.getRequestURI().toString();
    System.out.println("使用的方法request.getRequestURI().toString()");
    System.out.println(AA);
    //得到请求数据
    String BB=request.getRequestURI();
    System.out.println("使用的方法getRequestURI()");
    System.out.println(BB);
    //得到请求的url地址中附加参数
    String CC=request.getQueryString();
    System.out.println(CC);
    System.out.println("使用的方法request.getQueryString()");
    //得到来访者的IP地址
    String DD=request.getLocalAddr();
    System.out.println(DD);
    System.out.println("使用的方法request.getLocalAddr()");
    //得到来访者的主机名
    String EE=request.getRemoteHost();
    System.out.println(EE);
    System.out.println("使用的方法request.getRemoteHost()");
    //得到来访者端口号
    int FF=request.getRemotePort();
    System.out.println(FF);
    System.out.println("使用的方法request.getRemotePort()");
    //得到请求url地址使用方法(重要)
    String GG=request.getMethod();
    System.out.println("GG");
    System.out.println("使用的方法request.getMethod()");
    //获取web服务器的主机名
    String HH=request.getLocalAddr();
    System.out.println("使用的方法request.getLocalAddr()");
    //获取web的服务·端口号
    int II =request.getLocalPort();
    System.out.println(II);
    System.out.println("使用的方法request.getLocalPort()");
  }
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }
}
package Com.Com.As_2.com.HuBin;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Map.Entry;
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.swing.text.html.parser.Entity;
/**
 * Servlet implementation class ServletF
 */
@WebServlet("/ServletF")
public class ServletF extends HttpServlet {
  private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletF() {
        super();
        System.out.println("ServletF真在运行中");
    }
  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    //设置发送servlet 浏览html格式 utf-8
    response.setCharacterEncoding("UTF-8");
    String aa=request.getParameter("name");
    String bb=request.getParameter("age");
    String cc=request.getParameter("phone");
    System.out.println("获得浏览器数据为"+aa+bb+cc);
    /*
     * 第一种方式
     */
    String [] ss=request.getParameterValues("hobby");
    System.out.println(Arrays.toString(ss));
    /*
     * 第二种方式集合
     */
    Map<String,String[]> map =request.getParameterMap();
    for (Entry<String, String[]> entry : map.entrySet()) {
      String name =entry.getKey();
      String[] values=entry.getValue();
    System.out.println(name+"%%"+Arrays.toString(values));  
    }
    /*
     * 第三种方式
     */
    Enumeration<String>e =request.getParameterNames();
    while (e.hasMoreElements()) {
      String name= e.nextElement();
      if (name.equals("hobby")) {
        String[]str =request.getParameterValues(name);
        System.out.println(name+";"+Arrays.toString(str));
      } else {
          String value =request.getParameter(name);
          System.out.println(name+";"+value);
      }
    }
  }
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }
}
package Com.Com.As_2.com.HuBin;
import java.sql.Connection;
public class Time {
  public static int time=60*60*60;
  static Connection time() {
    while (time>0) {
      time--;
      try {
        Thread.sleep(1000);
        int hh=time/1/1%1;
        int mm=time/60%1;
        int ss=time%6;
        if(hh==0 &&mm==0 && ss==0) {
          break;
        }
        System.out.println("0小时"+hh+"Сʱ"+mm+"分钟"+ss+"秒");
      } catch (InterruptedException e) {
        // TODO: handle exception
    }finally {
      System.out.println("正在跳转页面哦 ServlectB");
      System.out.println(".......真在跳转页面 ");
    }
    }
    return null;
  }
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    time();
  }
}
package Com.Com.As_2.com.HuBin;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class Servlect4
 */
@WebServlet("/Servlect4")
public class Servlect4 extends HttpServlet {
  private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Servlect4() {
        super();
        System.out.println("Servlect4在运行中");
        // 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
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");
    /*
     * 获得动态数据
     */
    PrintWriter pw =response.getWriter();
    String a=(String)((ServletRequest) response).getAttribute("sf");
    String b=(String)((ServletRequest) response).getAttribute("name");
    String c=(String)((ServletRequest) response).getAttribute("h");
    pw.print("<h1>收到Servlect3的内容,回复消息任务完成,获得/Servlect3的数据</h1>"+a);
    pw.print("<h1>收到Servlect3的内容,回复消息任务完成,获得/Servlect3的数据</h1>"+b);
    pw.print("<h1>收到Servlect3的内容,回复消息任务完成,获得/Servlect3的数据</h1>"+c);
  }
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }
package Com.Com.As_2.com.HuBin;
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 Servlet3
 */
@WebServlet("/Servlect3")
public class Servlet3 extends HttpServlet {
  private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Servlet3() {
        super();
        // TODO Auto-generated constructor stub
    }
  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");
    request.setAttribute("sf", "<h1 style='color;red'>手机</h1>");
    request.setAttribute("name", "<h1 style='color;red'中华有为</h1>");
    request.setAttribute("h", "<h1 style='color;red'无力而生</h1>");
    request.getRequestDispatcher("/Servlect4").forward(request, response);
  }
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }
}

运行结果


http://localhost:8080/Com.Com.As_2/ServlectF?name=shanghk&age=45&QQ=34455666443

http://localhost:8080/Com.Com.As_2/ServlectF?name=shanghk&age=45&QQ=34455666443

调用ServletA

实现连续页面跳转(从servletD--servletA--servletB)

 

继承.多态案例

/**

* 思路

* 1.首先,创造动物类

* 2 其次,分别创造猫类和狗类(他们继承于动物类)

* 3 再者,创建食物类:

* 4 再者,猫和狗都有自己不同的爱吃的食物(他们继承于食物类)

*  5.主人类(就可以将动物和对应的食物统一起来):

* 6 最后,方法的调用(测试)

* @author MZFAITHDREAM

*

package com.food;
public class Bone extends Food{
   public void showName() {
          System.out.println("食物:骨头");
      }
}
package com.food;
public class Carrot extends Food{
   public void showName() {
          System.out.println("食物:红萝卜");
      }
}
package com.food;
public class Fish extends Food{
   public void showName() {
          System.out.println("食物:鱼");
      }
}
package com.food;
public class Food {
  String name;
    public Food() {
    super();
    // TODO Auto-generated constructor stub
  }
  public Food(String name) {
    super();
    this.name = name;
  }
  public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    // 食物类里面让它有一个方法
    public void showName() {
      System.out.println("00000000000");
    }
}
package com.food;
public class potherlb  extends Food{
  @Override
  public void showName() {
    System.out.println("食物:potherlb");
  }
}
package com.food;
public class Vegetables  extends Food{
   public void showName() {
     System.out.println("食物:vegetables");
      }
}
package com.test;
import com.animal.Animal;
import com.animal.Cat;
import com.animal.Dog;
import com.animal.Duck;
import com.animal.Pig;
import com.animal.Rabbit;
import com.food.Bone;
import com.food.Carrot;
import com.food.Fish;
import com.food.Food;
import com.food.Vegetables;
import com.food.potherlb;
/**
 * 思路
 * 1.首先,创造动物类
 * 2 其次,分别创造猫类和狗类(他们继承于动物类)
 * 3 再者,创建食物类:
 * 4 再者,猫和狗都有自己不同的爱吃的食物(他们继承于食物类)
 *  5.主人类(就可以将动物和对应的食物统一起来):
 * 6 最后,方法的调用(测试)
 * @author MZFAITHDREAM
 *
 */
public class DuoTaiDemo {
  public static void main(String args[]) {
       Master master = new Master();
       master.feed(new Dog(), new Bone());
       System.out.println("===================AAAA========================");
       master.feed(new Cat(), new Fish());
       System.out.println("======================SSSS=====================");
       master.feed(new Duck(), new Vegetables());
       System.out.println("========================DDDD===================");
       master.feed(new Pig(), new potherlb());
       System.out.println("=========================FFFF==================");
       master.feed(new Rabbit(), new Carrot());
       System.out.println("++++++++++++++++++++++++++++++++++++++++");
       //父类向子类
        Animal a =new Cat();
        a.name="hihi";
        a.age="2";
        System.out.println(a.name);
        System.out.println(a.age);
        a.cry();
        a.eat();
        a.sleep();
        System.out.println("===========================================");
        Animal b =new Dog();
        b.cry();
        b.eat();
        b.sleep();
        Animal c =new Duck();
        c.eat();
        c.cry();
        c.sleep();
        System.out.println("===========================================");
        Animal e=new Pig();
        e.eat();
        e.cry();
        e.sleep();
        System.out.println("===========================================");
        Animal f =new Rabbit();
        f.cry();
        f.eat();
        f.sleep();
        System.out.println("===========================================");
        Food ab=new Bone();
        ab.showName();
        Food bc=new Carrot();
        bc.showName();
        Food cd=new Fish();
        cd.showName();
        Food de=new potherlb();
        de.showName();
        Food ef=new Vegetables();
        ef.showName();
        // hin方便,可以再试试
  }
}
package com.test;
import com.animal.Animal;
import com.food.Food;
public class Master {
  // 给动物喂食物,如果没有多态,他要写给猫喂食和给狗喂食两个方法
    // 有了多态,以后即使再来好多动物,用这一个函数就可以了
    public <sleep> void feed(Animal an, Food f ) {
        an.eat();
        f.showName();
    }
}


相关文章
|
7月前
|
缓存 Java 开发者
JSP 教程 之 JSP 隐式对象 10
JSP隐式对象是预定义的Java对象,如request、response、out、session、application等,直接供开发者使用。out对象是JspWriter实例,用于向网页输出内容,类似PrintWriter但有缓存处理和抛出IOException。exception对象保存了页面的异常信息,用于错误处理。
41 3
|
7月前
|
缓存 Java 开发者
JSP 教程 之 JSP 隐式对象 5
JSP教程介绍了九个隐式对象,如request、response、out、session、application等,无需声明即可直接使用。out对象是JspWriter实例,用于向网页输出内容,可配置是否缓存。它扩展了PrintWriter功能,处理缓存并可能抛出IOException。session对象基于HttpSession,用于跨客户端请求的会话跟踪。
31 1
|
6月前
|
SQL druid Java
javaweb案例实训之基于jsp和servlet的用户管理开发[增删改查及登录注销]
javaweb案例实训之基于jsp和servlet的用户管理开发[增删改查及登录注销]
44 0
|
7月前
|
缓存 Java 开发者
JSP 教程 之 JSP 隐式对象 9
JSP隐式对象是预定义的Java对象,无需声明即可直接使用。包括9大对象:request(HttpServletRequest)、response(HttpServletResponse)、out(JspWriter,用于输出到网页)、session(HttpSession)、application(ServletContext)、config(ServletConfig)、pageContext(PageContext,访问所有对象和命名空间)、page(页面实例,等同于Java的this)和Exception(异常对象)。
45 0
|
7月前
|
缓存 Java 对象存储
JSP 教程 之 JSP 隐式对象 8
JSP隐式对象是预定义的Java对象,如request、response、out等,无需声明即可直接使用。out对象是JspWriter实例,用于向response输出内容,支持print和println方法,可抛出IOException。pageContext对象代表整个JSP页面,提供访问页面信息和不同scope的对象,如request、response、session等,并有removeAttribute()方法管理页面属性。
37 0
|
7月前
|
缓存 Java 开发者
JSP 教程 之 JSP 隐式对象 7
JSP隐式对象是预定义的Java对象,无需声明即可使用。包括9大对象:request、response、out、session、application、config、pageContext、page和Exception。其中,out对象用于输出内容到网页,基于JspWriter,支持print和println方法。config对象是ServletConfig的实例,提供访问Servlet初始化参数的途径,如获取servlet名称。
34 0
|
7月前
|
缓存 Java 开发者
JSP 教程 之 JSP 隐式对象 6
JSP隐式对象是预定义的Java对象,无需声明即可直接使用。包括:request(HttpServletRequest)、response(HttpServletResponse)、out(JspWriter,用于输出到网页)、session(HttpSession)、application(ServletContext)、config(ServletConfig)、pageContext(PageContext)、page(当前页面对象)和Exception。out对象基于JspWriter,用于内容输出,提供print和println方法。
30 0
|
7月前
|
缓存 Java 开发者
JSP 教程 之 JSP 隐式对象 4
JSP隐式对象是预定义的Java对象,无需声明即可直接使用。包括9大对象:request、response、out、session、application、config、pageContext、page和Exception。其中,out对象基于JspWriter,用于向response写入内容,具有缓存管理功能,并扩展了PrintWriter的方法。常用方法有print()、println()用于输出各种类型数据,以及flush()刷新输出流。
41 0
|
2月前
|
Java 容器
【学习笔记】Jsp与Servlet技术
【学习笔记】Jsp与Servlet技术
81 0
|
4月前
|
SQL Java 数据库
jsp中使用Servlet查询SQLSERVER数据库中的表的信息,并且打印在屏幕上
该博客文章介绍了在JSP应用中使用Servlet查询SQL Server数据库的表信息,并通过JavaBean封装图书信息,将查询结果展示在Web页面上的方法。
jsp中使用Servlet查询SQLSERVER数据库中的表的信息,并且打印在屏幕上