Servlet(一)Servlet基础

Servlet基础

目录

Servlet基础

-Servlet概述

-Tomcat容器等级

-HelloServlet手工编写第一个Servlet

-HelloServlet使用eclipse编写第一个Servlet

-Servlet执行流程

-Tomacat装载Servlet的三种情况

-JSP与SerVlet对象的对应关系

-通过Servlet获取表单数据

-Servlet的路径跳转

应用:用Server实现用户登录


-Servlet概述

jsp的前身就是Servlet

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

-Tomcat容器等级

Tomcat容器分为四个等级,

1. Container 容器,集装箱

2.Engine 引擎容器

3.Host 主机()

4.Servlet容器(tomcat最低级别的容器)里面包含了一个或多个Context

—— Context (上下文,背景,环境) 一个context对应一个web项目

—— Wrapper 容器里的封装部分。

-HelloServlet手工编写第一个Servlet

1.      继承HttpServlet

Servlet层级关系:

Servlet(接口)-->GenericServlet(抽象类,与协议无关的Servlet)-->HttpServlet(抽象类,实现了Http协议的Servlet)-->Custom Servlet(自定义的Servlet)。

如何创建和使用Servlet?

2.      重写doGet()和doPost方法

3.      注册Servlet

a)      在web.xml中进行如下配置:

   

       

        HelloServlet

       

        servlet.HelloServlet

   

 

   

        HelloServlet

       

        /servlet/HelloServlet

   

b)Servlet3.0之后可以使用注解来表示所有xml中的配置:

@WebServlet(name="HelloServlet",value={"/servlet/HelloServlet"})

测试:

在Eclipse中新建DynamicWebProject的时候不要直接点"完成",在下一步有个勾选项(Generate web.xml deployment descriptor),选上就会默认生成web.xml

Servlet(一)Servlet基础_第1张图片

选择Superclass,输入HttpServlet -选择第一项- OK

Servlet(一)Servlet基础_第2张图片

选择source-Override/Implement methods

Servlet(一)Servlet基础_第3张图片

勾选doGet和doPost

Servlet(一)Servlet基础_第4张图片

Index.jsp

<%@ page language="java" import="java.util.*"

    contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>









Insert title here





    

第一个Servlet小例子

   
    Get方式请求HelloServlet
   
       
HelloServlet.java 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; //继承于HttpServlet public class HelloServlet extends HttpServlet {     @Override     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         // TODO Auto-generated method stub         System.out.println("处理Get请求。。。");         PrintWriter out=response.getWriter();         out.println("Hello Servlet!
");     }     @Override     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         // TODO Auto-generated method stub         System.out.println("处理Post请求。。。");         PrintWriter out=response.getWriter();         out.println("Hello Servlet!
");     }     }

Web.xml

  <servlet>

  <servlet-name>HelloServletservlet-name>

  <servlet-class>servlet.HelloServletservlet-class>

  servlet>

  <servlet-mapping>

  <servlet-name>HelloServletservlet-name>

  <url-pattern>/servlet/HelloServleturl-pattern>

  servlet-mapping>

运行:

Servlet(一)Servlet基础_第5张图片

Servlet(一)Servlet基础_第6张图片

Servlet(一)Servlet基础_第7张图片

-HelloServlet使用eclipse编写第一个Servlet

Servlet不能自动配置web.xml的原因

建dynamic web project 时,dynamic web module version选择2.5就ok了。

Servlet(一)Servlet基础_第8张图片

新建servlet

Servlet(一)Servlet基础_第9张图片

已经自动配置了web.xml文件,选择Next

Servlet(一)Servlet基础_第10张图片

默认勾选了get和post等,finish。

Servlet(一)Servlet基础_第11张图片

测试:

Servlet(一)Servlet基础_第12张图片

 

Servlet(一)Servlet基础_第13张图片

Servlet(一)Servlet基础_第14张图片

HelloServlet.java

添加需要输出的脚本,留意其中注释掉的部分

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;



/**

 * Servlet implementation class HelloServlet

 */

public class HelloServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

      

    /**

     * @see HttpServlet#HttpServlet()

     */

    public HelloServlet() {

        super();

        // TODO Auto-generated constructor stub

    }



    /**

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // TODO Auto-generated method stub

        //response.getWriter().append("Served at: ").append(request.getContextPath());

        System.out.println("处理Get请求。。。");

        PrintWriter out=response.getWriter();

        out.println("Hello Servlet!
");     }     /**      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)      */     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         // TODO Auto-generated method stub         //doGet(request, response);         System.out.println("处理Post请求。。。");         PrintWriter out=response.getWriter();         out.println("Hello Servlet!
");     } }

Index.jsp

    <h1>使用Eclipse创建Servlet小例子h1>

    <hr>

    <a href="servlet/HelloServlet">Get方式请求HelloServleta><br>

    <form action="servlet/HelloServlet" method="post">

    <input type="submit" value="Post方式请求HelloServlet">

    form>

 

Web.xml

需要修改一处

改成  

/servlet/HelloServlet即可

 

-Servlet执行流程

1.客户端发送请求给服务器。

2.服务器开始接受,先判断该请求的servlet实例是否存在,如果不存在先装载一个servlet类并创建实例。如果存在则直接调用该servlet的service方法,之后进行判断是调用doGet方法还是doPost方法。

3.servlet创建实例后,调用init方法进行初始化。之后调用servce方法,判断是调用doGet方法还是doPost方法。

4.最后判断服务是否关闭,如果关闭则调用destroy方法。

 

注:

编写Servlet的doPost方法时,需要抛出ServletExcpetion和IOException异常

-Tomacat装载Servlet的三种情况

1、自动装载:某些Servlet如果需要在Servlet容器启动时就加载,需要在web.xml下它的标签里中,添加优先级代码:

1

数字越小表示该servlet的优先级越高,会先于其他自动装载的优先级较低的先装载

2、Servlet容器启动后,客户首次向某个Servlet发送请求时,Tomcat容器会加载它

3、当Servlet类文件被更新后,也会重新自动加载

Servlet是长期驻留在内存里的。某个Servlet一旦被加载,就会长期存在于服务器的内存里,直到服务器关闭

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

-JSP与SerVlet对象的对应关系

Jsp内置对象out与servlet中response.getWriter()获得对象并不完全匹配,Jsp中是JspWriter类型,而servlet中获得是PrintWriter类型,其实一个是在Jsp中输出,一个是在servlet中输出,类型肯定不一样;

request、response内置对象可以通过service()方法传到doGet()、doPost()里的request、response来获取;

session可以通过request.getSession()来获取;

application可以通过getServletContext()来获取;

exception可以通过Throwable 来获得;

page对应this对象;

pageContext对象对应PageContext对象;

config可以通过getServletConfig()来获取。

-通过Servlet获取表单数据

1.建立JavaBean类;

2.在Servlet类中的 doPost方法内编写代码;

a)实例化JavaBean对象,通过 getParameter(String param);获取表单值,通过 getParameterValues(String param); 获取多个同name的表单值;通过setter()方法给JavaBean对象传值;

b)将JavaBean对象保存到session中;

c)进行页面跳转。

3.jsp页面中创建Servlet对象,通过或对象的get()方法获取值。

<% String[] favorites=userReg.getFavorites();

   for(String favorite:favorites){

 %>

<%=favorite %>  

<% }%>

 

注意事项:

1.在 jsp 页面中可以使用<% %> 写 java 代码;

2.日期转换时需要注意格式 '-';

3.复选框需要使用 getParameterValues 方式获取;

4.注意复选框是否为 null ;

5.注意javaBean属性名不与表单属性名冲突!

6. request.setCharacterEncoding("UTF-8");//防止中文乱码

7.留意勾选框一直false的情况

if(request.getParameterValues("isAccept")!=null){

              isAccept = request.getParameter("isAccept");

            }else{

              isAccept = "false";

            }

u.setFlag("true".equals(isAccept)?true:false);

是否接受霸王条款

8.留意格式,若为mm则一直是1月,出现错误

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

 

测试:

Servlet(一)Servlet基础_第15张图片

Servlet(一)Servlet基础_第16张图片

Servlet(一)Servlet基础_第17张图片

Servlet(一)Servlet基础_第18张图片

Users.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;

    }



}

RegServlet.java

package servlet;



import java.io.IOException;

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;



/**

 * Servlet implementation class RegServlet

 */

public class RegServlet extends HttpServlet {





    /**

     * @see HttpServlet#HttpServlet()

     */

    public RegServlet() {

        super();

        // TODO Auto-generated constructor stub

    }

    public void destroy() {

        super.destroy(); // Just puts "destroy" string in log

        // Put your code here

    }



    /**

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse

     *      response)

     */

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        // TODO Auto-generated method stub

        doPost(request, response);

    }



    /**

     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse

     *      response)

     */

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        // TODO Auto-generated method stub

        Users u = new Users();

        String username, mypassword, gender, email, introduce, isAccept;

        Date birthday;

        String[] favorites;

        request.setCharacterEncoding("UTF-8");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        try {

            username = request.getParameter("username");

            mypassword = request.getParameter("mypassword");

            gender = request.getParameter("gender");

            email = request.getParameter("email");

            birthday = sdf.parse(request.getParameter("birthday"));

            favorites = request.getParameterValues("favorite");

            introduce=request.getParameter("introduce");

            if(request.getParameterValues("isAccept")!=null)

            {

              isAccept = request.getParameter("isAccept");

            }

            else

            {

              isAccept = "false";

            }



            u.setUsername(username);

            u.setMypassword(mypassword);

            u.setGender(gender);

            u.setEmail(email);

            u.setBirthday(birthday);

            u.setFavorites(favorites);

            u.setIntroduce(introduce);

            u.setFlag("true".equals(isAccept)?true:false);

           



            // 把注册成功的用户对象保存到session中

            request.getSession().setAttribute("regUser", u);

            // 跳转到注册成功页面

            request.getRequestDispatcher("../userinfo.jsp").forward(request, response);



        } catch (Exception ex) {

            ex.printStackTrace();

        }

    }

    public void init() throws ServletException {

        // Put your code here

    }





}

userinfo.jsp

<%@ 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+"/";

%>







  

    

   

    My JSP 'userinfo.jsp' starting page

   

    

    

       

    

    

    

     

  

 

  

    

用户信息

   
   
                                                                                                                                                                                                                                                                                                                 
用户名: 
密码: 
性别: 
E-mail: 
出生日期:              <%                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");                String date = sdf.format(regUser.getBirthday());                            %>              <%=date%>          
爱好:              <%                String[] favorites = regUser.getFavorites();                for(String f:favorites)                {             %>                 <%=f%>                <%                }             %>          
自我介绍: 
是否介绍协议: 
   
 

reg.jsp

<%@ 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+"/";

%>







  

    

   

    My JSP 'reg.jsp' starting page

   

    

    

       

    

    

    

     

   

  

 

  

    

用户注册

   
   
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
用户名:
密码:
确认密码:
电子邮箱:
性别:
出生日期:                                   
爱好:                 NBA                      音乐                      电影                      上网                  
自我介绍:                                     
接受协议:                      是否接受霸王条款                
                                                              
           
 

-Servlet的路径跳转

一、JSP跳转到Servlet

1、相对路径,如href="servlet/TestServlet"

***注意:如果写成"/servlet/TestServlet"会报错,因为第一个'/'表示的是【服务器根目录:http://localhost:8080/】

2、绝对路径,通过内置成员变量path实现,如href="<%=path%>/servlet/TestServlet"。

***注意:这里的path得到的是项目根目录,如【http://localhost:8080/Servlet002_GetFormDemo】

二、Servlet跳转JSP

1、请求重定向:response.sendRedirect(request.getContextPath()+"/xxx.jsp");这里通过request.getContextPath()方法获得项目根目录,或者通过"../xxx.jsp"取得上层路径得到

2、服务器内部转发:request.getRequestDispatcher("../xxx.jsp").forward(req,resp);

***小结:都可以通过../xxx.jsp得到

应用:用Server实现用户登录

JSP项目链接: https://blog.csdn.net/RayMa0305/article/details/81603914

 

删除com.DAO、dologin.jsp

新建一个servlet/Loginservlet

在login.jsp中把action=”dologin.jsp”    改为

Loginservlet.java

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. 
          */          public void destroy() {                    super.destroy(); // Just puts "destroy" string in log                    // Put your code here          }          /**           * The doGet method of the servlet.
          *           * 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.
          *           * 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.
          *           * @throws ServletException           *             if an error occurs           */          public void init() throws ServletException {                    // Put your code here          } }

Servlet(一)Servlet基础_第19张图片

Servlet(一)Servlet基础_第20张图片

Servlet(一)Servlet基础_第21张图片

 

你可能感兴趣的:(Servlet)