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

第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文件中,声明对象语句如下

  
    FirstServletNew
    com.hwp.FirstServletNew
  

2.映射 Servlet

  
    FirstServletNew
    /servlet/FirstServletNew
  

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



  
    
    
    My JSP 'index.jsp' starting page
    
    
        
    
    
    
  
  
  
   
用  户  名:
密        码:
手机号码:
  • 编写 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+"/";
%>



  
    
    
    My JSP 'success.jsp' starting page
    
    
    
        
    
    
    

  
  
  
  <%  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");
  %>
  
用户名: <%=user_name%>
密 码: <%=pwd%>
年龄: <%=phone%>
  • 编写 fail.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



  
    
    
    My JSP 'fail.jsp' starting page
    
    
    
        
    
    
    

  
  
  
    登录失败 
  • 编写 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


  ServletDemo
  
    UserRegisterServlet
    com.hwp.servlet.UserRegisterServlet
  

  
    UserRegisterServlet
    /index
  
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  

你可能感兴趣的:(JAVA Web学习(11)___第8章 Servlet 技术)