第二十四天 Servlet+jsp+mysql+navicat的增删改查以及视图
来源:互联网 发布:青少年行知实践园图片 编辑:程序博客网 时间:2024/05/29 04:54
1.entity包放的是实体类,也就是实体类的属性与数据库中的表中的字段名(就是所谓的列名),进行映射的关系。
create database test02 default character set gbk;use test02create table person(id int primary key auto_increment,name varchar(20),salary varchar(20),age varchar(2));insert into person (name,salary,age) values("猪八戒","12321","12");jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=gbk
package com.entity;/** * 项目名称:web04 * 类名称:Person * 类描述: 存储数据库中的信息,实体类中的属性对应数据库值的字段 * 创建人:Administrator * 创建时间:2017年5月30日 下午12:38:12 * 修改人:Administrator * 修改时间:2017年5月30日 下午12:38:12 * 修改备注: * @version * */public class Person { private int id; private String name; private String salary; private String age; 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 getSalary() { return salary; } public void setSalary(String salary) { this.salary = salary; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((age == null) ? 0 : age.hashCode()); result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((salary == null) ? 0 : salary.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age == null) { if (other.age != null) return false; } else if (!age.equals(other.age)) return false; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (salary == null) { if (other.salary != null) return false; } else if (!salary.equals(other.salary)) return false; return true; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", salary=" + salary + ", age=" + age + "]"; } }2.dao层有关数据库操作的接口和实现类
package com.dao;import java.sql.SQLException;import java.util.List;import com.entity.Person;/** * 项目名称:web04 * 类名称:PersonDao * 类描述:完成数据库操作的业务处理 * 创建人:Administrator * 创建时间:2017年5月30日 下午12:51:48 * 修改人:Administrator * 修改时间:2017年5月30日 下午12:51:48 * 修改备注: * @version */public interface PersonDao { //查看 public List<Person> findAll() throws ClassNotFoundException, SQLException; //添加 public void Save(Person p) throws ClassNotFoundException, SQLException; //根据用户id查找用户 public Person findById(int id) throws ClassNotFoundException, SQLException; //根据用户id修改用户 public void update(Person p) throws ClassNotFoundException, SQLException; //删除 public void delete(int id) throws ClassNotFoundException, SQLException;}
package com.dao;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.List;import com.entity.Person;import com.util.DBUtils;public class PersonDaoImpl implements PersonDao { @Override public List<Person> findAll() { // TODO Auto-generated method stub //构造集合建立数据库链接 List<Person> lists=new ArrayList<Person>(); Connection conn = null; try { conn = DBUtils.getConn(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } String sql="select id,name,salary,age from person"; Statement st=null; try { st = conn.createStatement(); ResultSet rs=st.executeQuery(sql); while(rs.next()){ Person p=new Person(); p.setId(rs.getInt(1)); p.setName(rs.getString(2)); p.setSalary(rs.getString(3)); p.setAge(rs.getString(4)); lists.add(p); } DBUtils.closeConn(conn); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return lists; } //增加用户的方法 @Override public void Save(Person p) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub Connection conn=DBUtils.getConn(); String sql="insert into person(name,salary,age) values(?,?,?)"; PreparedStatement ps=conn.prepareStatement(sql); ps.setString(1, p.getName()); ps.setString(2, p.getSalary()); ps.setString(3, p.getAge()); ps.executeUpdate(); DBUtils.closeConn(conn); } //根据id查找用户 @Override public Person findById(int id) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub Connection conn=DBUtils.getConn(); String sql="select * from person where id='"+id+"'"; Statement st=conn.createStatement(); ResultSet rs=st.executeQuery(sql); Person p = new Person(); while(rs.next()){ String name=rs.getString("name"); String salary=rs.getString("salary"); String age=rs.getString("age"); p.setId(id); p.setName(name); p.setAge(age); p.setSalary(salary); } return p; } //根据所传用户修该数据库用户信息 @Override public void update(Person p) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub Connection conn=DBUtils.getConn(); String sql="update person set name='"+p.getName()+"',salary='"+p.getSalary()+"',age='"+p.getAge()+"' where id='"+p.getId()+"'"; Statement st=conn.createStatement(); st.executeUpdate(sql); } //根据id删除用户 @Override public void delete(int id) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub Connection conn=DBUtils.getConn(); String sql="delete from person where id='"+id+"'"; Statement st=conn.createStatement(); st.executeUpdate(sql); DBUtils.closeConn(conn); }}
3.service层,逻辑操作的接口以及实现类
package com.service;import java.sql.SQLException;import java.util.List;import com.entity.Person;//有关person的业务逻辑接口public interface PersonService { //查看 public List<Person> findAll() throws ClassNotFoundException, SQLException; //添加 public void save(Person p) throws ClassNotFoundException, SQLException; //根据用户id查找用户 public Person findById(int id) throws ClassNotFoundException, SQLException; //根据用户id修改用户 public void update(Person p) throws ClassNotFoundException, SQLException; //删除 public void delete(int id) throws ClassNotFoundException, SQLException;}
package com.service;import java.sql.SQLException;import java.util.List;import com.dao.PersonDao;import com.entity.Person;public class PersonServiceImpl implements PersonService { //可以创建子类对象指向父类引用,多态的形式 private PersonDao dao; public PersonServiceImpl(PersonDao dao) { this.dao = dao; } @Override public List<Person> findAll() throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub return dao.findAll(); } @Override public void save(Person p) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub dao.Save(p); } @Override public Person findById(int id) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub return dao.findById(id); } @Override public void update(Person p) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub dao.update(p); } @Override public void delete(int id) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub dao.delete(id); }}
4.web层,Servlet类,负责把Service和jsp连接
package com.web;import java.io.IOException;import java.sql.SQLException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.dao.PersonDao;import com.dao.PersonDaoImpl;import com.entity.Person;import com.service.PersonService;import com.service.PersonServiceImpl;//将数据显示在浏览器页面@SuppressWarnings("serial")public class PersonServlet extends HttpServlet{ protected void service(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{ //设置请求响应的编码 request.setCharacterEncoding("GBK"); response.setContentType("text/html;charset=GBK"); //获取uri,也就是请求的方式 String uri=request.getRequestURI(); String path=uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf(".")); //实例化一个PersonDao接口实现类的对象 PersonDao dao=new PersonDaoImpl(); PersonService service=new PersonServiceImpl(dao); if(path.equals("/list")){ try { List<Person> lists=service.findAll(); request.setAttribute("lists", lists); //转发// RequestDispatcher dispatcher=request.getRequestDispatcher("list.jsp");// dispatcher.forward(request, response); request.getRequestDispatcher("WEB-INF/list.jsp").forward(request, response); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServletException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else if(path.equals("/add")){ Person p=new Person(); p.setName( request.getParameter("name")); p.setAge(request.getParameter("age")); p.setSalary(request.getParameter("salary")); // out.println("<h1>用户添加成功!</h1>"); try { service.save(p); response.sendRedirect("list.do");// request.getRequestDispatcher("WEB-INF/list.jsp").forward(request, response); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else if(path.equals("/regist")){ //转发是同一个服务器的容器中一个组件向另外的一个组件发送请求 request.getRequestDispatcher("WEB-INF/index.jsp").forward(request, response); //重定向是直接访问地址 //response.sendRedirect("WEB-INF/index.jsp"); }else if(path.equals("/delete")){ try { service.delete(Integer.parseInt(request.getParameter("deleteId"))); response.sendRedirect("list.do"); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else if(path.equals("/modify")){ try { Person p= dao.findById(Integer.parseInt(request.getParameter("modifyId"))); request.setAttribute("person", p); request.getRequestDispatcher("WEB-INF/modify.jsp").forward(request, response);; } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else if(path.equals("/update")){ Person p=new Person(); p.setId(Integer.parseInt(request.getParameter("id"))); p.setName(new String(request.getParameter("name").getBytes("ISO-8859-1"),"GBK")); // p.setName(request.getParameter("name")); p.setAge(request.getParameter("age")); p.setSalary(request.getParameter("salary")); try { service.update(p); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } response.sendRedirect("list.do"); }else if(path.equals("/view")){ try { Person p= service.findById(Integer.parseInt(request.getParameter("viewId"))); request.setAttribute("person" ,p); request.getRequestDispatcher("WEB-INF/view.jsp").forward(request, response); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}
5.utitl有关工具
package com.util;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;//与数据库有关操作的工具类public class DBUtils { public static Connection getConn() throws ClassNotFoundException, SQLException{ Class.forName("com.mysql.jdbc.Driver"); Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=GBK","root","1234"); return conn; } public static void closeConn(Connection conn) throws SQLException{ if(conn!=null){ conn.close(); } }}
6.四张WEB-INF下的jsp页面依次为index注册,list显示用户.modify修改用户.view显示某个用户的视图
<%@ page language="java" import="java.util.*,java.text.* " pageEncoding="GBK"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <% Date date=new Date(); SimpleDateFormat st=new SimpleDateFormat("yyyy-MM-dd"); st.format(date); %> <title>用户注册界面</title> <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--> </head> <body> <h1>用户注册界面(<%=st.format(date)%>)</h1><form action="add.do" method="post" ><table border="1px"><tr><td>name:</td><td><input type="text" name="name"/></td></tr><tr><td>salary:</td><td><input type="text" name="salary"/></td></tr><tr><td>age:</td><td><input type="text" name="age"/></td></tr><tr><td colspan="2"><input type="submit" value="提交"/></td></tr></table></form> </body></html>
<%@ page language="java" import="java.util.*,com.entity.*" pageEncoding="GBK" contentType="text/html;charset=GBK"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'list.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--> </head> <body> <h1>用户信息表</h1> <table border="1px"> <tr><td><id>id</id></td><td><name>name</name></td><td><age>age</age></td><td><salary>salary</salary></td><td><delete>delete</delete></td><td><update>update</update></td> </tr> <% List<Person> lists=(List<Person>)request.getAttribute("lists"); Iterator<Person> it=lists.iterator();while(it.hasNext()){ Person p=it.next(); int id=p.getId(); String name=p.getName(); String salary=p.getSalary(); String age=p.getAge();%><tr><td><%=id%></td><td><a href="view.do?viewId=<%=id%>"><%=name%></a></td><td><%= age%></td><td><%= salary%></td><td><a href="delete.do?deleteId=<%=id%>">delete</a></td><td><a href="modify.do?modifyId=<%=id %>">update</a></td></tr> <% } %> </table> <h1><a href="regist.do">继续注册!</a></h1> </body></html>
<%@ page language="java" import="java.util.*,com.entity.*" pageEncoding="GBK" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"s> <title>My JSP 'list.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--> </head> <body> <h1>修改用户信息</h1> <form action="update.do"> <table border="1px"> <tr><td>id</td><td>name</td><td>age</td><td>salary</td><td rowspan="2"> <input type="submit" value="提交"/></td> </tr> <% Person p =(Person)request.getAttribute("person"); int id=p.getId(); String name=p.getName(); String salary=p.getSalary(); String age=p.getAge();%><tr><td><input type="text" name="id" value=<%=id%>></td><td><input type="text" name="name" value=<%=name%>></td><td><input type="text" name="age" value=<%= age%>></td><td><input type="text" name="salary" value=<%= salary%>></td></tr> </table> </form> </body></html>
<%@ page language="java" import="java.util.*" import="com.entity.*" pageEncoding="GBK"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>用户信息视图</title> <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--> </head> <body> <h1>用户信息视图</h1><table border="1px"> <tr><td>id</td><td>name</td><td>age</td><td>salary</td> </tr> <% Person p =(Person)request.getAttribute("person"); int id=p.getId(); String name=p.getName(); String salary=p.getSalary(); String age=p.getAge();%><tr><td><input type="text" disabled="disabled" name="id" value=<%=id%>></td><td><input type="text" disabled="disabled" name="name" value=<%=name%>></td><td><input type="text" name="age" disabled="disabled" value=<%= age%>></td><td><input type="text" disabled="disabled" name="salary" value=<%= salary%>></td></tr> </table> <a href="list.do">返回用户列表</a> </body></html>
8.xml文件
<?xml version="1.0" encoding="ISO-8859-1"?><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_2_5.xsd" version="2.5"> <servlet> <servlet-name>myWeb</servlet-name> <servlet-class>com.web.PersonServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>myWeb</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <error-page> <error-code>405</error-code> <location>/error.html</location> </error-page></web-app>
阅读全文
1 0
- 第二十四天 Servlet+jsp+mysql+navicat的增删改查以及视图
- mysql+jsp+servlet 增删改查实例
- jsp+servlet的增删改查页面
- jsp + servlet 增删改查
- jsp&servlet的登陆界面以及增删改查功能的实现
- JSP中链接MySQL数据库以及增删改查
- 最简单的jsp+servlet的增删改查代码
- jsp+servlet+jdbc实现对数据库的增删改查
- servlet jsp一套完整的增删查改思路
- Jsp+Servlet对数据库的增删改查
- jsp+servlet+jdbc实现对数据库的增删改查
- jsp+servlet+jdbc实现对数据库的增删改查
- jsp+servlet+jdbc实现对数据库的增删改查
- servlet的增删改查
- servlet+jsp数据库增删改查实例
- jsp+javabean+servlet实现增删改查
- extjs3.4+mysql+servlet的简单增删改查 分页
- mysql视图---增删改查(二)
- 一道js面试题的深入~
- 如何将java.util.date转化为文本格式
- jQuery基础知识
- nginx+tomcat+redis基本概念
- Netty中的SimpleChannelInboundHandler的通信过程
- 第二十四天 Servlet+jsp+mysql+navicat的增删改查以及视图
- 关于时间的操作(Java)
- golang中new和make简析
- [原]红帽 Red Hat Linux相关产品iso镜像下载
- struts2
- 微信小程序 四 wxss引用 wxml引用
- MyFlag Step9:app端与服务器端的代码编写
- 加勒比海盗5——死无对证
- Python笔记(三)购物车小程序