Servlet

使用Servlet进行增删改查

步骤

1.  导入以下几个jar包到WEB-INF下的lib包里,必要时build path,其中jstl.jar和standard.jar是使用jstl要用的(eclipse中)

2.  写对应的dao,service,以及实现类

3.  写对应的servlet类,必须继承HttpServlet类

  1. 在此servlet类里加私有的service实现类;
  2. 添加doPost()和doGet方法:一般是在doPost()里写具体操作代码,doGet()方法里调用doPost,这样,不管提交方式是post还是get,都可以访问;
  3. doPost()方法里要先加

request.setCharacterEncoding("utf-8");

response.setContentType("text/html;charset=utf-8");

  1. 取参和传参,转发和重定向

取参:

String age1=request.getParameter("age");

int age = Integer.parseInt(age1);

传参:

request.setAttribute("emp", emp);

request.getRequestDispatcher("/emp.jsp").forward(request, response);

重定向:

response.sendRedirect(request.getContextPath()+"/error.jsp");

5配置web.xml,写对应的servlet和其映射

访问时:先通过url定位到web.xml里servlet的url-pattern,再对应到servlet-name,再找到对应的servlet类,根据访问时提交的方法调用相应的doPost()或者doGet()方法

6.写对应的前台页面

取后台传过来的数据:${ }

提交的url路径:

<form  action="/servletTest/updateEmp" method="post"></form>

<a  href="/servletTest/deleteEmp?id=${emp.id }">删除</a>

示例代码

DbUtil.java

package util;

import org.apache.commons.dbutils.QueryRunner;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DbUtil {

private static ComboPooledDataSource ds=new ComboPooledDataSource();

public static QueryRunner getQueryRunner(){
QueryRunner qr = new QueryRunner(ds);
return qr;
}

}

c3p0-config.xml

<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost/test</property>
<property name="user">root</property>
<property name="password"></property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">10</property>
</default-config>
</c3p0-config>

EmpDao.java

package dao;

import java.util.List;

import entity.Emp;

public interface EmpDao {

public int add(Emp emp);
public int delete(int id);
public int update(Emp emp);
public Emp find(int id);
public List<Emp> findAll();
}

EmpDaoImpl.java

package dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import util.DbUtil;
import dao.EmpDao;
import entity.Emp;

public class EmpDaoImpl implements EmpDao {

QueryRunner qr = DbUtil.getQueryRunner();
@Override
public int add(Emp emp) {
String sql="insert into emp(age,name) values(?,?) ";
int num=0;
try {
num = qr.update(sql, emp.getAge(),emp.getName());
} catch (SQLException e) {
e.printStackTrace();
}
return num;
}
@Override
public List<Emp> findAll() {
String sql="select*from emp";
List<Emp> emps=null;
try {
emps=qr.query(sql, new BeanListHandler<Emp>(Emp.class));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return emps;
}
@Override
public int delete(int id) {
String sql="delete from emp where id="+id;
int num=0;
try {
num=qr.update(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return num;
}
@Override
public int update(Emp emp) {
String sql="update emp set name=?,age=? where id=?";
System.out.println("sql---------"+sql);
int num=0;
try {
num=qr.update(sql, emp.getName(),emp.getAge(),emp.getId());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return num;
}
@Override
public Emp find(int id) {
String sql="select * from emp where id="+id;
Emp emp=null;
try {
emp=qr.query(sql, new BeanHandler<Emp>(Emp.class));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return emp;
}

}

EmpService.java

package service;

import java.util.List;

import entity.Emp;

public interface EmpService {

public int addEmp(Emp emp);
public List<Emp> findAll();
public int delete(int id);
public int update(Emp emp);
public Emp find(int id);
}

EmpServiceImpl.java

package service.impl;

import java.util.List;

import service.EmpService;
import dao.impl.EmpDaoImpl;
import entity.Emp;

public class EmpServiceImpl implements EmpService {

private EmpDaoImpl empDao=new EmpDaoImpl();
@Override
public int addEmp(Emp emp) {
int num = empDao.add(emp);
return num;
}
@Override
public List<Emp> findAll() {

return empDao.findAll();
}
@Override
public int delete(int id) {

return empDao.delete(id);
}
@Override
public int update(Emp emp) {

return empDao.update(emp);
}
@Override
public Emp find(int id) {
return empDao.find(id);
}

}

AddEmpServlet.java

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 service.impl.EmpServiceImpl;
import entity.Emp;

public class AddEmpServlet extends HttpServlet {

private EmpServiceImpl empService=new EmpServiceImpl();
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String age1=request.getParameter("age");
int age = Integer.parseInt(age1);
String name = request.getParameter("name");
Emp emp=new Emp();
emp.setAge(age);
emp.setName(name);
int num = empService.addEmp(emp);
if(num>0){
response.sendRedirect(request.getContextPath()+"/empList");
}else{
response.sendRedirect(request.getContextPath()+"/error.jsp");
}
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);;
}
}

DeleteEmpServlet.java

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 service.impl.EmpServiceImpl;
import entity.Emp;

public class DeleteEmpServlet extends HttpServlet {

private EmpServiceImpl empService=new EmpServiceImpl();

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String id1 = request.getParameter("id");
Integer id=Integer.parseInt(id1);
System.out.println("进入删除,id="+id);
int num = empService.delete(id);
System.out.println("删除?---"+num);
if(num>0){
response.sendRedirect(request.getContextPath()+"/empList");
}else{
response.sendRedirect("/error.jsp");
}
}

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}

//修改时,先找到要修改的对象,再转发到需要修改的页面,显示要修改的对象信息,然后提交时修改

FindUpdEmpServlet .java

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 entity.Emp;
import service.impl.EmpServiceImpl;

public class FindUpdEmpServlet extends HttpServlet {

private EmpServiceImpl empService=new EmpServiceImpl();

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
Integer id=Integer.parseInt(request.getParameter("id"));
Emp emp = empService.find(id);
System.out.println("要修改的emp"+emp.getName());
if(emp!=null){
request.setAttribute("emp", emp);
request.getRequestDispatcher("/update.jsp").forward(request, response);;
}else{
response.sendRedirect(request.getContextPath()+"/error.jsp");
}
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}

}

UpdateEmpServlet.java

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 service.impl.EmpServiceImpl;
import entity.Emp;

public class UpdateEmpServlet extends HttpServlet {

private EmpServiceImpl empService=new EmpServiceImpl();

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String id1 = request.getParameter("id");
Integer id=Integer.parseInt(id1);
String name = request.getParameter("name");
String age1 = request.getParameter("age");
Integer age=Integer.parseInt(age1);
Emp emp=new Emp();
emp.setId(id);
emp.setAge(age);
emp.setName(name);
//empService.find(id);
int num = empService.update(emp);
if(num>0){
response.sendRedirect(request.getContextPath()+"/empList");
}else{
response.sendRedirect("/error.jsp");
}
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}

}

FindEmpServlet.java

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 entity.Emp;
import service.impl.EmpServiceImpl;

public class FindEmpServlet extends HttpServlet {

private EmpServiceImpl empService=new EmpServiceImpl();
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
Integer id=Integer.parseInt(request.getParameter("id"));
Emp emp = empService.find(id);
System.out.println("emp---"+emp.getName()+"---"+emp.getAge());
if(emp!= null){
request.setAttribute("emp", emp);
request.getRequestDispatcher("/emp.jsp").forward(request, response);
}else{
response.sendRedirect(request.getContextPath()+"/error.jsp");
}
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}

FindEmpsServlet.java

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 entity.Emp;
import service.impl.EmpServiceImpl;

public class FindEmpsServlet extends HttpServlet {

private EmpServiceImpl empService=new EmpServiceImpl();

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
List<Emp> emps = empService.findAll();
if(emps!=null){
request.setAttribute("emps", emps);
request.getRequestDispatcher("/list.jsp").forward(request, response);
}else{
response.sendRedirect(request.getContextPath()+"/error.jsp");
}
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>servletTest</display-name>
<servlet>
<servlet-name>addEmp</servlet-name>
<servlet-class>servlet.AddEmpServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>deleteEmp</servlet-name>
<servlet-class>servlet.DeleteEmpServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>findUpdEmp</servlet-name>
<servlet-class>servlet.FindUpdEmpServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>updateEmp</servlet-name>
<servlet-class>servlet.UpdateEmpServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>findEmp</servlet-name>
<servlet-class>servlet.FindEmpServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>empList</servlet-name>
<servlet-class>servlet.FindEmpsServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>addEmp</servlet-name>
<url-pattern>/addEmp</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>deleteEmp</servlet-name>
<url-pattern>/deleteEmp</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>findUpdEmp</servlet-name>
<url-pattern>/findUpdEmp</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>updateEmp</servlet-name>
<url-pattern>/updateEmp</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>findEmp</servlet-name>
<url-pattern>/findEmp</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>empList</servlet-name>
<url-pattern>/empList</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

前台页面

add.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>添加员工</title>
</head>
<body>
<form action="/servletTest/addEmp" method="post">
姓名:<input type="text" name="name"/><p>
年龄:<input type="text" name="age"/><p>
<input type="submit" value="添加"/>
</form>
</body>
</html>

list.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>员工列表</title>
</head>
<body>
添加成功
<table>
<tr >
<td colspan="3">
<a href="index.jsp">添加</a>
</td>
</tr>
<tr>
<th>编号</th>
<th>年龄</th>
<th>age</th>
<th colspan="3">操作</th>
</tr>
<!--items里面写${requestScope.emps}也可以 -->
<c:forEach items="${emps }" var="emp" varStatus="vs">
<tr>
<td>${emp.id }</td>
<td>${emp.name }</td>
<td>${emp.age }</td>
<td><a href="/servletTest/deleteEmp?id=${emp.id }">删除</a></td>
<td><a href="/servletTest/findUpdEmp?id=${emp.id }">修改</a></td>
<td><a href="/servletTest/findEmp?id=${emp.id }">查看</a></td>
</tr>

</c:forEach>
</table>
</body>
</html>

emp.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
编号:${emp.id }<p>
姓名:${emp.name }<p>
年龄:${emp.age }
</body>
</html>

update.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>修改员工</title>
</head>
<body>
<form action="/servletTest/updateEmp" method="post">
编号:<input type="text" name="id" value="${emp.id }" readonly="readonly"/><p>
姓名:<input type="text" name="name" value="${emp.name }"/><p>
年龄:<input type="text" name="age" value="${emp.age }"/><p>
<input type="submit" value="提交"/>
</form>
</body>
</html>

error.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<h1>出错了</h1>
</body>
</html>

servlet增删改查的更多相关文章

  1. 12 Servlet_04 Servlet增删改查 静态页面与动态页面 EL表达式 table表格的一些样式

    今天学习了servlet的增删改查: 存储数据 setAttribute(String name,Object obj );获取数据 getAttribute(String name);删除数据 re ...

  2. 最简单的jsp+servlet的增删改查代码

    package ceet.ac.cn.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.s ...

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

    1.DAO模式 分包:依次建立 entity:实体包,放的是跟oracle数据库中表结构相对应的对象的属性,也就是这个对象有什么 dao:增删改查接口,实现增删改查的具体方法 service:同dao ...

  4. 数据库中的记录通过servlet回显到jsp页面中(连接数据库或者查询參照:对数据进行增删改查)

    我们常常会用到通过图书的名称来查询图书那么这种话我们也就会使用到从数据库中搜索出数据而且载入到自己的Jsp页面中 这种话我们须要将从数据库中获取到的数据放进响应中然后通过%=request.getAt ...

  5. jsp-2 简单的servlet连接mysql数据库 增删改查

    连接mysql数据库的操作 有增删改查 用的包有 commons-lang3-3.5 mysql-connector-java-5.1.40-bin 但是实际上也就是 数据查询和数据处理两种 所以对数 ...

  6. JavaWeb程序利用Servlet的对SQLserver增删改查操作

    声明:学了几天终于将增删改查的操作掌握了,也发现了一些问题,所以总结一下. 重点:操作数据库主要用的是SQL语句跟其他无关. 一:前提知识:PreparedStatement PreperedStat ...

  7. Servlet练习:实现增删改查的综合练习

    ---恢复内容开始--- 本文为原创,转载请注明出处:https://www.cnblogs.com/Tom-shushu/p/9383066.html 本篇内容主要介绍:通过Servlet,JSP, ...

  8. JSP+Servlet+JavaBean实现数据库的增删改查

    基本思想:JSP文件显示页面,使用form或href超链接传值到Servlet中方法,在Servlet方法中调用Dao层的类对象,实现对数据库里的数据的增删改查,之后重新返回到JSP输出操作完的结果. ...

  9. mysql+servlet+jsp实现数据库的增删改查

    首先,了解数据库目前我们仅仅用来存放数据,在这里我们在数据库中生成一个表,包含id,classname,teacher,location.Tomcat用来配置eclipse,只有这样我们才能使用JSP ...

随机推荐

  1. gradle的安装配置成功标志

    gradle主要位于AndroidStudio中 看我的目录 在环境变量里添加用户变量 GRADLE_HOME 然后在环境变量 path 中增加 %GRADLE_HOME%\bin;,如图所示 测试配 ...

  2. 对于Arrays的deep相关的方法。

    关于: deepEquals Arrays.equals(Object[] o1, Object[] o2):当是判断数组是引用类型数组的时候,从以下条件判断: 1.o1与o2指向同一个数组实例时,返 ...

  3. python字符串的常用方法

  4. Counted(内存管理机制)

    class Counted { private: unsigned int count_; public: Counted() : count_() { } virtual ~Counted() { ...

  5. VUE通过id从列表页跳转到相对的详情页

    新闻列表页面: 在这里我用a标签进行跳转,在vue里面可以这样写<router-link></router-link> 1 <router-link :to=" ...

  6. jq实现百度图片移入移出内容提示框上下左右移动的效果

    闲来无聊,看到百度图片hover的时候提示框的效果,遂想试一试自己能否实现. 百度图片hover的效果: 需求: 1. 当鼠标从图片上部移入的时候,提示框从上部移到正常位置.从上部移出的时候,提示框从 ...

  7. fuel6.0安装部署

    在经过一系列安装openstack方式后,个人觉得fuel的安装方式相对简易,接下来记录下安装部署fuel6.0的过程.本教程适合想把fuel6.0部署后,云主机需要连接外网的需求. 安装virtua ...

  8. nGrinder TestRunner XFF / X-Forwarded-For

    s 我们在压测请求报文里面带了这个"x-forward-for":"10.24.51.132"这个字段,所以我们所有的压测请求穿透到应用系统的时候,应用系统上采 ...

  9. 解决pycharm问题:module 'pip' has no attribute 'main'

    问题 更新pip之后,Pycharm安装package出现如下报错: 解决 找到安装目录下 helpers/packaging_tool.py文件,找到如下代码: 修改为如下,保存即可.

  10. Windows下的包管理工具-Scoop

    关于scoop的介绍 https://www.jianshu.com/p/bb0ba62b519c https://blog.csdn.net/fcymk2/article/details/86653 ...