美文网首页19-23年 学习笔记
【Java Web 程序开发】学习笔记

【Java Web 程序开发】学习笔记

作者: Du1in9 | 来源:发表于2020-05-13 11:30 被阅读0次

    参考文献:https://book.douban.com/subject/26581849/
    完整源代码:https://pan.baidu.com/s/1IQUsLuFwOj_QXglHPPmqug 提取码:2647


    第一章 XML基础
    1.1 XML概述
    1.1.1 W3C组织介绍
    https://wiki.hk.xileso.top/wiki/W3C
    1.1.2 什么是XML
    https://baike.baidu.com/item/%E5%8F%AF%E6%89%A9%E5%B1%95%E6%A0%87%E8%AE%B0%E8%AF%AD%E8%A8%80/2885849?fromtitle=xml&fromid=86251&fr=aladdin
    1.1.3 XML与HTML的比较
    https://blog.csdn.net/m18633778874/article/details/79028240/
    1.2 XML语法
    例1-1 元素定义,注释
    book.xml

    <?xml version="1.0" encoding="GB2312"?>
    <!--注释信息-->
    <书架>
        <书>
            <书名>程序员的自我修养</书名>
            <价格>23.5元</价格>
        </书>
        <书>
            <书名>肖生克的救赎</书名>
            <价格>20.5</价格>
        </书>
    </书架> 
    

    建议用notepad++编写,浏览器打开



    例1-2 特殊字符

    <书名>&lt;程序员的自我修养&gt;</书名>
    

    例1-3 CDATA区
    java.xml

    <?xml version="1.0"?>
    <java>
    <![CDATA[
        if(a>b&&b>c)
            max=a;
    ]]>
    </java> 
    

    1.3 DTD约束
    例1-4 DTD约束
    Note.xml
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE note SYSTEM "Note.dtd">
    <note>
    <to>George</to>
    <from>John</from>
    <heading>Reminder</heading>
    <body>Don't forget the meeting!</body>
    </note> 
    

    Note.dtd

    <?xml version="1.0" encoding="GB2312"?>
    <!ELEMENT note (to, from, heading, body)>
    <!ELEMENT to (#PCDATA)>
    <!ELEMENT from (#PCDATA)>
    <!ELEMENT heading (#PCDATA)>
    <!ELEMENT body (#PCDATA)> 
    

    1.4 Schema 约束
    例1-5 使用名称空间引入XML Schema文档
    book1.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <书架 xmlns="http://www.it315.org/xmlbook/schema"
    xmlns:demo="http://www.it315.org/demo/schema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.it315.org/xmlbook/schema http://www.it315.org/xmlbook.xsd
    http://www.it315.org/demo/schema http://www.it315.org/demo.xsd">
    
    <书>
    <书名>JavaScript网页开发</书名>
    <作者>木丁西</作者>
    <售价 demo:币种=”人民币”>28.00元</售价>
    </书>
    </书架>
    

    例1-6 不使用名称空间引入XML Schema文档
    book2.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <书架 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="xmlbook.xsd">
    <书>
    <书名>JavaScript网页开发</书名>
    <作者>张孝祥</作者>
    <售价>28.00元</售价>
    </书>
    </书架>
    

    第二章 Tomcat 开发Web站点
    2.1 Web开发相关知识
    2.1.1 B/S架构和C/S架构
    https://blog.csdn.net/sea_snow/article/details/81187804
    2.1.2 通信协议
    https://www.cnblogs.com/xhwy/archive/2012/03/03/2378293.html
    2.1.3 Web资源
    https://www.cnblogs.com/linkworld/p/7573043.html
    例2-1 dynamic.html
    现在的时间是:
    <script type="text/javascript">
    document.write(new Date());
    </script>
    

    2.2 安装Tomcat
    2.2.1 Tomcat简介
    https://baike.baidu.com/item/tomcat/255751?fr=aladdin
    2.2.2 Tomcat安装和启动
    个人不建议配置tomcat8,后面用Myclipse做项目不方便
    https://blog.csdn.net/oqqKen12345/article/details/82839914
    例2-2 dynamic.jsp
    Now the time is:<br>
    <%=new java.util.Date()%>
    

    (运行Tomcat,jsp文件放在Apache-Tomcat-8.5.45\webapps\Me\文件夹,再访问http://localhost:8080/Me/dynamic.jsp即可)
    2.3 发布Web应用
    2.3.1 什么是Web应用
    https://www.jianshu.com/p/ddbe852179fe
    2.3.2 配置Web应用虚拟目录(选做)
    https://blog.csdn.net/baolibin528/article/details/38034101
    2.3.3 配置Web应用默认页面(选做)
    https://blog.csdn.net/weixin_43740680/article/details/92086233
    2.3.4 Tomcat的管理平台
    https://blog.csdn.net/cuijiying/article/details/78526982

    2.4 Eclipse中配置Tomcat服务器
    https://jingyan.baidu.com/article/219f4bf7b57b20de442d38ac.html
    第三章 HTTP协议
    3.1 HTTP概述
    3.1.1 HTTP介绍
    https://www.runoob.com/http/http-intro.html
    3.1.2 HTTP1.0和HTTP1.1
    https://blog.csdn.net/FU250/article/details/90763223
    3.1.3 HTTP消息
    https://blog.csdn.net/huangjin0507/article/details/52170460
    3.2 HTTP请求信息
    https://blog.csdn.net/u010256388/article/details/68491509/
    例3-1 GET.html
    <html>
    <body>
    <form action="" method="get">
        姓名:<input type="text" name="name" style="width:150px"/><p/>
        年龄:<input type="text" name="age" style="width:150px"/><p/>
        <input type="submit" value="提交"/><p/>
    </form>
    </body>
    </html>
    

    例3-2 POST.html

    <html>
    <body>
    <form action="" method="post">
        姓名:<input type="text" name="name" style="width:150px"/><p/>
        年龄:<input type="text" name="age" style="width:150px"/><p/>
        <input type="submit" value="提交"/><p/>
    </form>
    </body>
    </html>
    

    中文乱码咋办?如图:


    打开Tomcat,访问http://localhost:8080/Three/GET.html,输入Jack,40,再看请求头消息

    打开Tomcat,访问http://localhost:8080/Three/POST.html,输入Jack,40,再看请求头消息

    3.3 HTTP响应信息
    3.3.1 HTTP响应状态行
    https://blog.csdn.net/zjs_csdns/article/details/89004295?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase
    3.3.2 HTTP响应消息头
    https://www.runoob.com/http/http-header-fields.html
    3.4 HTTP其他头字段
    3.4.1 通用头字段
    https://blog.csdn.net/u010369338/article/details/69566058/
    3.4.2 实体头字段
    https://www.iteye.com/blog/zengguo1988-283702
    第四章 Servlet技术
    4.1 Servlet开发入门
    4.1.1 Servlet接口
    https://www.cnblogs.com/weibanggang/p/9464307.html
    4.1.2 实现第一个Servlet程序
    先找到servlet-api.jar,设置环境变量
    set classpath=%classpath%;E:\apache-tomcat-8.5.45\apache-tomcat-8.5.45\lib\servlet-api.jar
    

    例4-1 HelloWorldServlet.java

    package Java_Web.Four;//这是包名,也就是文件夹的路径,我这里是E:\Java_Web\Four
    import java.io.*;
    import javax.servlet.*;
    
    public class HelloWorldServlet extends GenericServlet{
      public void service(ServletRequest request,ServletResponse response) throws ServletException,IOException{
        PrintWriter out = response.getWriter();
        out.println("XXXXX");
      }
    }
    

    编译

    javac HelloWorldServlet.java
    

    在webapps文件夹新建xxx\WEB-INF\classes目录,然后将包放进去



    在WEB-INF中,新建web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0">
     <servlet>
           <servlet-name>HelloWorldServlet</servlet-name>
           <servlet-class>Java_Web.Four.HelloWorldServlet</servlet-class>
        </servlet>
     <servlet-mapping>
           <servlet-name>HelloWorldServlet</servlet-name>
            <url-pattern>/HelloWorldServlet</url-pattern>
        </servlet-mapping>
    </web-app>
    <!--
    <servlet>用于注册Servlet
    <servlet-name>HelloWorldServlet</servlet-name>指定servlet的名称为HelloWorldServlet,你也可以改成其他的
    <servlet-class>java_web.HelloWorldServlet</servlet-class>指定servlet完整的类名,要和你编写的.java 文件的类名相同
    <servlet-mapping>用于映射servlet对外访问虚拟路径,它的<servlet-name>名字必须和<servlet>中的<servlet-name>相同
    <url-pattern>是指定该servlet的虚拟路径,该路径以正斜杠(/)开头,表示当前web应用程序的根目录
    -->
    

    启动Tomcat,访问http://localhost:8080/Four/HelloWorldServlet即可


    ①如果出现以下情况,多半是web.xml书写格式有误,一点点失误就会报错,巨坑



    ②因为每次编译都要设置环境变量比较麻烦,可以把语句存在一个文本里,下次直接套用,例如我的就是:

    cd /d E:\apache-tomcat-8.5.45\apache-tomcat-8.5.45\webapps\chapter04\WEB-INF\classes\Java_Web\Four
    set classpath=%classpath%;E:\apache-tomcat-8.5.45\apache-tomcat-8.5.45\lib\servlet-api.jar
    javac xxx.java
    

    4.1.3 Servlet的生命周期
    https://www.runoob.com/servlet/servlet-life-cycle.html
    4.2 Servlet高级应用
    4.2.1 HttpServlet
    例4-3
    RequestMethodServlet.java

    package Java_Web.Four;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    
    public class RequestMethodServlet extends HttpServlet{
      public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        PrintWriter out = response.getWriter();
        out.println("this is doGetmethod");
      }
      public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        PrintWriter out = response.getWriter();
        out.println("this is doPostmethod");
      }
    }
    

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0">
     <servlet>
           <servlet-name>RequestMethodServlet</servlet-name>
           <servlet-class>Java_Web.Four.RequestMethodServlet</servlet-class>
        </servlet>
     <servlet-mapping>
           <servlet-name>RequestMethodServlet</servlet-name>
            <url-pattern>/RequestMethodServlet</url-pattern>
        </servlet-mapping>
    </web-app>
    

    开启tomcat,访问http://localhost:8080/chapter04/RequestMethodServlet


    在webapp\chapter04目录下新建form.html
    <form action="/chapter04/RequestMethodServlet" method="post">
        姓名:<input type="text" name="name" style="width:150px"/><p/>
        密码:<input type="text" name="psw" style="width:150px"/><p/>
        <input type="submit" value="提交"/><p/>
    </form>
    

    访问http://localhost:8080/chapter04/form.html

    点击提交,会显示“this is doPostmethod”,所以我们知道采用POST方式请求Servlet时,会自动调用doPost( )方法
    4.2.2 使用MyEclipse开发Servlet
    新建Web项目




    新建Servlet程序




    对Servlet的doPost( )和doGet( )方法进行修改

    如果servers窗口不见了,点击windows--show views--others

    直接在Myclipse里运行



    4.2.3 Servlet虚拟路径的映射
    https://blog.csdn.net/qq_24042659/article/details/82967306
    4.3 ServletConfig和ServletContext
    4.3.1 ServletConfig接口

    Servlet运行期间,通常需要一些辅助信息,可以在web.xml中使用<init-param>进行配置
    <param-name>表示参数名称,<param-value>表示参数值

    新建Servlet程序,配置web.xml

    <servlet>
        <display-name>TestServlet02</display-name>
        <servlet-name>TestServlet02</servlet-name>
        <servlet-class>Java_Web.Four.TestServlet02</servlet-class>
        <init-param>
          <param-name> encoding </param-name>
          <param-value> UTF-8 </param-value>
        </init-param>
    </servlet>
    

    TestServlet02.java

    package Java_Web.Four;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    
    public class TestServlet02 extends HttpServlet{
      public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        PrintWriter out = response.getWriter();
        ServletConfig config=this.getServletConfig();
        String param=config.getInitParameter("encoding");
        out.println("encoding="+param);
      }
      public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
          this.doGet(request,response);
      }
    }
    

    编译,运行,访问



    可以看出,ServletConfig对象可以获得web.xml中的参数信息
    4.3.2 ServletContext接口
    ①获取初始化参数
    例4-6
    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0">
      
      <servlet>
        <display-name>TestServlet03</display-name>
        <servlet-name>TestServlet03</servlet-name>
        <servlet-class>Java_Web.Four.TestServlet03</servlet-class>
      </servlet>
      <context-param>
        <param-name> companyName </param-name>
        <param-value> alibaba </param-value>
      </context-param>
      <context-param>
        <param-name> address </param-name>
        <param-value> earth </param-value>
      </context-param>
      <servlet-mapping>
        <servlet-name>TestServlet03</servlet-name>
        <url-pattern>/TestServlet03</url-pattern>
      </servlet-mapping>
    </web-app>
    

    TestServlet03.java

    package Java_Web.Four;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class TestServlet03 extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
              PrintWriter out = response.getWriter();
              // 得到ServletContext对象
             ServletContext context = this.getServletContext();
             // 得到包含所有初始化参数名的Enumeration对象
             Enumeration<String> paramNames = context.getInitParameterNames();
              // 遍历所有的初始化参数名,得到相应的参数值,打印到控制台
             out.println("all the paramName and paramValue are following:"+"<br>");
              // 遍历所有的初始化参数名,得到相应的参数值并打印
             while (paramNames.hasMoreElements()) {
                String name = paramNames.nextElement();
                String value = context.getInitParameter(name);
                out.println(name + ": " + value);
                  out.println("<br>");
             }
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
              this.doGet(request, response);
        }
    }
    

    编译,运行,访问



    ②实现共享数据
    例4-7
    TestServlet04.java

    package Java_Web.Four;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class TestServlet04 extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            ServletContext context = this.getServletContext();
             // 通过setAttribute()方法设置属性值
            context.setAttribute("data", "this servlet save data");
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request, response);
        }
    }
    

    例4-8
    TestServlet05.java

    package Java_Web.Four;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class TestServlet05 extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         PrintWriter out = response.getWriter();
            ServletContext context = this.getServletContext();
                    // 通过getAttribute()方法获取属性值
            String data = (String) context.getAttribute("data");
            out.println(data);
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request, response);
        }
    }
    

    编译,启动,分别访问,可知ServletContext存储数据可被多个Servlet共享
    ③读取Web应用资源文件
    在classes目录下新建资源文件itcast.properties

    Company=abcdefg
    Address=earth
    

    例4-9
    TestServlet06.java

    package Java_Web.Four;
    import java.io.*;
    import java.util.Properties;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class TestServlet06 extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            ServletContext context = this.getServletContext();
            PrintWriter out = response.getWriter();
            InputStream in = context
                    .getResourceAsStream("/WEB-INF/classes/itcast.properties");
            Properties pros = new Properties();
            pros.load(in);
            out.println("Company=" + pros.getProperty("Company") + "<br>");
            out.println("Address=" + pros.getProperty("Address") + "<br>"); 
    }
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request, response);
        }
    }
    

    第五章 请求和响应
    5.1 HttpServletResponse对象
    5.1.1 发送状态码
    5.1.2 发送响应消息头
    5.1.3 发送响应消息体
    ①getOutputStream()方法
    ②getWriter()方法
    例5-1
    PrintServlet.java

    package Java_Web.Five;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class PrintServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String data="hello_motherfucker!";
            OutputStream out=response.getOutputStream();// 获取输出流对象
            out.write(data.getBytes());                     // 输出字符串信息
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request,response);
        }
    }
    

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0">
      <servlet>
        <display-name>PrintServlet</display-name>
        <servlet-name>PrintServlet</servlet-name>
        <servlet-class>Java_Web.Five.PrintServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>PrintServlet</servlet-name>
        <url-pattern>/PrintServlet</url-pattern>
      </servlet-mapping>
    </web-app>
    

    5.2 HttpServletResponse应用
    5.2.1 中文输出乱码问题
    法一:例5-3
    ChineseServlet.java
    package Java_Web.Five;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class ChineseServlet extends HttpServlet {
        public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
            response.setCharacterEncoding("utf-8");//设置字符编码方式
            String data="中国";
            PrintWriter out = response.getWriter();   
            out.println(data);
        }
        public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
            doGet(request,response);
        }
    }
    

    修改浏览器编码:https://jingyan.baidu.com/article/cd4c2979f2a664756e6e60db.html

    法二:例5-4
    ChineseServlet.java
    package Java_Web.Five;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class ChineseServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String data="中国";
             response.setContentType("text/html;charset=utf-8");//设置HttpServletResponse和浏览器编码为utf-8
            PrintWriter out = response.getWriter();
            out.println(data);
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request,response);
        }
    }
    

    5.2.2 网页定时刷新并跳转
    例5-5
    RefreshServlet.java

    package Java_Web.Five; 
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class RefreshServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
             // 2秒后刷新并跳转到指定网页
             response.setHeader("Refresh","2;URL=https://www.jianshu.com/u/32aab16373de");
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    例5-6
    RefreshServlet.java

    package Java_Web.Five; 
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class RefreshServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {      
            response.setHeader("Refresh","1");// 每隔1秒定时刷新当前页面
            response.getWriter().println(new java.util.Date());// 输出当前时间
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    5.2.3 禁止浏览器缓存页面
    例5-7
    CacheServlet.java

    package Java_Web.Five; 
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class CacheServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8"); 
            response.setDateHeader("Expires",0);
            response.setHeader("Cache-Control","no-cache"); 
            response.setHeader("Pragma","no-cache");  
            PrintWriter out = response.getWriter();
            out.println("本次响应的随机数为:" + Math.random());
            out.println("<form action='NotServlet'" + "method='POST'>" +
                "第一个参数:<input type='text' name='p1'><br>" +
                "第二个参数:<textarea name='p2'></textarea><br>" +
                "<input type='submit' value='提交'> " +
                "</form>");
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    5.2.4 请求重定向
    例5-8
    login.html

    <!--把表单内容提交到chapter05工程下的LoginServlet-->
    <form action="/chapter05/LoginServlet" method="post">
        用户名: <input type="text" name="username" /><br> 
        密  码: <input type="password" name="password" /><br> 
        <input type="submit" value="登录" />
    </form>
    

    welcome.html

    <html>
        <head>
            <title>Insert title here</title>
        </head>
        <body>
            欢迎你 ♂ 登录成功!
        </body>
    </html>
    

    LoginServlet.java

    package Java_Web.Five; 
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class LoginServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            // 用HttpServletRequest对象的getParameter()方法获取用户名和密码
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            // 假设用户名和密码分别为:Du1in9和123
            if (("Du1in9").equals(username) &&("123").equals(password)) {
                response.sendRedirect("/chapter05/welcome.html");// 如果用户名和密码正确,重定向到 welcome.html
            } 
            else {
                response.sendRedirect("/chapter05/login.html");// 如果用户名和密码错误,重定向到login.html
            }
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    


    5.3 HttpServletRequest对象
    5.3.1 获取请求行信息
    例5-11
    RequestLineServlet.java
    package Java_Web.Five; 
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class RequestLineServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            // 获取请求行的相关信息
            out.println("getMethod : " + request.getMethod() + "<br>");
            out.println("getRequestURI : " + request.getRequestURI() + "<br>");
            out.println("getQueryString : " + request.getQueryString() + "<br>");
            out.println("getProtocol : " + request.getProtocol() + "<br>");
            out.println("getContextPath : " + request.getContextPath() + "<br>");
            out.println("getPathInfo : " + request.getPathInfo() + "<br>");
            out.println("getPathTranslated : " + request.getPathTranslated()+ "<br>");
            out.println("getServletPath : " + request.getServletPath() + "<br>");
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    5.3.2 获取请求消息头
    例5-12
    RequestHeadersServlet.java

    package Java_Web.Five; 
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Enumeration;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class RequestHeadersServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            // 获取请求消息中所有头字段
            Enumeration headerNames = request.getHeaderNames();
            // 使用循环遍历所有请求头,并通过getHeader()方法获取一个指定名称的头字段
            while (headerNames.hasMoreElements()) { 
                String headerName = (String) headerNames.nextElement();
                out.print(headerName + " : " + request.getHeader(headerName)+ "<br>");
            }
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    利用Referer请求头防止“盗链”
    例5-13
    download.html
    <html>
        <head>
            <title>Insert title here</title>
        </head>
        <body>
            <a href="/chapter05/DownManagerServlet">download</a>
        </body>
    </html>
    

    例5-14
    DownManagerServlet.java

    package Java_Web.Five;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class DownManagerServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            String referer = request.getHeader("referer");// 获取referer头的值
            String sitePart = "http://" + request.getServerName();// 获取访问地址
            // 判断referer头是否为空,这个头的首地址是否以sitePart开始的
            if (referer != null && referer.startsWith(sitePart)) {
                out.println("Downloading ...");// 处理正在下载的请求
            } 
            else {// 非法下载请求跳转到download.html页面
                RequestDispatcher rd = request.getRequestDispatcher("/download.html");
                rd.forward(request, response);
            }
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    5.3.3 获取请求消息体
    例5-15
    form.html

    <form action="/chapter05/RequestBodyServlet" method="post">
        用户名:<input type="text" name="username"><br>
        密  码:<input type="password" name="password"><br>
        <input type="submit" value="提交">
    </form>
    

    RequestBodyServlet.java

    package Java_Web.Five;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class RequestBodyServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            
            InputStream in = request.getInputStream();// 获取输入流对象
            byte[] buffer = new byte[1024]; // 定义1024个字节的数组
            StringBuilder sb = new StringBuilder(); // 创建StringBuilder对象
            int len;
            while ((len = in.read(buffer)) != -1) {// 循环读取数组中的数据
                sb.append(new String(buffer, 0, len));
            }
            System.out.println(sb);
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    5.4 HttpServletRequest应用
    5.4.1 获取请求参数
    form.html

    <form action="/chapter05/RequestParamsServlet" method="POST">
        用户名:<input type="text" name="username"><br>
        密 码:<input type="password" name="password"><br>
        爱 好:
        <input type="checkbox" name="hobby" value="sing">唱
        <input type="checkbox" name="hobby" value="dance">跳
            <input type="checkbox" name="hobby" value="rap">rap
        <input type="checkbox" name="hobby" value="basketball">篮球<br>
        <input type="submit" value="提交">
    </form>
    

    RequestParamsServlet.java

    package Java_Web.Five; 
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class RequestParamsServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            String name = request.getParameter("username");
            String password = request.getParameter("password");
            System.out.println("用户名:" + name);
            System.out.println("密   码:" + password);
            String[] hobbys= request.getParameterValues("hobby");
            System.out.print("爱好:");
            for (int i = 0; i < hobbys.length; i++) {
                System.out.print(hobbys[i]+" ");
            }
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    5.4.2 请求参数的中文乱码问题
    RequestParamsServlet.java中设置中文编码即可

    request.setCharacterEncoding("gbk");
    


    5.4.3 获取网络连接信息
    RequestNetServlet.java

    package Java_Web.Five; 
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class RequestNetServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            response.setContentType("text/html ;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("getRemoteAddr : " + request.getRemoteAddr() + "<br>");
            out.println("getRemoteHost : " + request.getRemoteHost() + "<br>");
            out.println("getRemotePort : " + request.getRemotePort() + "<br>");
            out.println("getLocalAddr : " + request.getLocalAddr() + "<br>");
            out.println("getLocalName : " + request.getLocalName() + "<br>");
            out.println("getLocalPort : " + request.getLocalPort() + "<br>");
            out.println("getServerName : " + request.getServerName() + "<br>");
            out.println("getServerPort : " + request.getServerPort() + "<br>");
            out.println("getScheme : " + request.getScheme() + "<br>");
            out.println("getRequestURL : " + request.getRequestURL() + "<br>");
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    5.4.4 通过Request对象传递数据
    setAttribute()方法,getAttribute()方法,removeAttribute()方法,getAttributeNames()方法
    5.5 RequestDispatcher对象的应用
    5.5.1 RequestDispatcher接口
    5.5.2 请求转发
    RequestForwardServlet.java

    package Java_Web.Five; 
    import java.io.IOException;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class RequestForwardServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            // 将数据存储到request对象中
            request.setAttribute("company", "阿里巴巴");        
            RequestDispatcher dispatcher = request.getRequestDispatcher("/ResultServlet");
            dispatcher.forward(request, response);
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    ResultServlet.java

    package Java_Web.Five;  
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class ResultServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();// 获取PrintWriter对象用于输出信息
            String company = (String) request.getAttribute("company");// 获取request请求对象中保存的数据
            if (company != null) {
                out.println("公司名称:" + company + "<br>");
            }
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    然后web.xml中配置他俩的映射,访问



    5.5.3 请求包含
    IncludingServlet.java

    package Java_Web.Five; 
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class IncludingServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            PrintWriter out = response.getWriter();
            RequestDispatcher rd = request.getRequestDispatcher("/IncludedServlet?p1=fuck");
            out.println("before including" + "<br>");
            rd.include(request, response);
            out.println("after including" + "<br>");
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    IncludedServlet.java

    package Java_Web.Five;  
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class IncludedServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            // 设置响应时使用的字符编码
            response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            PrintWriter out = response.getWriter();
            out.println("中国" + "<br>");
            out.println("URI:" + request.getRequestURI() + "<br>");
            out.println("QueryString:" + request.getQueryString() + "<br>");
            out.println("parameter p1:" + request.getParameter("p1") + "<br>");
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    然后web.xml中配置他俩的映射,访问


    第六章 会话及其会话技术
    6.1 会话概述
    https://www.cnblogs.com/luoxn28/p/5513789.html
    6.2 Cookie对象
    6.2.1 什么是Cookie
    https://blog.csdn.net/qq_17452939/article/details/80901985
    6.2.2 Cookie API
    https://blog.csdn.net/u011541946/article/details/90273259
    6.3 Cookie之显示用户上次访问时间
    源代码编译时报错,因为date.toLocaleString()已过时,我用DateFormat.format(Date date)进行了取代
    LastAccessServlet.java
    package Java_Web.Six; 
    import java.io.IOException;
    import java.util.Date;
    import java.text.SimpleDateFormat;
    import javax.servlet.ServletException;
    import javax.servlet.http.*;
    public class LastAccessServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            // 指定服务器输出内容的编码方式UTF-8,防止发生乱码
            response.setContentType("text/html;charset=utf-8");
            String lastAccessTime = null;
            // 获取所有的cookie,并将这些cookie存放在数组中
            Cookie[] cookies = request.getCookies();
            for (int i = 0; cookies != null && i < cookies.length; i++) {
                // 如果cookie的名称为lastAccess,则获取该cookie的值
                if ("lastAccess".equals(cookies[i].getName())) {
                    lastAccessTime = cookies[i].getValue();
                    break;
                }
            }
            // 判断是否存在名称为lastAccess的cookie
            if (lastAccessTime == null) {
                response.getWriter().print("您是首次访问本站!!!");
            } 
            else {
                 response.getWriter().print("您上次的访问时间是: " + lastAccessTime);
            }
            // 创建cookie,将当前时间作为cookie的值发送给客户端
            String currentTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
            Cookie cookie = new Cookie("lastAccess", currentTime);
            // 发送 cookie
            response.addCookie(cookie);
        }
       protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
            // TODO Auto-generated method stub
            this.doPost(req, resp);
        }
    }
    

    6.4 Session对象
    6.4.1 什么是Session
    https://blog.csdn.net/q_sea__/article/details/79430215
    6.4.2 HttpSession API
    https://blog.csdn.net/u011541946/article/details/90442127
    6.4.3 Session 超时管理
    https://www.cnblogs.com/d0minic/p/12258853.html
    6.5 Session之实现购物车
    ListBookServlet.java

    package Java_Web.Six; 
    import java.io.*;
    import java.util.*;
    import javax.servlet.http.*;
    import javax.servlet.ServletException;
    
    class Book implements Serializable {
        private static final long serialVersionUID = 1L;
        private String id;
        private String name;
        public Book() {
        }
        public Book(String id, String name) {
            this.id = id;
            this.name = name;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
    class BookDB {
        private static Map<String, Book> books = new LinkedHashMap<String, Book>();
        static {
            books.put("1", new Book("1", "javaweb开发"));
            books.put("2", new Book("2", "jdbc开发"));
            books.put("3", new Book("3", "java基础"));
            books.put("4", new Book("4", "struts开发"));
            books.put("5", new Book("5", "spring开发"));
        }
        // 获得所有的图书
        public static Collection<Book> getAll() {
            return books.values();
        }
        // 根据指定的id获得图书
        public static Book getBook(String id) {
            return books.get(id);
        }
    }
    public class ListBookServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
        public void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter out = resp.getWriter();
            Collection<Book> books = BookDB.getAll();
            out.write("本站提供的图书有:<br>");
            for (Book book : books) {
                String url = "/chapter06/PurchaseServlet?id=" + book.getId();
                out.write(book.getName() + "<a href='" + url 
                        + "'>点击购买</a><br>");
            }
        }
    }
    

    PurchaseServlet.java
    换共有类:

    public class PurchaseServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
        @SuppressWarnings("unchecked")
        public void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
            // 获得用户购买的商品
            String id = req.getParameter("id");
            if (id == null) {
                // 如果id为null,重定向到ListBookServlet页面
                String url = "/chapter06/ListBookServlet";
                resp.sendRedirect(url);
                return;
            }
            Book book = BookDB.getBook(id);
            // 创建或者获得用户的Session对象
            HttpSession session = req.getSession();
            // 从Session对象中获得用户的购物车
            List<Book> cart = (List) session.getAttribute("cart");
            if (cart == null) {
                // 首次购买,为用户创建一个购物车(List集合模拟购物车)
                cart = new ArrayList<Book>();
                // 将购物城存入Session对象
                session.setAttribute("cart", cart);
            }
            // 将商品放入购物车
            cart.add(book);
            // 创建Cookie存放Session的标识号
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            cookie.setMaxAge(60 * 30);
            cookie.setPath("/chapter06");
            resp.addCookie(cookie);
            // 重定向到购物车页面
            String url = "/chapter06/CartServlet";
            resp.sendRedirect(url);
        }
    }
    

    CartServlet.java
    换共有类:

    public class CartServlet extends HttpServlet {
        @SuppressWarnings("unchecked")
        public void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter out = resp.getWriter();
            // 变量cart引用用户的购物车
            List<Book> cart = null;
            // 变量pruFlag标记用户是否买过商品
            boolean purFlag = true;
            // 获得用户的session
            HttpSession session = req.getSession(false);
            // 如果session为null,purFlag置为false
            if (session == null) {
                purFlag = false;
            } 
            else {
                // 获得用户购物车
                cart = (List) session.getAttribute("cart");
                // 如果用的购物车为null,purFlag置为false
                if (cart == null) {
                    purFlag = false;
                }
            }
            /*如果purFlag为false,表明用户没有购买图书 重定向到ListServlet页面*/
            if (!purFlag) {
                out.write("对不起!您还没有购买任何商品!<br>");
            } else {
                // 否则显示用户购买图书的信息
                out.write("您购买的图书有:<br>");
                double price = 0;
                for (Book book : cart) {
                    out.write(book.getName() + "<br>");
                }
            }
        }
    }
    

    访问http://localhost:8080/chapter06/ListBookServlet.java



    6.6 Session之实现用户登录
    Login.html
    <form name="reg" action="/chapter06/LoginServlet" method="post">
        用户名: <input name="username" type="text" /><br/>
        密码:   <input name="password" type="password" /><br/>
                <input type="submit" value="提交" id="bt" />
    </form>
    

    IndexServlet.java

    package Java_Web.Six; 
    import java.io.*;
    import java.util.*;
    import javax.servlet.http.*;
    import javax.servlet.ServletException;
    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;
        }   
    }
    public class IndexServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            // 解决乱码问题
            response.setContentType("text/html;charset=utf-8");
            // 创建或者获取保存用户信息的Session对象
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");
            if (user == null) {
                response.getWriter().print("您还没有登录,请<a href='/chapter06/Login.html'>登录</a>");
            } 
            else {
                response.getWriter().print("您已登录,欢迎你," + user.getUsername() + "!");
                response.getWriter().print("<a href='/chapter06/LogoutServlet'>退出</a>");
                // 创建Cookie存放Session的标识号
                Cookie cookie = new Cookie("JSESSIONID", session.getId());
                cookie.setMaxAge(60 * 30);
                cookie.setPath("/chapter06");
                response.addCookie(cookie);
            }
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    LoginServlet.java
    换共有类:

    public class LoginServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            PrintWriter pw = response.getWriter();
            //假设正确的用户名 是Du1in9 密码是123
            if (("Du1in9").equals(username) && ("123").equals(password)) {
                User user = new User();
                user.setUsername(username);
                user.setPassword(password);
                request.getSession().setAttribute("user", user);
                response.sendRedirect("/chapter06/IndexServlet");
            } 
            else {
                pw.write("用户名或密码错误,登录失败");
            }
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    LogoutServlet.java
    换共有类:

    public class LogoutServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            // 将Session对象中的User对象移除
            request.getSession().removeAttribute("user");
            response.sendRedirect("/chapter06/IndexServlet");
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    访问http://localhost:8080/chapter06/IndexServlet



    6.7 Session之实现验证码
    Login.html
    <form name="reg" action="/chapter06/LoginServlet" method="post">
            用户名: <input name="username" type="text" /><br /> 
            密码: <input name="password" type="password" /><br /> 
            验证码:<input type="text" name="check_code"> 
    <img src="/chapter06/CheckServlet"><br>
            <input type="submit" value="提交" id="bt" />
    </form>
    

    CheckServlet.java

    package Java_Web.Six; 
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.awt.*;
    import java.awt.image.*;
    import javax.imageio.ImageIO;
    public class CheckServlet extends HttpServlet{
        private static int WIDTH = 60; //验证码图片宽度
        private static int HEIGHT = 20; //验证码图片高度
        public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{     
            HttpSession session = request.getSession();
            response.setContentType("image/jpeg");
            ServletOutputStream sos = response.getOutputStream();
            //设置浏览器不要缓存此图片
            response.setHeader("Pragma","No-cache");
            response.setHeader("Cache-Control","no-cache");
            response.setDateHeader("Expires", 0);
            //创建内存图象并获得其图形上下文
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); 
            Graphics g = image.getGraphics();
            //产生随机的认证码
            char [] rands = generateCheckCode();
            //产生图像
            drawBackground(g);
            drawRands(g,rands);
            //结束图像的绘制过程,完成图像
            g.dispose();
            //将图像输出到客户端
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(image, "JPEG", bos);
            byte [] buf = bos.toByteArray();
            response.setContentLength(buf.length);
            //下面的语句也可写成:bos.writeTo(sos);
            sos.write(buf);
            bos.close();
            sos.close();
            //将当前验证码存入到Session中
            session.setAttribute("check_code",new String(rands));
            //直接使用下面的代码将有问题,Session对象必须在提交响应前获得
            //request.getSession().setAttribute("check_code",new String(rands));
        }
           //生成一个4字符的验证码
        private char [] generateCheckCode()
        {
            //定义验证码的字符表
            String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            char [] rands = new char[4];
            for(int i=0; i<4; i++)
            {
                int rand = (int)(Math.random() * 36);
                rands[i] = chars.charAt(rand);
            }
            return rands;
        }
        private void drawRands(Graphics g , char [] rands)
        {
            g.setColor(Color.BLACK);
            g.setFont(new Font(null,Font.ITALIC|Font.BOLD,18));
            //在不同的高度上输出验证码的每个字符     
            g.drawString("" + rands[0],1,17);
            g.drawString("" + rands[1],16,15);
            g.drawString("" + rands[2],31,18);
            g.drawString("" + rands[3],46,16);
            System.out.println(rands);
        }
        private void drawBackground(Graphics g)
        {
            //画背景
            g.setColor(new Color(0xDCDCDC));
            g.fillRect(0, 0, WIDTH, HEIGHT);
            //随机产生120个干扰点
            for(int i=0; i<120; i++)
            {
                int x = (int)(Math.random() * WIDTH);
                int y = (int)(Math.random() * HEIGHT);
                int red = (int)(Math.random() * 255);
                int green = (int)(Math.random() * 255);
                int blue = (int)(Math.random() * 255);
                g.setColor(new Color(red,green,blue));      
                g.drawOval(x,y,1,0);
            }
        }
    }
    

    LoginServlet.java

    package Java_Web.Six; 
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.*;
    import javax.servlet.http.*;
    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;
        }   
    }
    public class LoginServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String checkCode = request.getParameter("check_code");
            String savedCode = (String) request.getSession().getAttribute("check_code");
            PrintWriter pw = response.getWriter();
            if (("Du1in9").equals(username) && ("123").equals(password)&& checkCode.equals(savedCode)) {
                User user = new User();
                user.setUsername(username);
                user.setPassword(password);
                request.getSession().setAttribute("user", user);
                response.sendRedirect("/chapter06/IndexServlet");
            } 
            else if (checkCode.equals(savedCode)) {
                pw.write("用户名或密码错误,登录失败");
            } 
            else {
                pw.write("验证码错误");
            }
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    访问http://localhost:8080/chapter06/Login.html



    第七章 JSP技术
    7.1 JSP概述
    7.1.1 什么是JSP
    https://www.runoob.com/jsp/jsp-intro.html
    simple.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"%>
    <html>
    <title>boy next ♂ door</title>
    <body>
        当前访问时间是:
        <%out.print(new java.util.Date().toLocaleString());%>
    </body>
    </html>
    

    访问http://localhost:8080/chapter07/simple.jsp

    7.1.2 JSP运行原理
    https://zhidao.baidu.com/question/476724087.html
    7.2 JSP基本语法
    JSP注释信息不会被发送到客户瑞
    comment.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"%>
    <html>
    <head>
    <title>Insert title here</title>
    </head>
    <body>
    <%-- 这个是注释内容 --%>
    </body>
    </html>
    

    7.3 JSP指令
    ①修改报错页面
    page.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"%>
    <html>
    <head>
    <title>Insert title here</title>
    </head>
    <body>
    <%int a=1/0;%>
    </body>
    </html>
    

    page1.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8" errorPage="error.jsp"%>
    <html>
    <head>
    <title>Insert title here</title>
    </head>
    <body>
    <%int a=1/0;%>
    </body>
    </html>
    

    error.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"%>
    <html>
    <head>
    <title>Insert title here</title>
    </head>
    <body>
    <h2>抱歉♂服务器出现故障♂正在解决♂请稍候。。。。。。。</h2>
    </body>
    </html>
    

    ②通用报错页面
    web.xml

      <error-page>
        <error-code>404</error-code>
        <location>/404.jsp</location>
      </error-page>
      <error-page>
        <error-code>500</error-code>
        <location>/500.jsp</location>
      </error-page>
    

    404.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"%>
    <html>
    <head>
    <title>Insert title here</title>
    </head>
    <body>
    <h2>404:你他妈在访问什么玩意</h2>
    </body>
    </html>
    

    500.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"%>
    <html>
    <head>
    <title>Insert title here</title>
    </head>
    <body>
    <h2>通用500错误处理页面</h2>
    </body>
    </html>
    

    访问http://localhost:8080/chapter07/page.jsp


    访问http://localhost:8080/chapter07/abcdefg.jsp

    7.4 JSP隐式对象
    7.4.1 隐式对象
    7.4.2 out对象
    out.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"%>
    <html>
    <head>
    <title>Insert title here</title>
    </head>
    <body>
    <%
       out.println("first line<br>");
       response.getWriter().println("second line<br>");
    %>  
    </body>
    </html>
    

    out1.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8" buffer="0kb"%>
    <html>
    <head>
    <title>Insert title here</title>
    </head>
    <body>
    <%
       out.println("first line<br>");
       response.getWriter().println("second line<br>");
    %>  
    </body>
    </html>
    

    7.4.3 pageContext对象
    pageContext.jsp

    <%
        HttpServletRequest req=(HttpServletRequest)pageContext.getRequest();
        String x = request.getRemoteAddr();
        out.println("本机的IP地址为:"+x);      
    %>
    

    访问http://127.0.0.1:8080/chapter07/pageContext.jsp


    pageContextDemo.jsp
    <%
        pageContext.setAttribute("company", "阿里巴巴",pageContext.PAGE_SCOPE);
        Object x = pageContext.getAttribute("company",pageContext.PAGE_SCOPE);
        out.println("公司名称为:" + x);
    %>
    

    7.4.4 exception对象
    price.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"%>
    <%@ page errorPage="execp.jsp"%>
    <%
        String p=request.getParameter("price");
        double x=Double.parseDouble(p);
        out.println("Total price:"+x*5);
    %>
    

    execp.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"%>
    <%@ page isErrorPage="true"%>
    <%
        out.println("exception.toString:"+"<br>");
        out.println(exception.toString());
        out.println("<br>");
        out.println("exception.getMessage():"+"<br>");
        out.println(exception.getMessage());
    %>
    

    访问http://localhost:8080/chapter07/price.jsp?price=3.5


    访问http://localhost:8080/chapter07/price.jsp?price=Du1in9

    7.5 JSP标签
    7.5.1 <jsp:include>标签
    included.jsp
    <%@ page contentType="text/html;charset=GB2312"%>
    <%Thread.sleep(2000);%>
    你~<br>
    <jsp:include page="included1.jsp" flush="true" />
    

    included1.jsp

    <%@ page contentType="text/html;charset=GB2312"%>
    <%Thread.sleep(2000);%>
    是~<br>
    <jsp:include page="included2.jsp" flush="true" />
    

    included2.jsp

    <%@ page contentType="text/html;charset=GB2312"%>
    <%Thread.sleep(2000);%>
    猪~<br>
    

    访问http://localhost:8080/chapter07/included.jsp


    7.5.2 <jsp:forward>标签
    jspforward.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"%>
    <jsp:forward page="welcome.jsp" />
    

    welcome.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"%>
    <html>
    <title>Insert title here</title>
    <body>
        你好,欢迎进入首页,当前访问时间是:
        <%out.print(new java.util.Date());%>
    </body>
    </html>
    

    第八章 JavaBean组件
    8.1 JavaBean概述
    https://blog.csdn.net/keep12moving/article/details/92666633
    8.2 反射(略)
    8.3 内省(略)
    8.4 JSP标签访问JavaBean
    8.4.1 <jsp:useBean>标签
    Manager.java
    package Java_Web.Eight; 
    class Employee {
        private String company;
        public String getCompany() {
            return company;
        }
        public void setCompany(String company) {
            this.company = company;
        }
    }
    public class Manager extends Employee {
        private double bonus;
        public double getBonus() {
            return bonus;
        }
        public void setBonus(double bonus) {
            this.bonus = bonus;
        }
    }
    

    useBean.jsp

    <%@ page language="java" pageEncoding="GBK"%>
    <html>
    <body>
        <jsp:useBean id="manager" scope="page" class="Java_Web.Eight.Manager" />
    </body>
    </html>
    

    8.4.2 <jsp:setProperty>标签
    ①property属性单独使用
    setProperty.jsp

    <%@ page language="java" pageEncoding="GBK" import="Java_Web.Eight.Manager"%>
    <html>
    <body>
            <jsp:useBean id="manager" class="Java_Web.Eight.Manager" />
            <jsp:setProperty name="manager" property="bonus" />
            <%
                manager = (Manager) pageContext.getAttribute("manager");
                out.write("bonus属性的值为:"+manager.getBonus());
            %>
    </body>
    </html>
    

    访问http://localhost:8080/chapter08/setProperty.jsp?bonus=500


    修改Manager.java
    package Java_Web.Eight; 
    class Employee {
        private String company;
        public String getCompany() {
            return company;
        }
        public void setCompany(String company) {
            this.company = company;
        }
    }
    public class Manager extends Employee {
        private double bonus=500;
        public double getBonus() {
            return bonus;
        }
        public void setBonus(double bonus) {
            this.bonus = bonus;
        }
    }
    

    访问http://localhost:8080/chapter08/setProperty.jsp


    修改setProperty.jsp
    <%@ page language="java" pageEncoding="GBK" import="Java_Web.Eight.Manager"%>
    <html>
    <body>
            <jsp:useBean id="manager" class="Java_Web.Eight.Manager" />
            <jsp:setProperty name="manager" property="*" />
            <%
                manager = (Manager) pageContext.getAttribute("manager");
                out.write("bonus属性的值为:"+manager.getBonus()+"<br />");
                out.write("company属性的值为:"+manager.getCompany());
            %>
    </body>
    </html>
    

    访问http://localhost:8080/chapter08/setProperty.jsp?bonus=600&company=阿里巴巴


    ②property属性和param属性混合使用
    setProperty.jsp
    <body>
            <form action="">
                  公司<input  type="text" name="corp"> <br/>
                  奖金<input  type="text" name="reward"> <br/>  
                      <input  type="submit" value="提交">     
            </form>
           <jsp:useBean id="manager" class="Java_Web.Eight.Manager" />
           <jsp:setProperty name="manager" property="company" param="corp" />
           <jsp:setProperty name="manager" property="bonus" param="reward" />
           <%
                manager = (Manager) pageContext.getAttribute("manager");
                out.write("bonus属性的值为:"+manager.getBonus()+"<br />");
                out.write("company属性的值为:"+manager.getCompany());
           %>
    </body>
    

    ③property属性和value属性混合使用
    setProperty.jsp

    <body>
            <jsp:useBean id="manager" class="Java_Web.Eight.Manager" />
            <jsp:setProperty name="manager" property="company" value="阿里巴巴" />
            <jsp:setProperty name="manager" property="bonus" value="1000.0" />
            <%
                manager = (Manager) pageContext.getAttribute("manager");
                out.write("bonus属性的值为:"+manager.getBonus()+"<br />");
                out.write("company属性的值为:"+manager.getCompany()); 
            %>
    </body>
    

    setProperty.jsp

    <%@ page language="java" pageEncoding="GBK" import="Java_Web.Eight.Manager" import="java.util.Date" import="java.text.SimpleDateFormat"%>
    <html>
    <body>
        <% 
            Date date = new Date();
            pageContext.setAttribute("date", date);
        %>    
        <jsp:useBean id="manager" class="Java_Web.Eight.Manager" />
        <jsp:setProperty name="manager" property="birthday" value="${date }" />
        <%
            manager = (Manager) pageContext.getAttribute("manager");
            String formatDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(manager.getBirthday());
            out.write("birthday属性的值为:"+formatDate);
        %>
    </body>
    </html>
    

    Manager.java

    package Java_Web.Eight;
    import java.util.Date;
    class Employee {
        private String company;
        public String getCompany() {
            return company;
        }
        public void setCompany(String company) {
            this.company = company;
        }
    }
    public class Manager extends Employee {
        private double bonus = 500.0;
        private Date birthday;
        public Date getBirthday() {
            return birthday;
        }
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
        public double getBonus() {
            return bonus;
        }
        public void setBonus(double bonus) {
            this.bonus = bonus;
        }
    }
    

    8.4.3 <jsp:getProperty>标签
    User.java

    package Java_Web.Eight;
    public class User {
        private String name;
        private String gender;
        private String education;
        private String email;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getGender() {
            return gender;
        }
        public void setGender(String gender) {
            this.gender = gender;
        }
        public String getEducation() {
            return education;
        }
        public void setEducation(String education) {
            this.education = education;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
    }
    

    login.jsp

    <body>
           <form action="/chapter08/userInfo.jsp" method="post">
              姓名:<input type="text" name="name" /> <br />
              性别:<input type="radio" name="gender" value="man" checked="checked" />man
                   <input type="radio" name="gender" value="woman" />woman   <br/>
              学历:<select name="education">
                        <option value="select">请选择</option>
                        <option value="high_school_student">high_school_student</option>
                        <option value="undergraduate">undergraduate</option>
                        <option value="graduate">graduate</option>
                        <option value="doctor">doctor</option>
                    </select>  <br/>
              邮箱:<input type="text" name="mail" /> <br />
                   <input type="submit" value="提交"/>
           </form>
    </body>
    

    userInfo.jsp

    <body>
            <jsp:useBean id="user" class="Java_Web.Eight.User" />
            <jsp:setProperty name="user" property="*" />
            <jsp:setProperty name="user"  property="email" param="mail" />
            姓名:<jsp:getProperty name="user" property="name" />  <br />
            性别:<jsp:getProperty name="user" property="gender" /> <br />
            学历:<jsp:getProperty name="user" property="education" /> <br />
            邮箱:<jsp:getProperty name="user" property="email" /> 
    </body>
    

    8.5 BeanUtils 工具(略)
    第九章 JSP开发模型
    9.1 JSP开发模型
    https://blog.csdn.net/zl5230/article/details/105851338
    9.2 案例
    Calculator.java

    package Java_Web.Nine;
    import java.math.BigDecimal;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.regex.Pattern;
    public class Calculator {
        // firstNum表示第一个运算数
        private String firstNum;
        // secondNum表示第二个运算数
        private String secondNum;
        // operator表示运算符
        private char operator;
        // error用于封装错误信息
        private Map<String, String> errors = new HashMap<String, String>();
    
        // 属性setter和getter方法
        public Map<String, String> getErrors() {
            return errors;
        }
        public void setErrors(Map<String, String> errors) {
            this.errors = errors;
        }
        public String getFirstNum() {
            return firstNum;
        }
        public void setFirstNum(String firstNum) {
            this.firstNum = firstNum;
        }
        public String getSecondNum() {
            return secondNum;
        }
        public void setSecondNum(String secondNum) {
            this.secondNum = secondNum;
        }
        public char getOperator() {
            return operator;
        }
        public void setOperator(char operator) {
            this.operator = operator;
        }
        /*calculate()方法根据传入的运算数和符号进行运算*/
        public String calculate() {
            BigDecimal result = null;
            BigDecimal first = new BigDecimal(firstNum);
            BigDecimal second = new BigDecimal(secondNum);
            switch (operator) {
            case '+':
                result = first.add(second);
                break;
            case '-':
                result = first.subtract(second);
                break;
            case '*':
                result = first.multiply(second);
                break;
            case '/':
                if ("0".equals(secondNum)) {
                    throw new RuntimeException("除数不能为0!");
                }
                result = first.divide(second);
                break;
            default:
                break;
            }
            return result.toString();
        }
        /*validate()方法用于验证表单传入的数据是否合法*/
        public boolean validate() {
            // flag是标识符,如果数据合法flag为true,反之为false
            boolean flag = true;
            Pattern p = Pattern.compile("\\d+");// 正则表达式,匹配数字
            if (firstNum == null || "".equals(firstNum)) { // 判断不能为空
                errors.put("firstNum", "第一个运算数不能为空");
                flag = false;
            } else if (!p.matcher(firstNum).matches()) { // 判断不能为非数字
                errors.put("firstNum", "第一个运算数必须为数字");
                flag = false;
            }
            if (secondNum == null || "".equals(secondNum)) { 
                errors.put("secondNum", "第二个运算数不能为空");
                flag = false;
            } else if (!p.matcher(secondNum).matches()) {
                errors.put("secondNum", "第二个运算数必须为数字");
                flag = false;
            }
            return flag;
        }
    }
    

    calculator.jsp

    <%@ page language="java" pageEncoding="GBK" import="java.util.Map"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <title>calculator</title>
        </head>
        <body>
            <jsp:useBean id="calculator" class="Java_Web.Nine.Calculator" />
            <jsp:setProperty property="*" name="calculator" />
            <%
                if (calculator.validate()) {
            %>
            <font color="green">运算结果: 
            <jsp:getProperty property="firstNum" name="calculator" />
            <jsp:getProperty property="operator" name="calculator" />
            <jsp:getProperty property="secondNum" name="calculator" />
            =<%=calculator.calculate()%></font>
            <%
                } 
                else {
                    Map<String, String> errors = calculator.getErrors();
                    pageContext.setAttribute("errors", errors);
                }
            %>
            <form action="" method="post">
                第一个运算数:<input type="text" name="firstNum" /> 
                <font color="red">${errors.firstNum}</font> <br />
                运算符: <select name="operator" style="margin-left: 100px">
                            <option value="+">+</option>
                            <option value="-">-</option>
                            <option value="*">*</option>
                            <option value="/">/</option>
                        </select> <br /> 
                第二个运算数: <input type="text" name="secondNum" /> 
                <font color="red">${errors.secondNum}</font> <br /> 
                <input type="submit" value="计算" />
            </form>
        </body>
    </html>
    

    相关文章

      网友评论

        本文标题:【Java Web 程序开发】学习笔记

        本文链接:https://www.haomeiwen.com/subject/ycygnhtx.html