美文网首页Java后端
JAVA Web学习(11)___第8章 Servlet 技术

JAVA Web学习(11)___第8章 Servlet 技术

作者: 岁月静好浅笑安然 | 来源:发表于2019-08-19 14:41 被阅读0次

第8章 Servlet 技术

8.1 Servlet基础

8.1.1 Servlet结构体系

8.1.2 Servlet技术特点

  • 可移植
  • 性能高效
  • 安全性高
  • 可扩展

8.1.3 Servlet与JSP区别

  • 角色不同
  • 编程方法不同
  • Servlet需要编译后运行
  • 速度不同

8.1.4 Servlet代码结构

package com.hwp;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {
    //处理 HTTP Delete请求
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        super.doDelete(req, resp);
    }
    //处理HTTP Get请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        super.doGet(req, resp);
    }
    //处理HTTP Post请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        super.doPost(req, resp);
    }
    //处理HTTP Put请求
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        super.doPut(req, resp);
    }
    //销毁方法
    @Override
    public void destroy() {
        super.destroy();
    }
    //初始化请求
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

}

8.2 Servlet API编程常用的接口和类

8.2.1 Servlet接口

方法 说明
public void init(ServletConfig config) Servlet实例化后,Servlet容器调用该方法来完成初始化工作
public void service(ServletRequest request,ServletResponse response) 用于处理客户端请求
public void destroy() 当 Servlet对象从 Servlet容器中移除时,容器调用该方法释放资源
public ServletConfig getServletConfig() 用于获取 Servlet对象的配置信息,返回 ServletConfig对象
public String getServletInfo() 返回 Servlet的信息,它是纯文本格式的字符串

8.2.2 ServletConfig接口

在 ServletConfig初始化方法中传递

public void init(ServletConfig config) throws ServletException {}
方法 说明
public String getInitParameter(String arg0) 返回String类型名称为name的初始化信息
public EgetInitParameterNames getInitParameterNames() 获取所有初始化参数名的枚举类集合
public ServletContext getServletContext() 获取 Servlet上下文对象
public String getServletName() 返回 Servlet对象实例名

8.2.3 HttpServletRequest接口

方法 说明
public String getContextPath() 返回请求的上下文路径,此路径以"/"开关
public Cookie[] getCookies() 返回cookie对象数组
public String getMethod() 返回请求所使用的HTTP类型,如get、post等
public String getQueryString() 返回请求中参数的字符串形式,如
public String getRequestURI() 返回主机名到请求参数之间的字符串形式
public StringBuffer getRequestURL() 返回请求的URL
public String getServletPath() 返回请求uri中的 Servlet路径的字符串,不包含请求在的参数信息
public HgetSession getSession() 返回与请求关联的 HgetSession

8.2.4 HttpServletResponse接口

方法 说明
public void addCookie(Cookie arg0) 向客户端写入cookie信息
public void sendError(int arg0) 发送一个错误状态码响应到客户端
public void sendError(int arg0,String arg1) 发送错误信息和错误状态码到客户端
public void sendRedirect(String arg0) 使客户端重定向到新的url

8.2.5 GenericServlet类

8.2.6 HttpServlet类

8.3 Servlet开发

8.3.1 Servlet创建

1.手动创建MyServlet类继承javax.servlet.http.HttpServlet,然后手动配置web.xml(不推荐使用)

2.通过IDE自动配置,File---NEW---Servlet,输入包名、类名然后勾选方法,直接下一步下一步完成(推荐使用)

8.3.2 Servlet配置

1.声明 Servlet对象

在web.xml文件中,声明对象语句如下

  <servlet>
    <servlet-name>FirstServletNew</servlet-name>
    <servlet-class>com.hwp.FirstServletNew</servlet-class>
  </servlet>

2.映射 Servlet

  <servlet-mapping>
    <servlet-name>FirstServletNew</servlet-name>
    <url-pattern>/servlet/FirstServletNew</url-pattern>
  </servlet-mapping>

8.4 实例,使用servlet实现简单登录功能

  • 编写index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="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>
   <form action=index method="post">
   <table>
   <tr><td>用&nbsp;&nbsp;户&nbsp;&nbsp;名:<input type="text" name="username"></td></tr>
   <tr><td>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码:<input type="text" name="password"></td></tr>
   <tr><td>手机号码:<input type="text" name="phone"></td></tr>
   <tr align="center"><td><input type="submit" value="提交""></td></tr>
   </table>
   </form>
  </body>
</html>
  • 编写 success.jsp
    只要三个输入框都不为空,就跳转到此页面,并且响应的用户名、密码、电话显示出来
<%@page import="com.hwp.bean.UserBean"%>
<%@ page language="java" import="java.util.*" pageEncoding="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 'success.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>
  <%  UserBean userBean=  (UserBean)request.getAttribute("user");
  String user_name=new String(userBean.getUsername().getBytes("ISO-8859-1"),"UTF-8");
  String pwd= new String(userBean.getPassword().getBytes("ISO-8859-1"),"UTF-8");
  String phone= new String(userBean.getPhone().getBytes("ISO-8859-1"),"UTF-8");
  %>
  <table border="1" align="center">
        <tr>
            <td>用户名:</td>
            <td><%=user_name%></td>
        </tr>
        <tr>
            <td>密&nbsp;码:</td>
            <td><%=pwd%></td>
        </tr>
        <tr>
            <td>年龄:</td>
            <td><%=phone%></td>
        </tr>
    </table>
  </body>
</html>

  • 编写 fail.jsp
<%@ page language="java" import="java.util.*" pageEncoding="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 'fail.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>
    登录失败 <br>
  </body>
</html>

  • 编写 UserRegisterServlet.java
package com.hwp.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 javax.servlet.http.HttpSession;

import com.hwp.bean.UserBean;

public class UserRegisterServlet extends HttpServlet {

    
    private static final long serialVersionUID = 1L;

    public UserRegisterServlet() {
        super();
    }


    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

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

          UserBean account = new UserBean();
          String user_name = request.getParameter("username");
          String pwd = request.getParameter("password");
          String phone = request.getParameter("phone");
          account.setPassword(pwd);
          account.setUsername(user_name);
          account.setPhone(phone);
    
        
        if(!user_name.isEmpty()&&!pwd.isEmpty()&&!phone.isEmpty()){
            String login_suc="success.jsp";
            request.setAttribute("user", account);
            request.getRequestDispatcher(login_suc).forward(request, response);
            return;
        }else{
        String login_fail="fail.jsp";
        response.sendRedirect(login_fail);
        return;
        }
    }

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

    
    public void init() throws ServletException {
        
    }

}

  • 编写 UserBean.java
package com.hwp.bean;

public class UserBean {
    private String username;
    private String password;
    private String phone;
    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 String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    
}

  • 配置 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>ServletDemo</display-name>
  <servlet>
    <servlet-name>UserRegisterServlet</servlet-name>
    <servlet-class>com.hwp.servlet.UserRegisterServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>UserRegisterServlet</servlet-name>
    <url-pattern>/index</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

相关文章

网友评论

    本文标题:JAVA Web学习(11)___第8章 Servlet 技术

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