第二十四天 Servlet+jsp+mysql+navicat的增删改查以及视图

1.entity包放的是实体类,也就是实体类的属性与数据库中的表中的字段名(就是所谓的列名),进行映射的关系。

create database test02 default character set gbk;
use test02
create 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 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 findAll() {
        // TODO Auto-generated method stub
        //构造集合建立数据库链接
        List lists=new ArrayList();
        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 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 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 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("

用户添加成功!

"); 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+"/";
%>



  
    
    <%
    	Date date=new Date();	
    	SimpleDateFormat st=new SimpleDateFormat("yyyy-MM-dd");
    	st.format(date);
     %>
    
    用户注册界面
    
	
	
	    
	
	
	

  
   
  	
  		

用户注册界面(<%=st.format(date)%>)

name:
salary:
age:

<%@ 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+"/";
%>



  
    
    
    My JSP 'list.jsp' starting page
    
	
	
	    
	
	
	

  
  
  
  	

用户信息表

<% List lists=(List)request.getAttribute("lists"); Iterator 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(); %> <% } %>
id name age salary delete update
<%=id%><%=name%><%= age%><%= salary%>deleteupdate

继续注册!


<%@ page language="java" import="java.util.*,com.entity.*" pageEncoding="GBK" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



  
    
    
    My JSP 'list.jsp' starting page
    
	
	
	    
	
	
	

  
  
  
  	

修改用户信息

<% Person p =(Person)request.getAttribute("person"); int id=p.getId(); String name=p.getName(); String salary=p.getSalary(); String age=p.getAge(); %>
id name age salary
>>>>

<%@ page language="java" import="java.util.*" import="com.entity.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



  
    
    
    用户信息视图
    
	
	
	    
	
	
	

  
  
  
  		

用户信息视图

<% Person p =(Person)request.getAttribute("person"); int id=p.getId(); String name=p.getName(); String salary=p.getSalary(); String age=p.getAge(); %>
id name age salary
>>>>
返回用户列表

8.xml文件



  
    myWeb
    com.web.PersonServlet
  
  
    myWeb
    *.do
  
  
    405
    /error.html
  




你可能感兴趣的:(java_web)