博客
关于我
强烈建议你试试无所不能的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

你可能感兴趣的文章
对团队成员公开感谢博客
查看>>
java学习第三天
查看>>
django+uwsgi+nginx+sqlite3部署+screen
查看>>
浅谈项目需求变更管理
查看>>
经典算法系列一-快速排序
查看>>
设置java web工程中默认访问首页的几种方式
查看>>
ASP.NET MVC 拓展ViewResult实现word文档下载
查看>>
8、RDD持久化
查看>>
第二次团队冲刺--2
查看>>
Linux上架设boost的安装及配置过程
查看>>
[转载]加密算法库Crypto——nodejs中间件系列
查看>>
使用Xshell密钥认证机制远程登录Linux
查看>>
Android 画图之 Matrix(一)
查看>>
【模板】最小生成树
查看>>
设计模式之结构型模式
查看>>
poj2569
查看>>
使用pygal_maps_world.i18n中数据画各大洲地图
查看>>
jQuery EasyUI 的下拉选择combobox后台动态赋值
查看>>
timeline时间轴进度“群英荟萃”
查看>>
python if else elif statement
查看>>