Java Web Servlet

各 Servlet 功能与实现详情

1. UpdateServlet

1. 构造方法 UpdateServlet()

  • 调用父类 HttpServlet 的构造方法,无额外自定义逻辑

2. doGet() 方法

  • 功能:处理 GET 请求,仅返回基础服务信息
  • 实现:通过 response.getWriter().append("Served at: ").append(request.getContextPath()) 返回服务路径信息,无实际业务逻辑

3. doPost() 方法(核心业务逻辑)

步骤 1:接收前端参数

从请求中获取需要更新的字段值:

  • channelid:内容所属频道 ID
  • title:内容标题
  • author:作者
  • createtime:创建时间
  • content:内容正文(会对双引号做替换处理)
  • id:需要更新的记录 ID(用于定位数据)
  • imgurl:图片 URL
步骤 2:处理特殊字段
  • 对 content 进行处理:content = content.replaceAll("\"", "\'"),将正文中的双引号替换为单引号,避免 SQL 语法错误
步骤 3:构建并执行更新 SQL
  • 拼接 SQL 语句:

    • 访问路径/UpdateServlet
    • 核心功能:更新 content 表中的已有记录
    • 请求处理
      • 仅通过 doPost() 方法处理请求
      • 接收前端参数:channelidtitleauthorcreatetimecontentidimgurl
      • 对 content 做特殊处理:content.replaceAll("\"", "\'")(替换双引号为单引号)
      • SQL 操作:
update content set title="xxx",createtime="xxx",author="xxx",imgurl="xxx",content="xxx",channelid=xxx where id= xxx
  • 响应结果:返回 "修改成功" 或 "修改失败" 字符串(UTF-8 编码)

2. AddContent(内容添加功能)

package com.qcby.servlet;

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

import com.qcby.db.MysqlUtil;

/**
 * Servlet implementation class AddContent
 */
@WebServlet("/AddContent")
public class AddContent extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddContent() {
        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());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String channelid = request.getParameter("channelid");
		String title = request.getParameter("title");
		String author = request.getParameter("author");
		String createtime = request.getParameter("createtime");
		String content = request.getParameter("content");
		content = content.replaceAll("\"", "\'");
		String imgurl = request.getParameter("imgurl");
		
		String sql = "insert into content(title,createtime,author,imgurl,content,channelid) values(\""+title+"\",\""+createtime+"\",\""+author+"\",\""+imgurl+"\",\""+content+"\","+channelid+")";
	
		int num = MysqlUtil.add(sql);
		String res = "添加失败";
		if(num>0) {
			res="添加成功";
		}
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(res);
	
	
	
	}

}
  • 访问路径/AddContent
  • 核心功能:向 content 表插入新记录
  • 构造方法 AddContent()

  • 调用父类 HttpServlet 的构造方法,无自定义初始化逻辑
  • 2. doGet() 方法

  • 功能:处理 GET 请求,仅返回基础服务信息
  • 实现:通过 response.getWriter().append("Served at: ").append(request.getContextPath()) 返回服务路径,无实际业务逻辑
  • 3. doPost() 方法(核心业务逻辑)

    步骤 1:接收前端参数

    从请求中获取需要添加的字段值:

  • channelid:内容所属频道 ID
  • title:内容标题
  • author:作者名称
  • createtime:创建时间
  • content:内容正文(需特殊处理)
  • imgurl:图片资源 URL
  • 步骤 2:处理特殊字段
  • 对 content 进行处理:content = content.replaceAll("\"", "\'"),将正文中的双引号替换为单引号,避免拼接 SQL 时出现语法错误
步骤 3:构建并执行插入 SQL
  • 拼接 SQL 语句:
  • insert into content(title,createtime,author,imgurl,content,channelid) 
    values("xxx","xxx","xxx","xxx","xxx",xxx)

  • 响应结果:返回 "添加成功" 或 "添加失败" 字符串(UTF-8 编码)

3. DeleteContent(内容删除功能)

package com.qcby.servlet;

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

import com.qcby.db.MysqlUtil;

/**
 * Servlet implementation class DeleteContent
 */
@WebServlet("/DeleteContent")
public class DeleteContent extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteContent() {
        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());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String id = request.getParameter("id");
		String sql = "delete from content where id in("+id+")";
		int num = MysqlUtil.del(sql);
		String res = "删除失败";
		if(num>0) {
			res="删除成功";
		}
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(res);
		
	}

}
  • 访问路径/DeleteContent
  • 核心功能:从 content 表删除记录(支持批量删除)
  • 请求处理
    • 仅通过 doPost() 方法处理请求
    • 接收参数:id(可传入多个 ID,用于批量删除)
  • SQL 操作
delete from content where id in(xxx)  -- 其中xxx为传入的id列表
  • 响应结果:返回 "删除成功" 或 "删除失败" 字符串(UTF-8 编码)

4. SearchChannel(频道查询功能)

package com.qcby.servlet;

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

import com.qcby.db.MysqlUtil;

/**
 * Servlet implementation class SearchChannel
 */
@WebServlet("/SearchChannel")
public class SearchChannel extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchChannel() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String sql = "select * from channel";
		String[] colums = {"id","channelname"};
		String res = MysqlUtil.getJsonBySql(sql, colums);
		//设置后端给前端返回信息为json
		response.setContentType("text/json;charset=utf-8");
		//返回数据
		response.getWriter().write(res);
	}

	/**
	 * @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);
	}

}
  • 访问路径/SearchChannel
  • 核心功能:查询 channel 表中的所有频道信息
  • 请求处理
    • doGet() 和 doPost() 均能处理请求(doPost() 直接调用 doGet()

SQL 操作

select * from channel
  • 响应结果
    • 返回 JSON 格式数据(包含 id 和 channelname 字段)
    • 明确设置响应类型:response.setContentType("text/json;charset=utf-8")

5.SearchContent Servlet

实现对content表的多条件分页查询,关联channel表获取频道名称

package com.qcby.servlet;

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

import com.qcby.db.MysqlUtil;

/**
 * Servlet implementation class SearchContent
 */
@WebServlet("/SearchContent")
public class SearchContent extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchContent() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//接收参数
		String channelid = request.getParameter("channelid");
		String title = request.getParameter("title");
		String author = request.getParameter("author");
		String page = request.getParameter("page");
		String pageSize = request.getParameter("pageSize");
		String id = request.getParameter("id");
		
		String sql = "select content.*,channelname from content,channel where content.channelid = channel.id ";
		if(channelid!=null&&!channelid.equals("0")) {
			sql+="	and channelid = "+channelid;
		}
		if(title!=null&&!title.equals("")) {
			sql+="  and title like \"%"+title+"%\"";
		}
		if(author!=null&&!author.equals("")) {
			sql+=" and author=\""+author+"\"";
		}
		if(id!=null&&!id.equals("")) {
			sql+=" and content.id = "+id;
		}
		sql+=" order by createtime desc";
		
		if(page!=null&&pageSize!=null&&!page.equals("")&&!pageSize.equals("")) {
			sql+=" limit "+(Integer.parseInt(page)-1)*Integer.parseInt(pageSize)+","+pageSize;
		}
		
		String[] colums = {"id","title","createtime","author","imgurl","content","channelid","channelname"};
		String res = MysqlUtil.getJsonBySql(sql, colums);
		
		//设置后端给前端返回信息为json
		response.setContentType("text/json;charset=utf-8");
		//返回数据
		response.getWriter().write(res);
		
	}

	/**
	 * @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);
	}

}
1. doGet () 方法(核心处理逻辑)
  1. 接收请求参数

    • channelid:频道 ID(用于筛选特定频道内容)
    • title:内容标题(支持模糊查询)
    • author:作者名称(精确匹配)
    • page:页码(分页参数)
    • pageSize:每页记录数(分页参数)
    • id:内容 ID(精确查询单条记录)
  2. 构建 SQL 查询语句

    • 基础 SQL:select content.*,channelname from content,channel where content.channelid = channel.id(关联两表查询)
    • 条件拼接规则:
      • channelid不为null且不等于 "0",添加and channelid = ${channelid}
      • title不为null且非空,添加and title like "%${title}%"(模糊查询)
      • author不为null且非空,添加and author="${author}"
      • id不为null且非空,添加and content.id = ${id}
    • 排序:固定按创建时间降序 order by createtime desc
    • 分页:若pagepageSize有效,添加limit ${(page-1)*pageSize},${pageSize}
  3. 执行查询与响应

    • 指定返回字段:idtitlecreatetimeauthorimgurlcontentchannelidchannelname
    • 通过MysqlUtil.getJsonBySql(sql, colums)获取 JSON 格式结果
    • 设置响应类型:response.setContentType("text/json;charset=utf-8")
    • 返回 JSON 数据
2. doPost () 方法

直接调用doGet(request, response),支持 POST 方式提交查询请求

6.GetCount Servlet(查询结果计数功能)

根据与SearchContent相同的查询条件,统计符合条件的记录总数(用于分页计算总页数)

package com.qcby.servlet;

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

import com.qcby.db.MysqlUtil;

/**
 * Servlet implementation class GetCount
 */
@WebServlet("/GetCount")
public class GetCount extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetCount() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String channelid = request.getParameter("channelid");
		String title = request.getParameter("title");
		String author = request.getParameter("author");
		
		String sql = "select count(*) from content,channel where content.channelid = channel.id ";
		if(channelid!=null&&!channelid.equals("0")) {
			sql+="	and channelid = "+channelid;
		}
		if(title!=null&&!title.equals("")) {
			sql+="  and title like \"%"+title+"%\"";
		}
		if(author!=null&&!author.equals("")) {
			sql+=" and author=\""+author+"\"";
		}

		int num = MysqlUtil.getCount(sql);
		String res = String.valueOf(num);
		response.getWriter().write(res);
	}

	/**
	 * @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);
	}

}

1. doGet () 方法(核心处理逻辑)

  1. 接收请求参数

    • SearchContent共享三个核心条件参数:channelidtitleauthor(无分页和id参数)
  2. 构建计数 SQL 语句

    • 基础 SQL:select count(*) from content,channel where content.channelid = channel.id
    • 条件拼接规则:与SearchContent完全一致(确保计数条件与查询条件统一)
  3. 执行计数与响应

    • 通过MysqlUtil.getCount(sql)获取记录总数
    • 将计数结果转为字符串返回(String.valueOf(num)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值