博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
利用Servlet做一套增删改查
阅读量:5135 次
发布时间:2019-06-13

本文共 13268 字,大约阅读时间需要 44 分钟。

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

前期准备配置

建一个动态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
list() { return list(0, Short.MAX_VALUE); } public List
list(int start, int count) { List
heros = new ArrayList
(); 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
登录页面
账号:
密码:
可以看出,action为login,method为post 现在需要在web.xml中配置映射
LoginServlet
servlet.LoginServlet
LoginServlet
/login

现在编写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();        }    }}

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

Insert title here

密码或账号错误

回到登陆界面重新登陆

服务器跳转是在web.xml中映射一个路径,然后在相应的servlet中执行操作

HeroListServlet
servlet.HeroListServlet
HeroListServlet
/listHero

编写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
heros = new HeroDAO().list(); StringBuffer sb = new StringBuffer(); sb.append("

Welcome:

"); String ps = ("

%s

"); String ps1 = String.format(ps, userName); sb.append(ps1); ps1 = ("
");//增加添加新成员的连接 sb.append(ps1); sb.append("
\r\n"); sb.append("
\r\n"); String trFormat = "
" + "
"//添加删除连接 + "
\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("
id name hp damage delete edit
%d %s %f %d delete edit
"); response.getWriter().write(sb.toString()); }}

增加新成员链接下的操作

转到添加页面addHero.html

 
名字 :
血量 :
伤害:

添加英雄

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(添加编辑删除的)

HeroAddServlet
/addHero
HeroDeleteServlet
servlet.HeroDeleteServlet
HeroDeleteServlet
/deleteHero
HeroEditServlet
servlet.HeroEditServlet
HeroEditServlet
/editHero

删除操作

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("");        format.append("
"); format.append("名字 :
"); format.append("血量 :
"); format.append("伤害:
"); format.append("
"); format.append("
"); format.append("
"); String html = String.format(format.toString(), hero.getName(), hero.getHp(), hero.getDamage(), hero.getId()); response.getWriter().write(html); }}
添加更新 更新操作
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);     }}

小结:

  •  前端的数据可以在服务端通过其name属性,利用request.getParameter("xxx");来获取
  • 设置session,request.getSession().setAttribute("userName", name);这样在服务端就可以通过 request.getSession().getAttribute("userName");获取存入session的username
  • 服务端跳转 request.getRequestDispatcher("success.html").forward(request, response);服务端跳转可以看到浏览器的地址依然是之前的路径路径,并不会变成success.html
  • 客户端跳转 response.sendRedirect("fail.html");

转载于:https://www.cnblogs.com/dong973711/p/10907733.html

你可能感兴趣的文章
JavaScript中进制之间的转换
查看>>
JavaScript
查看>>
策略模式
查看>>
asp.net常用的引用命名空间的含义
查看>>
HDU 4436 str2int(后缀自动机)
查看>>
UIKit结构图
查看>>
java虚拟机指令dup的理解
查看>>
多校5 HDU5787 K-wolf Number 数位DP
查看>>
后缀自动机
查看>>
原生ajax 和axios 一起使用导致获取不到用户信息
查看>>
Android求生之路4-添加背景图片
查看>>
Vue教程学习 一:
查看>>
django.modle基础(增删改查)
查看>>
Response.AddHeader使用实例
查看>>
导入maven项目,ojdbc依赖发生错误解决方案
查看>>
h5移动端网页头部标签模板
查看>>
[Linux]DOS 和 Linux 常用命令的对比
查看>>
实验三
查看>>
java_2018_Day7_构造方法
查看>>
ENVI5.1无缝镶嵌工具
查看>>