利用Servlet的增删改查

Posted dong973711

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用Servlet的增删改查相关的知识,希望对你有一定的参考价值。

 真的,稳住,考上研,利用两年逆袭。一步一步来,实在不行,最后最差也不过就是就回家种地,想想也不错。

前期准备配置

建一个动态web项目

新建Dynamic Web Project
File->New->Other->Web->Dynamic Web Project

新建web.xml文件并新建几个包

技术图片技术图片

开始写代码

在entity在新建两个类,User(用来登录)和Hero(用来增删改查)

user表和用户表,代建。

数据库连接放util中包中

package util;

import java.sql.Connection;
import java.sql.DriverManager;

import javax.sound.midi.Soundbank;

public class DbUtil {

    private String dbUrl="jdbc:mysql://localhost:3306/how2java";
    private String dbUserName="root";
    private String dbPassword="123456";
    private String jdbcName="com.mysql.jdbc.Driver";
    
    /**
     * 获取数据库连接
     * @return
     * @throws Exception
     */
    public Connection getCon() throws Exception{
        Class.forName(jdbcName);
        Connection con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
        System.out.println("数据库连接成功!");
        return con;
    }
    
    /**
     * 关闭数据库连接
     * @param con
     * @throws Exception
     */
    public void closeCon(Connection con) throws Exception{
        if(con!=null){
            con.close();
        }
    }
    
}

hero的增删查改的方法实现放在dao包下

package dao;

import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;

import entity.Hero;
import util.DbUtil;

public class HeroDAO {
    DbUtil dbutil = new DbUtil();
//添加新英雄
    public void add(Hero hero) {
        String sql = "insert into hero values(null,?,?,?)";
        try {
            Connection c = (Connection) dbutil.getCon();
            PreparedStatement ps = (PreparedStatement) c.prepareStatement(sql);
            ps.setString(1, hero.name);
            ps.setFloat(2, hero.hp);
            ps.setInt(3, hero.damage);

            ps.execute();

            ResultSet rs = (ResultSet) ps.getGeneratedKeys();
            if (rs.next()) {
                int id = rs.getInt(1);
                hero.id = id;
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
    }
//更新英雄
    public void update(Hero hero) {

        String sql = "update hero set name= ?, hp = ? , damage = ? where id = ?";
        try (Connection c = (Connection) dbutil.getCon();
                PreparedStatement ps = (PreparedStatement) c.prepareStatement(sql);) {

            ps.setString(1, hero.name);
            ps.setFloat(2, hero.hp);
            ps.setInt(3, hero.damage);
            ps.setInt(4, hero.id);

            ps.execute();

        } catch (Exception e) {

            e.printStackTrace();
        }

    }
//删除英雄
    public void delete(int id) {

        try (Connection c = (Connection) dbutil.getCon();

                Statement s = (Statement) c.createStatement();) {

            String sql = "delete from hero where id = " + id;

            s.execute(sql);

        } catch (Exception e) {

            e.printStackTrace();
        }
    }
//根据id号获得英雄
    public Hero get(int id) {
        Hero hero = null;

        try (Connection c = (Connection) dbutil.getCon(); Statement s = (Statement) c.createStatement();) {

            String sql = "select * from hero where id = " + id;

            ResultSet rs = (ResultSet) s.executeQuery(sql);

            if (rs.next()) {
                hero = new Hero();
                String name = rs.getString(2);
                float hp = rs.getFloat("hp");
                int damage = rs.getInt(4);
                hero.name = name;
                hero.hp = hp;
                hero.damage = damage;
                hero.id = id;
            }

        } catch (Exception e) {

            e.printStackTrace();
        }
        return hero;
    }

    public List<Hero> list() {
        return list(0, Short.MAX_VALUE);
    }

    public List<Hero> list(int start, int count) {
        List<Hero> heros = new ArrayList<Hero>();

        String sql = "select * from hero order by id asc limit ?,? ";

        try (Connection c = (Connection) dbutil.getCon();
                PreparedStatement ps = (PreparedStatement) c.prepareStatement(sql);) {

            ps.setInt(1, start);
            ps.setInt(2, count);

            ResultSet rs = (ResultSet) ps.executeQuery();

            while (rs.next()) {
                Hero hero = new Hero();
                int id = rs.getInt(1);
                String name = rs.getString(2);
                float hp = rs.getFloat("hp");
                int damage = rs.getInt(4);
                hero.id = id;
                hero.name = name;
                hero.hp = hp;
                hero.damage = damage;
                heros.add(hero);
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return heros;
    }
}

 

登录模块

login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录页面</title>
</head>
<body>
  
<form action="login" method="POST">
账号: <input type="text" name="name"> <br>
密码: <input type="password" name="password"> <br>
<input type="submit" value="登录">
</form>
  
</body>
</html>
从<form action="login" method="POST">可以看出,action为login,method为post
现在需要在web.xml中配置映射
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>servlet.LoginServlet</servlet-class>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>  
</web-app>

现在编写LoginServlet类

package servlet;

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

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;

import util.DbUtil;

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        System.out.println(name + "  " + password);
        String sql = "select * from user where name = ‘" + name +"‘ and password = ‘" + password+"‘";
        DbUtil dbConnect = new DbUtil();
        try {
            Connection con = (Connection) dbConnect.getCon();
            Statement s = (Statement) con.createStatement();
            ResultSet set = (ResultSet) s.executeQuery(sql);
            if (set.next()) {
                System.out.println("账号密码正确");
                request.getSession().setAttribute("userName", name);
                request.getRequestDispatcher("/listHero").forward(request, response);//服务器跳转
            } else {
                response.sendRedirect("fail.html");// 客户端跳转
                System.out.println("账号密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

客户端跳转我设置了登录信息错误跳转到的页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>密码或账号错误</h1>
<a href="login.html">回到登陆界面重新登陆</a>
</body>
</html>

服务器挑战这是在web.xml中映射一个动作

 <servlet>
        <servlet-name>HeroListServlet</servlet-name>
        <servlet-class>servlet.HeroListServlet</servlet-class>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>HeroListServlet</servlet-name>
        <url-pattern>/listHero</url-pattern>
    </servlet-mapping>

编写HeroListServlet,以html形式展示出英雄列表

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 dao.HeroDAO;
import entity.Hero;

public class HeroListServlet extends HttpServlet{
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         String userName = (String) request.getSession().getAttribute("userName");
         System.out.println("欢迎"+userName);
        if (null == userName) {
            response.sendRedirect("login.html");
            return;
        }
        response.setContentType("text/html; charset=UTF-8");
        
        
        List<Hero> heros = new HeroDAO().list();

        StringBuffer sb = new StringBuffer();
        
        sb.append("<h1 align=‘center‘>Welcome:</h1>");
        String ps = ("<h2 align=‘center‘>%s</h2>");
        String ps1 = String.format(ps, userName);
        sb.append(ps1);
        
        ps1 = ("<div align=‘center‘><a href=‘addHero.html‘>增加成员</a></div>");//增加添加新成员的连接
        sb.append(ps1);
        
        
        sb.append("<table align=‘center‘ border=‘1‘ cellspacing=‘0‘>\\r\\n");
        sb.append("<tr><td>id</td><td>name</td><td>hp</td><td>damage</td><td>delete</td><td>edit</td></tr>\\r\\n");

        String trFormat = "<tr><td>%d</td><td>%s</td><td>%f</td><td>%d</td>"
                + "<td><a href=‘deleteHero?id=%d‘>delete</a></td>"//添加删除连接
                + "<td><a href=‘editHero?id=%d‘>edit</a></td></tr>\\r\\n";//添加修改连接

        for (Hero hero : heros) {
            //System.out.println(hero);
            String tr = String.format(trFormat, hero.getId(), hero.getName(), hero.getHp(),
                    hero.getDamage(),hero.getId(),hero.getId());//设置删除和修改连接下的id就是相对应英雄的id
            sb.append(tr);
        }
        sb.append("</table>");
        response.getWriter().write(sb.toString());
    }
}

增加新成员链接下的操作

转到添加页面addHero.html

<!DOCTYPE html>
 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
<form action="addHero" method="post">
     名字 : <input type="text" name="name"> <br>
血量 : <input type="text" name="hp"> <br>
伤害: <input type="text" name="damage"> <br>
         <input type="submit" value="增加 ">
</form>

添加英雄

package servlet;

import java.io.IOException;

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

import dao.HeroDAO;
import entity.Hero;
import net.sf.json.JSONObject;

public class HeroAddServlet extends HttpServlet{
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException{
        
        request.setCharacterEncoding("UTF-8");
        
        String name = request.getParameter("name");
        String hp = request.getParameter("hp");
        String damage = request.getParameter("damage");
        
        Hero hero = new Hero();
        hero.setName(name);
        hero.setHp(Float.parseFloat(hp));
        hero.setDamage(Integer.parseInt(damage));
        
        new HeroDAO().add(hero);
        System.out.println("添加成功"+hero.toString());
        
        request.getRequestDispatcher("/listHero").forward(request, response);
    }
}

配置web.xml(添加编辑删除的)

<servlet-mapping>
        <servlet-name>HeroAddServlet</servlet-name>
        <url-pattern>/addHero</url-pattern>
    </servlet-mapping>  
    
    <servlet>
        <servlet-name>HeroDeleteServlet</servlet-name>
        <servlet-class>servlet.HeroDeleteServlet</servlet-class>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>HeroDeleteServlet</servlet-name>
        <url-pattern>/deleteHero</url-pattern>
    </servlet-mapping>
    
    <servlet>
        <servlet-name>HeroEditServlet</servlet-name>
        <servlet-class>servlet.HeroEditServlet</servlet-class>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>HeroEditServlet</servlet-name>
        <url-pattern>/editHero</url-pattern>
    </servlet-mapping>

删除操做

package servlet;

import java.io.IOException;

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

import dao.HeroDAO;

public class HeroDeleteServlet extends HttpServlet {
    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        int id = Integer.parseInt(request.getParameter("id"));//获得要删除的id

        new HeroDAO().delete(id);//调用删除英雄方法
        
        request.getRequestDispatcher("/listHero").forward(request, response);//跳转到展示hero页面
    }
}

编辑操作

package servlet;

import java.io.IOException;

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

import dao.HeroDAO;
import entity.Hero;

public class HeroEditServlet extends HttpServlet {
    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        
        int id = Integer.parseInt(request.getParameter("id"));
        Hero hero = new HeroDAO().get(id);
        StringBuffer format = new StringBuffer();
        response.setContentType("text/html; charset=UTF-8");

        format.append("<!DOCTYPE html>");

        format.append("<form action=‘updateHero‘ method=‘post‘>");
        format.append("名字 : <input type=‘text‘ name=‘name‘ value=‘%s‘ > <br>");
        format.append("血量 : <input type=‘text‘ name=‘hp‘  value=‘%f‘ > <br>");
        format.append("伤害: <input type=‘text‘ name=‘damage‘  value=‘%d‘ > <br>");
        format.append("<input type=‘hidden‘ name=‘id‘ value=‘%d‘>");
        format.append("<input type=‘submit‘ value=‘更新‘>");
        format.append("</form>");

        String html = String.format(format.toString(), hero.getName(), hero.getHp(), hero.getDamage(), hero.getId());

        response.getWriter().write(html);
    }
}
<form action=‘updateHero‘ method=‘post‘>添加更新
更新操作
package servlet;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import dao.HeroDAO;
import entity.Hero;
 
public class HeroUpdateServlet extends HttpServlet {
 
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        request.setCharacterEncoding("UTF-8");
 
        Hero hero = new Hero();
        hero.setId(Integer.parseInt(request.getParameter("id")));
        hero.setName(request.getParameter("name"));
        hero.setHp(Float.parseFloat(request.getParameter("hp")));
        hero.setDamage(Integer.parseInt(request.getParameter("damage")));
 
        new HeroDAO().update(hero);
 
        request.getRequestDispatcher("/listHero").forward(request, response);
 
    }
}

总结:

 

以上是关于利用Servlet的增删改查的主要内容,如果未能解决你的问题,请参考以下文章

Android Studio 实现实现学生信息的增删改查 -源代码 四(Servlet + 连接MySql数据库)

Android Studio 实现实现学生信息的增删改查 -源代码 四(Servlet + 连接MySql数据库)

Web对数据库的增删改查(servlet+jsp+javaBean增删改查)

web项目总结——通过jsp+servlet实现对oracle的增删改查功能

jsp+servlet+jdbc实现对数据库的增删改查

Servlet中请给出一个Cookie的增删改查的例子。