• Servlet_1_基础


    路径记录自imooc:JAVA遇见HTML——Servlet篇 http://www.imooc.com/learn/269

    ---1-1 Servlet--------------------------------------------------

    Servlet:servlet是在服务器上运行的小程序。一个servlet就是一个java小程序,并且可以通过“请求-响应”编程模式来访问这个驻留在服务器内存里的servlet程序。

    ① Servlet就是JAVA 类
    ② Servlet是一个继承HttpServlet类的类
    ③ 这个在服务器端运行,用以处理客户端的请求

    ---1-2 Tomcat容器等级--------------------------------------------------

    Tomcat容器等级分为四个等级

      Servlet的容器管理Context容器,一个Context对应一个Web工程。

    1.Tomcat 容器
    2.  Container 容器
    3.    Engine 引擎容器
    4.      Host 主机
    5.          Servlet 容器(tomcat最低级别的容器)里面包含了一个或多个Context
          — Context (上下文,背景,环境) 一个Context对应一个Web项目
          —— Wrapper 容器里的封装部分

    ---1-3 手工编写第一个Servlet--------------------------------------------------

    1.自己编写的Servlet继承了HttpServlet类,一般只需覆盖doPost或者doGet方法,不必覆盖sevrvice( )方法.

      因为一个sevrvice( )方法会调用doPost或者doGet方法 

    2.HttpServlet类扩展了GenericServlet类,实现了GenericServlet类的抽象方法sevrvice( )

    3.HttpServlet类有两个sevrvice( )方法

    HelloServlet.java:

      response.setContentType("text/html;charset=utf-8");//指定输出文件类型"text/html",字符集charset为"utf-8"

    --------

    package servlet;

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

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

    public class HelloServlet extends HttpServlet {

     /**
      * Constructor of the object.
      */
     public HelloServlet() {
      super();
     }

     /**
      * Destruction of the servlet. <br>
      */
     public void destroy() {
      super.destroy(); // Just puts "destroy" string in log
      // Put your code here
     }

     /**
      * The doGet method of the servlet. <br>
      *
      * This method is called when a form has its tag value method equals to get.
      *
      * @param request the request send by the client to the server
      * @param response the response send by the server to the client
      * @throws ServletException if an error occurred
      * @throws IOException if an error occurred
      */
     public void doGet(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
            System.out.println("处理Get请求...");
      
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
      out.println("<HTML>");
      out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
      out.println("  <BODY>");
      out.println("<strong>Hello Servlet!</strong><br>");
      out.println("  </BODY>");
      out.println("</HTML>");
      out.flush();
      out.close();
     }

     /**
      * The doPost method of the servlet. <br>
      *
      * This method is called when a form has its tag value method equals to post.
      *
      * @param request the request send by the client to the server
      * @param response the response send by the server to the client
      * @throws ServletException if an error occurred
      * @throws IOException if an error occurred
      */
     public void doPost(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
      System.out.println("处理Post请求...");
      response.setContentType("text/html;charset=utf-8");//指定输出文件类型"text/html",字符集charset为"utf-8"
      PrintWriter out = response.getWriter();
      out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
      out.println("<HTML>");
      out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
      out.println("  <BODY>");
      out.println("<strong>Hello Servlet!</strong><br>");
      out.println("  </BODY>");
      out.println("</HTML>");
      out.flush();
      out.close();
     }

     /**
      * Initialization of the servlet. <br>
      *
      * @throws ServletException if an error occurs
      */
     public void init() throws ServletException {
      // Put your code here
     }

    }

    web.xml:

    servlet的URLlocalhost是服务器主机名,也可以是IP地址127.0.0.1;8080是tomcat服务器的端口号;

            helloapp是web工程的上下文地址ContexRoot(一般情况下与web工程名一致);最后是<url-pattern/>标签中的内容。

    a. <servlet>与<servlet-mapping>的<servlet-name>一一对应

    b.<url-pattern>/servlet/HelloServlet</url-pattern>  与JSP中的<a href="servlet/HelloServlet">Get方式请求HelloServlet</a>的URL路径一一对应

      /servlet/HelloServlet,"/"项目根目录

      <servlet>
        <description>This is the description of my J2EE component</description>
        <display-name>This is the display name of my J2EE component</display-name>
        <servlet-name>HelloServlet</servlet-name>//a
        <servlet-class>servlet.HelloServlet</servlet-class>
      </servlet>

      <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>//a
        <url-pattern>/servlet/HelloServlet</url-pattern>//定义
      </servlet-mapping>

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
        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_2_5.xsd">
      <display-name></display-name>
      
      <servlet>
        <description>This is the description of my J2EE component</description>
        <display-name>This is the display name of my J2EE component</display-name>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>servlet.HelloServlet</servlet-class>
      </servlet>
    
      <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/servlet/HelloServlet</url-pattern>
      </servlet-mapping>
          
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>

    index.jsp:

    1.Get方式请求HelloServlet

    <h1>使用MyEclipse创建Servlet小例子</h1>
        <hr>
        <a href="servlet/HelloServlet">Get方式请求HelloServlet</a><br>

    2.Post方式请求HelloServlet 注:编写Servlet的doPost方法时,需要抛出ServletExcpetion和IOException异常

     <form action="servlet/HelloServlet" method="post">
          <input type="submit" value="Post方式请求HelloServlet"/> 
       </form>

    <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'index.jsp' starting page</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
      </head>
      
      <body>
         <h1>使用MyEclipse创建Servlet小例子</h1>
        <hr>
        <a href="servlet/HelloServlet">Get方式请求HelloServlet</a><br>
    <!--Post方式提交--> <form action="servlet/HelloServlet" method="post"> <input type="submit" value="Post方式请求HelloServlet"/> </form> </body> </html>

    ---1-6 Servlet执行流程和声明周期--------------------------------------------------

    Servlet执行流程:此处以get方式举例:请求 -> <servlet-mapping>中的<url-pattern>-> <servlet-name> -> <servlet>中的<servlet-name> -> <servlet-class> ->servlet类中执行doGet()或doPost()。

    Get方式请求HelloServlet    --->    <a href="servlet/HelloServlet"> 超链接方式为GET方式

    通过a(url)找到b(name),通过b找到c(name)再找到d(class)

    如图:

    servlet生命周期

    servlet的生命周期分为三个阶段:
    1.初始化阶段,调用init()方法
    2.响应阶段,调用service()方法,决定调用doGet()还是doPost()
    3.终止阶段,调用destory()方法
    简单的可以概述为:
    servlet的生命周期包括的就是初始化,加载,实例化,服务和销毁

    ---1-9 Tomcat装载Servlet的三种情况--------------------------------------------------

    下列时刻Servlet容器装载Servlet:

    1.自动加载模式:Servlet容器启动时自动装载某些Servlet,实现它只需要在web.xml文件中<Servlet></Servlet>之间添加  如下代码:

          <load-on-startup>1</load-on-startup> 数字越小优先级越高
    2.servlet容器启动之后,客户端首次向服务器发出请求时。
    3.servlet类文件更新之后,重新装载servlet。

      servlet被装载之后servlet容器创建一个servlet实例并且调用servlet的init()方法进行初始化,在servlet的整个生命周期里,init()只被调用一次。

    注:server停止时才执行destory()

    package servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class TestServlet1 extends HttpServlet {
       
        
        
        /**
         * Constructor of the object.
         */
        public TestServlet1() {
            System.out.println("TestServlet1构造方法被执行....");
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            System.out.println("TestServlet1销毁方法被执行....");
        }
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println("TestServlet1的doGet()方法被执行...");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
            out.println("<HTML>");
            out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
            out.println("  <BODY>");
            out.println("<h1>大家好,我是TestServlet1!</h1>");
            out.println("  </BODY>");
            out.println("</HTML>");
            out.flush();
            out.close();
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println("TestServlet1的doPost()方法被执行...");
            doGet(request,response); //让doPost()执行与doGet()相同的操作。
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            // Put your code here
            System.out.println("TestServlet1的初始化方法被执行....");
        }
    
    }

    web.xml:

    验证自动装载:load-on-startup的数字越小优先级越高,优先加载

    <load-on-startup>2</load-on-startup>

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
        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_2_5.xsd">
      <display-name></display-name>
      <servlet>
        <description>This is the description of my J2EE component</description>
        <display-name>This is the display name of my J2EE component</display-name>
        <servlet-name>TestServlet1</servlet-name>
        <servlet-class>servlet.TestServlet1</servlet-class>
        <load-on-startup>2</load-on-startup>
      </servlet>
      <servlet>
        <description>This is the description of my J2EE component</description>
        <display-name>This is the display name of my J2EE component</display-name>
        <servlet-name>TestServlet2</servlet-name>
        <servlet-class>servlet.TestServlet2</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
    
    
      <servlet-mapping>
        <servlet-name>TestServlet1</servlet-name>
        <url-pattern>/servlet/TestServlet1</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>TestServlet2</servlet-name>
        <url-pattern>/servlet/TestServlet2</url-pattern>
      </servlet-mapping>    
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>

    ---1-10 Servlet与JSP内置对象的对应关系--------------------------------------------------

    注:out(type:jspWriter)与resq.getWriter(type:printWriter)实际上类型不一致

    ---1-11 Servlet获取表单数据--------------------------------------------------

    提交表单页reg.jsp:

    日期格式(dateFormat)参考-JAVA豆知识

    <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'reg.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
        <style type="text/css">
         .label{
              width: 20%    
         }
         .controler{
              width: 80%    
         }
       </style>  
       <script type="text/javascript" src="js/Calendar3.js"></script>
      </head>
      
      <body>
        <h1>用户注册</h1>
        <hr>
        <form name="regForm" action="servlet/RegServlet" method="post" >
                  <table border="0" width="800" cellspacing="0" cellpadding="0">
                    <tr>
                        <td class="lalel">用户名:</td>
                        <td class="controler"><input type="text" name="username" /></td>
                    </tr>
                    <tr>
                        <td class="label">密码:</td>
                        <td class="controler"><input type="password" name="mypassword" ></td>
                        
                    </tr>
                    <tr>
                        <td class="label">确认密码:</td>
                        <td class="controler"><input type="password" name="confirmpass" ></td>
                        
                    </tr>
                    <tr>
                        <td class="label">电子邮箱:</td>
                        <td class="controler"><input type="text" name="email" ></td>
                        
                    </tr>
                    <tr>
                        <td class="label">性别:</td>
                        <td class="controler"><input type="radio" name="gender" checked="checked" value="Male"><input type="radio" name="gender" value="Female"></td>
                        
                    </tr>
                   
                    <tr>
                        <td class="label">出生日期:</td>
                        <td class="controler">
                          <input name="birthday" type="text" id="control_date" size="10"
                          maxlength="10" onclick="new Calendar().show(this);" readonly="readonly" />
                        </td>
                    </tr>
                    <tr>
                        <td class="label">爱好:</td>
                        <td class="controler">
                        <input type="checkbox" name="favorite" value="nba"> NBA &nbsp;
                          <input type="checkbox" name="favorite" value="music"> 音乐 &nbsp;
                          <input type="checkbox" name="favorite" value="movie"> 电影 &nbsp;
                          <input type="checkbox" name="favorite" value="internet"> 上网 &nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td class="label">自我介绍:</td>
                        <td class="controler">
                            <textarea name="introduce" rows="10" cols="40"></textarea>
                        </td>
                    </tr>
                    <tr>
                        <td class="label">接受协议:</td>
                        <td class="controler">
                            <input type="checkbox" name="isAccept" value="true">是否接受霸王条款
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2" align="center">
                            <input type="submit" value="注册"/>&nbsp;&nbsp;
                            <input type="reset" value="取消"/>&nbsp;&nbsp;
                        </td>
                    </tr>
                  </table>
                </form>
      </body>
    </html>

    user.java:

    package entity;
    
    import java.util.Date;
    
    //用户实体类
    public class Users {
    
        private String username; //用户名
        private String mypassword; //密码
        private String email; //电子邮箱
        private String gender; //性别
        private Date birthday; //出生日期
        private String[] favorites; //爱好
        private String introduce; //自我介绍
        private boolean flag; //是否接受协议
        
        public Users()
        {
            
        }
        
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getMypassword() {
            return mypassword;
        }
        public void setMypassword(String mypassword) {
            this.mypassword = mypassword;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
        public String getGender() {
            return gender;
        }
        public void setGender(String gender) {
            this.gender = gender;
        }
        public Date getBirthday() {
            return birthday;
        }
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
        public String[] getFavorites() {
            return favorites;
        }
        public void setFavorites(String[] favorites) {
            this.favorites = favorites;
        }
        public String getIntroduce() {
            return introduce;
        }
        public void setIntroduce(String introduce) {
            this.introduce = introduce;
        }
    
        public boolean isFlag() {
            return flag;
        }
    
        public void setFlag(boolean flag) {
            this.flag = flag;
        }
    }

    servlet:

    package servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import entity.Users;
    
    public class RegServlet extends HttpServlet {
    
        /**
         * Constructor of the object.
         */
        public RegServlet() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            doPost(request,response);
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            request.setCharacterEncoding("utf-8");
            
            Users u = new Users();
            String username,mypassword,gender,email,introduce,isAccept;
            Date birthday;
            String[] favorites;
            
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try
            {
                username = request.getParameter("username");
                mypassword = request.getParameter("mypassword");
                gender = request.getParameter("gender");
                email = request.getParameter("email");
                introduce = request.getParameter("introduce");
                birthday = sdf.parse(request.getParameter("birthday"));
                if(request.getParameterValues("isAccpet")!=null)
                {
                  isAccept = request.getParameter("isAccept");
                }
                else
                {
                  isAccept = "false";
                }
                //用来获取多个复选按钮的值
                favorites = request.getParameterValues("favorite");
                u.setUsername(username);
                u.setMypassword(mypassword);
                u.setGender(gender);
                u.setEmail(email);
                u.setFavorites(favorites);
                u.setIntroduce(introduce);
                if(isAccept.equals("true"))
                {
                    u.setFlag(true);
                }
                else
                {
                    u.setFlag(false);
                }
                u.setBirthday(birthday);
                
                //把注册成功的用户对象保存在session中
                request.getSession().setAttribute("regUser", u);
                //跳转到注册成功页面
                request.getRequestDispatcher("../userinfo.jsp").forward(request,response);
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
            
            
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            // Put your code here
        }
    
    }

    跳转页面userinfo.jsp

    1. Servlet编辑并保存user对象:

                //把注册成功的用户对象保存在session中
                request.getSession().setAttribute("regUser", u); //跳转到注册成功页面
                request.getRequestDispatcher("../userinfo.jsp").forward(request,response);

    2.userInfo.jsp:

      通过javabean获取传递的user(modol)

      <jsp:useBean id="regUser" class="entity.Users" scope="session"/>  

        <jsp:getProperty name="regUser" property="gender"/>//property为user的property

    <%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%>
    
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'userinfo.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
        <style type="text/css">
         .title{
             width: 30%;    
             background-color: #CCC;
             font-weight: bold;
         }
         .content{
             width:70%;
             background-color: #CBCFE5;
         }
         
       </style>  
      </head>
      
      <body>
        <h1>用户信息</h1>
        <hr>
        <center>
         <jsp:useBean  id="regUser" class="entity.Users" scope="session"/>   
         <table width="600" cellpadding="0" cellspacing="0" border="1">
            <tr>
              <td class="title">用户名:</td>
              <td class="content">&nbsp;<jsp:getProperty name="regUser" property="username"/></td>
            </tr>
            <tr>
              <td class="title">密码:</td>
              <td class="content">&nbsp;<jsp:getProperty name="regUser" property="mypassword"/></td>
            </tr>
            <tr>
              <td class="title">性别:</td>
              <td class="content">&nbsp;<jsp:getProperty name="regUser" property="gender"/></td>
            </tr>
            <tr>
              <td class="title">E-mail:</td>
              <td class="content">&nbsp;<jsp:getProperty name="regUser" property="email"/></td>
            </tr>
            <tr>
              <td class="title">出生日期:</td>
              <td class="content">&nbsp;
                <% 
                   SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                   String date = sdf.format(regUser.getBirthday());
                   
                %>
                 <%=date%>
              </td>
            </tr>
            <tr>
              <td class="title">爱好:</td>
              <td class="content">&nbsp;
                <% 
                   String[] favorites = regUser.getFavorites();
                   for(String f:favorites)
                   {
                %>
                    <%=f%> &nbsp;&nbsp;
                <% 
                   }
                %>
              </td>
            </tr>
            <tr>
              <td class="title">自我介绍:</td>
              <td class="content">&nbsp;<jsp:getProperty name="regUser" property="introduce"/></td>
            </tr>
            <tr>
              <td class="title">是否介绍协议:</td>
              <td class="content">&nbsp;<jsp:getProperty name="regUser" property="flag"/></td>
            </tr>
         </table>
        </center>
      </body>
    </html>

    ---1-13 Servlet 路径跳转--------------------------------------------------

    绝对路径:<a href="<%=path%>/servlet/HelloServlet">访问HelloServlet!</a>

    相对路径:<a href="servlet/HelloServlet">访问HelloServlet!</a>

    方式1: 

      <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <!--url-pattern处必须以/开头,这里的/表示项目的根目录  -->
        <url-pattern>/servlet/HelloServlet</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/servlet/TestServlet</url-pattern>
      </servlet-mapping>

    方式2:

    <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'index.jsp' starting page</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
      </head>
      
      <body>
        <h1>Servlet路径跳转</h1>
        <hr>
        <!--使用相对路径访问HelloServlet -->
        <!-- /servlet/HelloServlet 第一个/表示服务器的根目录 -->
        <a href="servlet/HelloServlet">访问HelloServlet!</a><br>
        <!-- 使用绝对路径 访问HelloServlet,可以使用path变量:path变量表示项目的根目录-->
        <a href="<%=path%>/servlet/HelloServlet">访问HelloServlet!</a><br>
        <!--表单中action的URL地址写法,与超链接方式完全相同。 -->
        <a href="servlet/TestServlet">访问TestServlet,跳转到Test.jsp</a>
         
      </body>
    </html>

     

    请求重定向和服务器内部跳转

      //使用request.getContextPath获得上下文对象
          response.sendRedirect(request.getContextPath()+"/test.jsp");

    方式3:请求重定向

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

       //请求重定向方式跳转到test.jsp,当前路径是ServletPathDirection/servlet/
       //response.sendRedirect("test.jsp");//test.jsp为相对路径
      
     

    方式4:服务器内部跳转

      //test.jsp在根目录下
         //服务器内部跳转,这里的斜线表示项目的根目录 。../表示返回当前目录上一级
      //request.getRequestDispatcher("/test.jsp").forward(request, response);
      request.getRequestDispatcher("../test.jsp").forward(request, response);
     }

    ---1-14 Servlet-阶段案例-------------------------------------------------

    package servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.po.Users;
    
    public class LoginServlet extends HttpServlet {
    
        /**
         * Constructor of the object.
         */
        public LoginServlet() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            doPost(request,response);
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            Users u = new Users();
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            u.setUsername(username);
            u.setPassword(password);
            //判断用户名和密码是否合法
            if(u.getUsername().equals("admin")&&u.getPassword().equals("admin"))
            {
                response.sendRedirect(request.getContextPath()+"/login_success.jsp");
            }
            else
            {
                response.sendRedirect(request.getContextPath()+"/login_failure.jsp");
            }
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            // Put your code here
        }
    
    }
  • 相关阅读:
    整理:分页存储过程整理
    净利润-流通市值比率”与公司估值
    常见7种股票底部形态(图解)
    nginx
    移动成本分布1
    浅谈公开信息检索和判断能力
    股票技术分析 成交量与换手率专题
    成份股和成份股指数
    股票底部形态初探
    筹码拉抬派发法
  • 原文地址:https://www.cnblogs.com/charles999/p/6707591.html
Copyright © 2020-2023  润新知