Servlet查询

CRUD是常见的页面功能,即我们常说的增删查改

  • C - Creation 增加
  • R - Retrieve 查询
  • U - Update 修改
  • D - Delete 删除

为web应用导入mysql-jdbc的jar包

  • 放在WEB-INF/lib 下指的是能够web应用中找到对应的class
  • 如果要在eclipse中做调试,还是需要为项目添加该jar才可以

编写HeroListServlet

  • 命名规范:[表][行为]Servlet这样一种命名规范
  • 增加:HeroAddServlet
package servlet;

import java.io.IOException;
import java.util.List;

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

import bean.Hero;
import dao.HeroDAO;

public class HeroListServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8");
        
        List heros = new HeroDAO().list();
        
        StringBuffer sb = new StringBuffer();
        sb.append("\r\n");
        sb.append("\r\n");
        String trFormat = "\r\n";
        
        for (Hero hero : heros) {
            String tr = String.format(trFormat, hero.getId(), hero.getName(), hero.getHp(), hero.getDamage());
            sb.append(tr);
        }
 
        sb.append("
idnamehpdamage
%d%s%f%d
"); response.getWriter().write(sb.toString()); } }

配置web.xml

  • 把路径listHero映射到HeroListServlet上
  • 加上包名
        HeroListServlet
        servlet.HeroListServlet
    
    
    
        HeroListServlet
        /listHero
    

重启tomcat,访问http://localhost/j2ee_dynamic/listHero

image.png

你可能感兴趣的:(Servlet查询)