Java Web核心之Servlet

Servlet的概述

Servlet运行在服务端的Java小程序,是sum公司提供的一套规范,用来处理客户端请求、相应给浏览器的动态资源

Servlet是JavaWeb三大组件之一(Servlet、Filter、Listener),且最重要

Servlet的作用

用来处理客户端发送过来的请求,并对请求作出响应

Java Web核心之Servlet_第1张图片
访问过程

Servlet的任务有:

  • 获取请求数据
  • 处理请求
  • 完成响应

Servlet的入门

准备工作

Servlet规范要求:Servlet程序需要编写实现类,并在web.xml进行配置

在实际开发中,我们不会直接去实现Servlet接口,因为那样需要覆盖的方法太多, 我们一般创建类继承HttpServlet

实现类:通常继承javax.servlet.http.HttpServlet类,并重写doGetdoPost方法

  • doGet方法用于处理get请求
  • doPost用于处理post请求

编写步骤

  • 编写配置文件
    在图中的web.xml中配置文件


    Java Web核心之Servlet_第2张图片
    配置文件
  
    aa
    com.cuzz.servlet.QuickStartServelet
  
  
  
    aa
    /QuickStartServelet
  

案例一、完成用户登录功能

  • 新建一个User类,省略了一部分
package com.cuzz.login;

public class User {

    private int id;
    private String username;
    private String password;

    public User(){}
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    ...
    
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password +  "]";
    }
}
  • 编写一个ServletLogin类来处理请求
    右击新建一个Servlet项目
package com.cuzz.login;

import java.io.IOException;
import java.sql.SQLException;

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

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.cuzz.utlis.DataSourceUtils;

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       

    public LoginServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        // 从数据库中验证该用户名和密码是否正确
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "SELECT * FROM login WHERE username=? and password=?";
        User user = null;
        try {
            user = qr.query(sql,new BeanHandler(User.class), username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        if(user != null){
            // 用户登入成功
            response.getWriter().write(user.toString());    
        }else{
            // 用户登入失败
            response.getWriter().write("sorry");
        }
    }

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

案例二、记录登入人的次数

import java.io.IOException;
import java.sql.SQLException;

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

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.cuzz.utlis.DataSourceUtils;

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    
    @Override
    public void init() throws ServletException {
        // 在Seveltcontext域中存一个数据count
        int count = 0;
        this.getServletContext().setAttribute("count", count);
    }

    public LoginServlet() {
        super();
 
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        // 从数据库中验证该用户名和密码是否正确
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "SELECT * FROM login WHERE username=? and password=?";
        User user = null;
        try {
            user = qr.query(sql,new BeanHandler(User.class), username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        if(user != null){
            // 用户登入成功
            //从servletcontext中取出count进行++运算
            ServletContext context = this.getServletContext();
            Integer count = (Integer) context.getAttribute("count");
            count++;
            response.getWriter().write(user.toString() + count);
            // 在把count记录到servletcontext中
            context.setAttribute("count", count);
        }else{
            // 用户登入失败
            response.getWriter().write("sorry");
        }
    }

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

你可能感兴趣的:(Java Web核心之Servlet)