java代码简单实现本地用户在浏览器端增、删、改、查
java代码简单实现本地用户在浏览器端增、删、改、查
1 准备
1.1 需要的软件、jar包、网页样式等
所有的资源我会在后面附上链接,供大家下载,一共分为两部分,一部分是单页全部显示,一部分是分页显示数据。
1.1.1 软件
IntelliJ IDEA
tomcat服务器
1.1.2 jar包
网页样式文件
1.2 提前准备工作
提前配置好tomcat和idea。
将jar包导入到idea中。
1.3 项目结构总览
2 实现步骤
2.1创建web三层架构、以及工厂包、工具包、javaBean包
2.2 导入web中的资源
2.3 敲代码
2.3.1 编写思想
借助idea强大的功能,可以反向编码
比如在servlet层中有需求,直接创建service层对象,调用想要使用的service层的方法(此时service层中还没有需要的方法),直接alt+回车,就可以在service层生成方法,再用service层调用dao层方法。
2.3.2 先写一个工具类,用来连接mysql数据库
使用druid连接池
其中beans.properties用做工厂类的简单配置文件,
druid配置文件中的内容
driverClass:com.mysql.jdbc.Driver
jdbcUrl:jdbc:mysql:///web(web替换成你数据库的名称)
username:root
password:root
beans配置文件中的内容
contactDao=com.lovejava.dao.ContactDao
contactService=com.lovejava.service.ContactService
创建JDBC工具类代码如下
// An highlighted block
package com.lovejava.utils;
import com.alibaba.druid.pool.DruidDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ResourceBundle;
public class JDBCUtils {
private static DruidDataSource dc = new DruidDataSource();
static {
ResourceBundle bundle = ResourceBundle.getBundle("druid-config");
String driverClass = bundle.getString("driverClass");
String jdbcUrl = bundle.getString("jdbcUrl");
String username = bundle.getString("username");
String password = bundle.getString("password");
dc.setDriverClassName(driverClass);
dc.setUrl(jdbcUrl);
dc.setUsername(username);
dc.setPassword(password);
}
public static Connection getConnection() throws SQLException {
return dc.getConnection();
}
public static DataSource getDataSource(){
return dc;
}
}
2.3.3 实现添加数据效果
在web.servlet包下创建BigServlet类,代码如下:
// An highlighted block
package com.lovejava.web.servlet;
import com.lovejava.domain.Contact;
import com.lovejava.domain.Page;
import com.lovejava.factory.BeanFactory;
import com.lovejava.service.ContactService;
import com.lovejava.service.IContactService;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
/**
* @author:tianyao
* @date:2019-03-11 21:32
*/
@WebServlet(name = "BigServlet", urlPatterns = "/big")
public class BigServlet extends HttpServlet {
private IContactService service = (IContactService) BeanFactory.creatBean("contactService");
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//处理POST请求的乱码问题
request.setCharacterEncoding("utf-8");
String action = request.getParameter("action");
//利用反射调用方法。
Class<? extends BigServlet> clazz = this.getClass();
try {
Method method = clazz.getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
method.invoke(this,request,response);
} catch (Exception e) {
e.printStackTrace();
}
//添加联系人
private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取请求参数.存在对象中。
Contact contact = new Contact();
try {
BeanUtils.populate(contact,request.getParameterMap());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//调用service层的添加数据方法
service.add(contact);
response.sendRedirect("big?action=showAll");
}
}
在domain包中创建用户对象存储查询到的数据信息和分页显示用来存放总页数、总数据条数、当前页、每一页显示的数据条数的对象。代码如下
Contact
// An highlighted block
package com.lovejava.domain;
public class Contact {
private Integer id;
private String name;
private String sex;
private int age;
private String address;
private String qq;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Contact{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", address='" + address + '\'' +
", qq='" + qq + '\'' +
", email='" + email + '\'' +
'}';
}
}
Page
// An highlighted block
package com.lovejava.domain;
import java.util.List;
/**
* @author:tianyao
* @date:2019-03-11 19:43
*/
public class Page {
private List<Contact> list;//本页数据
private Long dataCount;//总数据条数
private Integer pageSize;//每页数据数
private Long pageCount;//页数
private Long currentPage;//当前页
@Override
public String toString() {
return "Page{" +
"list=" + list +
", dataCount=" + dataCount +
", pageSize=" + pageSize +
", pageCount=" + pageCount +
", currentPage=" + currentPage +
'}';
}
public List<Contact> getList() {
return list;
}
public void setList(List<Contact> list) {
this.list = list;
}
public Long getDataCount() {
return dataCount;
}
public void setDataCount(Long dataCount) {
this.dataCount = dataCount;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Long getPageCount() {
return pageCount;
}
public void setPageCount(Long pageCount) {
this.pageCount = pageCount;
}
public Long getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Long currentPage) {
this.currentPage = currentPage;
}
}
创建工厂类,用来生成dao层,以及service层的对象。此处需要使用之前的beans.properties配置文件。
BeanFactory类
package com.lovejava.factory;
import java.util.ResourceBundle;
/**
* @author:tianyao
* @date:2019-03-12 10:29
*/
public class BeanFactory {
private static ResourceBundle bundle;
static {
//读取配置文件
bundle = ResourceBundle.getBundle("beans");
}
public static Object creatBean(String key){
//也就是获取对应的类的全限定名
String className = bundle.getString(key);
//使用反射创建对象
try {
Class<?> clazz = Class.forName(className);
return clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}}
service层用面向接口思想分别写出service类和其要实现的接口
ContactService类
// An highlighted block
package com.lovejava.service;
import com.lovejava.dao.IContactDao;
import com.lovejava.domain.Contact;
import com.lovejava.domain.Page;
import com.lovejava.factory.BeanFactory;
import java.util.List;
public class ContactService implements IContactService{
private IContactDao dao = (IContactDao) BeanFactory.creatBean("contactDao");
//添加联系人方法
@Override
public void add(Contact con) {
dao.add(con);
}
}
接口IContactService
// An highlighted block
package com.lovejava.service;
import com.lovejava.domain.Contact;
import com.lovejava.domain.Page;
import java.util.List;
/**
* @author:tianyao
* @date:2019-03-12 10:14
*/
public interface IContactService {
//添加联系人方法
void add(Contact con);
}
dao层同理
ContactDao类
// An highlighted block
package com.lovejava.dao;
import com.lovejava.domain.Contact;
import com.lovejava.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
public class ContactDao implements IContactDao{
//增加一行数据的方法
@Override
public void add(Contact con) {
JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
String sql = "insert into contact values(null,?,?,?,?,?,?)";
template.update(sql,con.getName(),con.getSex(),con.getAge(),con.getAddress(),con.getQq(),con.getEmail());
}
}
至此完成添加用户需求,其余分页显示、删除、修改、全部展示同理。
2.3.4 补充其他需求
原理类似添加参数方法
完成后的代码如下
BigServlet类
// An highlighted block
package com.lovejava.web.servlet;
import com.lovejava.domain.Contact;
import com.lovejava.domain.Page;
import com.lovejava.factory.BeanFactory;
import com.lovejava.service.ContactService;
import com.lovejava.service.IContactService;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
/**
* @author:tianyao
* @date:2019-03-11 21:32
*/
@WebServlet(name = "BigServlet", urlPatterns = "/big")
public class BigServlet extends HttpServlet {
private IContactService service = (IContactService) BeanFactory.creatBean("contactService");
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//处理POST请求的乱码问题
request.setCharacterEncoding("utf-8");
String action = request.getParameter("action");
//用反射技术调用方法
Class<? extends BigServlet> clazz = this.getClass();
try {
Method method = clazz.getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
method.invoke(this,request,response);
} catch (Exception e) {
e.printStackTrace();
}
}
//分页显示
private void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Long currentPage = Long.valueOf(request.getParameter("currentPage"));
Page page =service.findList(currentPage);
System.out.println(page);
request.setAttribute("page",page);
request.getRequestDispatcher("page.jsp").forward(request,response);
} //回显信息
private void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求参数id
int id = Integer.parseInt(request.getParameter("id"));
//调用service方法获取数据
Contact con = service.queryById(id);
//将数据转发到页面展示
request.setAttribute("con",con);
System.out.println("big"+con);
request.getRequestDispatcher("/update.jsp").forward(request,response);
}
//修改信息
private void update(HttpServletRequest request, HttpServletResponse response ) throws IOException {
Map<String, String[]> map = request.getParameterMap();
Contact contact = new Contact();
try {
BeanUtils.populate(contact,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//调用ContactService中的更新方法
Boolean flag = service.update(contact);
if (flag=true){
//跳转到list.jsp
response.sendRedirect("big?action=showAll");
}else {
response.getWriter().write("修改失败");
}
}
//删除联系人
private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
int id = Integer.parseInt(request.getParameter("id"));
service.delete(id);
//调用查询全部的servlet展示效果
response.sendRedirect("big?action=showAll");
}
//展示所有联系人
private void showAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//处理请求
List<Contact> list = service.showAll();
request.setAttribute("list",list);
request.getRequestDispatcher("list.jsp").forward(request,response);
}
//添加联系人
private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取请求参数.存在对象中。
Contact contact = new Contact();
try {
BeanUtils.populate(contact,request.getParameterMap());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//调用service层的添加数据方法
service.add(contact);
response.sendRedirect("big?action=showAll");
}
}
ContactService类
// An highlighted block
package com.lovejava.service;
import com.lovejava.dao.IContactDao;
import com.lovejava.domain.Contact;
import com.lovejava.domain.Page;
import com.lovejava.factory.BeanFactory;
import java.util.List;
public class ContactService implements IContactService{
private IContactDao dao = (IContactDao) BeanFactory.creatBean("contactDao");
//分页显示
@Override
public Page findList(Long currentPage) {
Page page = new Page();
page.setCurrentPage(currentPage);
//设置每一页的数据条数
Integer pageSize = 3;
page.setPageSize(pageSize);
//设置总数据条数
Long dataCount = dao.dataCount();
page.setDataCount(dataCount);
//设置总页数
Long pageCount = dataCount%pageSize == 0 ? dataCount/pageSize:dataCount/pageSize+1;
page.setPageCount(pageCount);
//获取到当前页码的数据集合
List<Contact> list = dao.findList(currentPage, pageSize);
page.setList(list);
return page;
}
//展示所有人信息
@Override
public List<Contact> showAll() {
//调用DAO层方法
List<Contact> list = dao.findAll();
return list;
}
//添加联系人方法
@Override
public void add(Contact con) {
dao.add(con);
}
//删除方法
@Override
public void delete(int id) {
dao.delete(id);
}
//通过ID查询数据并回显方法
@Override
public Contact queryById(int id) {
Contact contact = dao.queryById(id);
return contact;
}
//修改数据
@Override
public Boolean update(Contact contact){
Boolean flag = dao.update(contact);
return flag;
}
}
IContactService接口
// An highlighted block
package com.lovejava.service;
import com.lovejava.domain.Contact;
import com.lovejava.domain.Page;
import java.util.List;
/**
* @author:tianyao
* @date:2019-03-12 10:14
*/
public interface IContactService {
//分页显示
Page findList(Long currentPage);
//展示所有人信息
List<Contact> showAll();
//添加联系人方法
void add(Contact con);
//删除方法
void delete(int id);
//通过ID查询数据并回显方法
Contact queryById(int id);
//修改数据
Boolean update(Contact contact);
}
ContactDao类
// An highlighted block
package com.lovejava.dao;
import com.lovejava.domain.Contact;
import com.lovejava.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
public class ContactDao implements IContactDao{
//获得总条数
@Override
public Long dataCount() {
String sql = "select count(*) from contact;";
JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
Long dataCount = template.queryForObject(sql, Long.class);
return dataCount;
}
//获得当前页面要显示的数据集合
@Override
public List<Contact> findList(Long currentPage, Integer pageSize) {
JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
String sql = "select * from contact limit ? ,?;";
List<Contact> list = template.query(sql,new BeanPropertyRowMapper<>(Contact.class),(currentPage-1)*pageSize,pageSize);
return list;
}
//查询到所有信息的方法
@Override
public List<Contact> findAll() {
JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
String sql = "select * from contact";
List<Contact> list = null;
try {
list = template.query(sql,new BeanPropertyRowMapper<>(Contact.class));
}catch (Exception e){
e.printStackTrace();
}
return list;
}
//增加一行数据的方法
@Override
public void add(Contact con) {
JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
String sql = "insert into contact values(null,?,?,?,?,?,?)";
template.update(sql,con.getName(),con.getSex(),con.getAge(),con.getAddress(),con.getQq(),con.getEmail());
}
//删除一行数据方法
@Override
public void delete(int id) {
JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
String sql= "delete from contact where id = ?";
template.update(sql,id);
}
//数据回显方法
@Override
public Contact queryById(int id) {
JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
String sql = "select * from contact where id = ?;";
Contact contact=null;
try {
contact = template.queryForObject(sql, new BeanPropertyRowMapper<>(Contact.class),id);
System.out.println("dao"+contact);
}catch (Exception e){
e.printStackTrace();
}
return contact;
}
//修改数据方法
@Override
public Boolean update(Contact contact) {
JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
String sql= "update contact set sex = ?,age = ? ,address = ? ,qq = ? ,email = ? where id = ?";
int i = template.update(sql, contact.getSex(), contact.getAge(), contact.getAddress(), contact.getQq(), contact.getEmail(), contact.getId());
Boolean flag = false;
if (i!=0){
flag=true;
}
return flag;
}
}
IContactDao接口
package com.lovejava.dao;
import com.lovejava.domain.Contact;
import java.util.List;
/**
* @author:tianyao
* @date:2019-03-12 10:22
*/
public interface IContactDao {
//获得总条数
Long dataCount();
//获得当前页面要显示的数据集合
List<Contact> findList(Long currentPage, Integer pageSize);
//查询到所有信息的方法
List<Contact> findAll();
//增加一行数据的方法
void add(Contact con);
//删除一行数据方法
void delete(int id);
//数据回显方法
Contact queryById(int id);
//修改数据方法
Boolean update(Contact contact);
}
完成!
3 总结
编写过程主要用到了JAVA中面向接口编程、反射、封装属性等思想。还有很多不足支持,努力学习,分享一下。
链接: https://pan.baidu.com/s/1G067JWUXTT9gBi1XpEtvzg.
提取码:a21u