为了账号安全,请及时绑定邮箱和手机立即绑定

jee之servlet基础学习笔记

标签:
Java

jee之servlet学习笔记

1.Servlet概述

答: 详见下图:图片描述
2.Tomcat容器等级
答: 详见下图:图片描述
3.使用Myeclipse编写Servlet
答:详见下图:如果表单提交时用的是get请求,那么我们就重写doGet()方法!图片描述
(1)在jsp页面使用get方式或post方式提交数据给后台servlet

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

(2)后台的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;

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");
        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
    }

}

(3)注册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>

记得:myeclipse会自动生成;
localhost是服务器主机名,也可以是IP地址127.0.0.1;8080是tomcat服务器的端口号;helloapp是web工程的上下文地址ContexRoot(一般情况下与web工程名一致);最后是<url-pattern/>标签中的内容。
4.Servlet执行流程和声明周期
答:详见下图:图片描述图片描述
servlet生命周期阶段包括初始化、加载、实例化、服务和销毁。
编写Servlet的doPost方法时,需要抛出ServletExcpetion和IOException异常。
5.Tomcat装载Servlet的三种情况
答:详见下图:记住servlet是长期服务器保存到内存中图片描述图片描述图片描述图片描述
(1)随便写一个jsp页面提交你数据给servlet

<body>
    <h1>Servlet生命周期</h1>
    <hr>
    <a href="servlet/TestServlet1">以Get方式请求TestServlet1</a>
  </body>

(2)要处理的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;

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的初始化方法被执行....");
    }

}

(3)注册Servlet

<?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>

6.Servlet与JSP内置对象的对应关系
答:详见下图:图片描述
7.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
    }

}

8.Servlet路径跳转:
答:详见下图:图片描述
(1)访问那个路径下的servlet:

  <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>

(2)在Servlet里面使用重定向或服务器转发

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

         //请求重定向方式跳转到test.jsp,当前路径是ServletPathDirection/servlet/
         //response.sendRedirect("test.jsp");
         //使用request.getContextPath获得上下文对象
         //response.sendRedirect(request.getContextPath()+"/test.jsp");

        //服务器内部跳转,这里的斜线表示项目的根目录
        //request.getRequestDispatcher("/test.jsp").forward(request, response);
        request.getRequestDispatcher("../test.jsp").forward(request, response);
    }
点击查看更多内容
21人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
67
获赞与收藏
941

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消