Java web

Wesley13
• 阅读 438

上次我们已经搞完了jsp的操作。现在该是后台的配置了。

在dao包里面进行数据链接:DBConn.java

/**
 * 
 */
/**
 * @author Administrator
 *
 */
package dao;

import java.sql.*;
public class DBConn {
    /**
     * 链接数据库
     * @return
     */
     public static Connection getConnection(){
         Connection conn=null;
         try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DataBaseName=EstateDB","sa","123456");
        } catch (Exception e) {
            e.printStackTrace();
        }
         return conn;
     }
}

BuildingDao.java

package 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 entity.Building;




public class BuildingDao {
  /**
   * 操作数据库命令链接
   * 数据访问类
   */
    private Connection conn;
    private Statement state;
    private ResultSet rs;
    private PreparedStatement pre;
    /**
     * 查询全部
     * @return
     * @throws SQLException
     */
    public List<Building> fill() throws SQLException {
        List<Building> list = new ArrayList<Building>();
        String sql = "select * from T_building";
        conn = DBConn.getConnection();
        state = conn.createStatement();
        rs = state.executeQuery(sql);
        Building p = null;
        while (rs.next()) {
            p = new Building();                
            p.setId(rs.getString("Id"));
            p.setCompany(rs.getString("Company"));
            p.setPhone(rs.getString("Phone"));
            p.setDescription(rs.getString("Description"));
            p.setStatus(rs.getString("Status"));
            list.add(p);
        }
        rs.close();
        state.close();
        conn.close();
        return list;
    }
    /**
     * 根据Id查询
     * @param Id
     * @return
     * @throws SQLException
     */
public Building fill(String Id) throws SQLException{
        
        conn = DBConn.getConnection();
        String sql="select * from T_building where Id=?";
        pre = conn.prepareStatement(sql);
        pre.setString(1, Id);
        rs=pre.executeQuery();
        Building p = null;
        if(rs.next()){
            p = new Building();                
            p.setId(rs.getString("Id"));
            p.setCompany(rs.getString("Company"));
            p.setPhone(rs.getString("Phone"));
            p.setDescription(rs.getString("Description"));
            p.setStatus(rs.getString("Status"));
        }
        rs.close();
        pre.close();
        conn.close();
        return p;
    }
/**
 * 添加
 * @param building
 * @return
 * @throws SQLException
 */
    public int add(Building building) throws SQLException {

        String sql = "insert  T_building values ('" + building.getId() + "','"
                + building.getCompany() + "','" + building.getPhone() + "','"
                + building.getDescription() + "','" + building.getStatus()
                + "')";
        System.out.println(sql);
        conn = DBConn.getConnection();
        state = conn.createStatement();        
        int result = state.executeUpdate(sql);
        state.close();
        conn.close();
        return result;

    }
    /**
     * 修改
     * @param building
     * @return
     * @throws SQLException
     */
    public int  update(Building  building) throws SQLException {
        String sql="UPDATE T_building SET Company=?,Phone =?,"+"Description=?, Status=? WHERE Id=?";
        conn=DBConn.getConnection();
        pre = conn.prepareStatement(sql);
        pre.setString(1,  building.getCompany());
        pre.setString(2,  building.getPhone());
        pre.setString(3,  building.getDescription());
        pre.setString(4,  building.getStatus());
        pre.setString(5,  building.getId());
        int count=pre.executeUpdate();
        pre.close();
        conn.close();
        return count;        
        // TODO Auto-generated method stub
        
    }
/**
 * 根据ID删除一项
 * @param Id
 * @throws SQLException
 */
    public void  delete(String Id) throws SQLException {
        String sql="delete from  T_building where  Id=?";
        conn=DBConn.getConnection();
        pre = conn.prepareStatement(sql);
        pre.setString(1,Id);
        pre.executeUpdate();
        pre.close();
        conn.close();                
        // TODO Auto-generated method stub        
    }
    /**
     * 多项选择Id删除
     * @param Id
     * @throws SQLException
     */
    public void  delete(String[] Id) throws SQLException {
        conn = DBConn.getConnection();
        String ids="'"+Id[0]+"'";
        for(int i=1;i<Id.length;i++) {
            ids=ids+",'"+Id[i]+"'";
        }
        String sql="delete from  T_building where  Id  in ("+ids+")";
        pre = conn.prepareStatement(sql);        
        pre.executeUpdate();
        pre.close();
        conn.close();                
        // TODO Auto-generated method stub        
    }
}

对啦,忘记创建实体类了。在entity包里面建实体类

Building.java

/**
 * 
 */
/**
 * @author Administrator
 *
 */
package entity;
public class Building {
    /**
     * 实体类
     * 定义get ,set 属性
     */
    private String Id;
    private String Company;
    private String Phone;
    private String Description;
    private String Status;
    public String getId() {
        return Id;
    }
    public void setId(String id) {
        Id = id;
    }
    public String getCompany() {
        return Company;
    }
    public void setCompany(String company) {
        Company = company;
    }
    public String getPhone() {
        return Phone;
    }
    public void setPhone(String phone) {
        Phone = phone;
    }
    public String getDescription() {
        return Description;
    }
    public void setDescription(String description) {
        Description = description;
    }
    public String getStatus() {
        return Status;
    }
    public void setStatus(String status) {
        Status = status;
    }
    
    
}

service服务

BuildingService.java

/**
 * 
 */
/**
 * @author Administrator
 *
 */
package service;

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

import dao.BuildingDao;
import entity.Building;


public class BuildingService{
    /**
     * 添加
     * @param building
     * @return
     * @throws SQLException
     */
    public int add(Building building) throws SQLException {
        BuildingDao dao=new BuildingDao();
        return dao.add(building);            
    }
    /**
     * 查询
     * @return
     * @throws SQLException
     */
    public  List<Building>  fill() throws SQLException{
        BuildingDao dao=new BuildingDao();    
        return dao.fill();
    }
    public  Building  fill(String  Id) throws SQLException{
        BuildingDao dao=new BuildingDao();    
        return dao.fill(Id);
    }
    /**
     * 修改
     * @param building
     * @return
     * @throws SQLException
     */
    public int update(Building building) throws SQLException{
        BuildingDao dao=new BuildingDao();
        return dao.update(building);        
    }
    /**
     *  删除
     * @param Id
     * @throws SQLException
     */
    public void delete(String Id) throws SQLException{
        BuildingDao dao=new BuildingDao();
         dao.delete(Id);;    
    }
    
    public void delete(String[] Id) throws SQLException {
        BuildingDao dao=new BuildingDao();
        dao.delete(Id);
    }
}

在action包里建servlet

BuildingServlet.java

/**
 * 
 */
/**
 * @author Administrator
 *
 */
package action;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JApplet;
import service.BuildingService;
import entity.Building;


public class BuildingServlet extends javax.servlet.http.HttpServlet implements
        javax.servlet.Servlet {

    static final long serialVersionUID = 1L;

    public BuildingServlet() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        response.setCharacterEncoding("utf-8");
        try {
            start(request, response);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");
        try {
            start(request, response);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private void start(HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        response.setCharacterEncoding("GBK");
        response.setContentType("text/html;charset=utf-8");
        BuildingService service = new BuildingService();
        String action = request.getParameter("action");
        String id = request.getParameter("id");
        /**
         * 添加
         */
        if (action.equals("add")) {
            response.setContentType("text/html;charset=utf-8");
            String Id = request.getParameter("Id");
            String Company = request.getParameter("Company");
            String Phone = request.getParameter("Phone");
            String Description = request.getParameter("Description");
            String Status = request.getParameter("Status");
            Building b = new Building();
            b.setId(Id);
            b.setCompany(Company);
            b.setPhone(Phone);
            b.setDescription(Description);
            b.setStatus(Status);
            BuildingService buildingService = new BuildingService();
            try {
                buildingService.add(b);
                PrintWriter out = response.getWriter();
                out.print("添加成功");
            } catch (SQLException e) {
                PrintWriter out = response.getWriter();
                out.print("添加失败");
                e.printStackTrace();
            }
        }
        /**
         * 查詢
         */
        else if (action.equals("list")) {
                    try {
                            List<Building> buildingList = service.fill();
                            request.setAttribute("buildingList", buildingList);
                            request.getRequestDispatcher("buildingList.jsp").forward(
                                    request, response);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                } else if (action.equals("list2")) {
                    String id1 = request.getParameter("id");
                    try {
                            Building building = service.fill(id1);
                            request.setAttribute("building", building);
                            request.getRequestDispatcher("buildingList.jsp").forward(
                                    request, response);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                }
        /**
         * 修改
         */                
                else if (id != null&&action.equals("update")) {
                            try {
                                    Building building = service.fill(id);
                                    request.setAttribute("building", building);
                                    request.getRequestDispatcher("buildingUpdate.jsp").forward(
                                            request, response);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                        } else if(action.equals("update2")){
                                String Id = request.getParameter("Id");
                                String Company = request.getParameter("Company");
                                String Phone = request.getParameter("Phone");
                                String Description = request.getParameter("Description");
                                String Status = request.getParameter("Status");
                                Building b = new Building();
                                b.setId(Id);
                                b.setCompany(Company);
                                b.setPhone(Phone);
                                b.setDescription(Description);
                                b.setStatus(Status);
                                BuildingService buildingService = new BuildingService();
                                try {
                                        buildingService.update(b);
                                        PrintWriter out = response.getWriter();
                                        out.print("修改成功");
                                        
                                    } catch (Exception e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }                
                        }
        /**
         * 删除
         */
                     if(action.equals("delete")) {
                         try {                            
                            List<Building> buildingDelete = service.fill();
                            request.setAttribute("buildingDelete", buildingDelete);
                            request.getRequestDispatcher("buildingDelete.jsp").forward(
                                    request, response);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                      }
                      else if(action.equals("delete2")) {
                          String[] ids=request.getParameterValues("Id");
                         // String id1=request.getParameter("id");
                          try {
                            //service.delete(id1);
                            service.delete(ids);
                              response.sendRedirect("BuildingServlet?action=delete");
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                      }
                      else if(action.equals("delete3")) {                          
                          String id1=request.getParameter("id");
                          try {                            
                            service.delete(id1);
                              response.sendRedirect("BuildingServlet?action=delete");
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                      }
                    
            }
}
点赞
收藏
评论区
推荐文章
Wesley13 Wesley13
2年前
java加密解密_____MD5加密(用户名映射(用户名和密码)串)唯一性
package com.cnse.module.security.md5Security;import java.io.UnsupportedEncodingException;import java.security.MessageDigest;/  @author Administrator md5加
Easter79 Easter79
2年前
SpringBoot报错:Invalid bound statement (not found)
错误原因:没有发现Mybatis配置文件的路径解决方法:1.检查Mapper包名与xml文件<mapper标签的namespace数据名称是否相同<mappernamespace"com.tuyrk._161_java_socket.project6.dao.FileMapper"</mapper2.Mapper中定义的方法
Stella981 Stella981
2年前
JSP+Servlet+JavaBean实现数据库的增删改查
基本思想:JSP文件显示页面,使用form或href超链接传值到Servlet中方法,在Servlet方法中调用Dao层的类对象,实现对数据库里的数据的增删改查,之后重新返回到JSP输出操作完的结果。共分为四个包和对应的JSP文件:1.DB包:建立连接数据库的方法,以及关闭操作数据库的方法。2.Servlet包:①接受来自JSP页面的参数,将这些
Wesley13 Wesley13
2年前
Java爬虫之JSoup使用教程
title:Java爬虫之JSoup使用教程date:201812248:00:000800update:201812248:00:000800author:mecover:https://imgblog.csdnimg.cn/20181224144920712(https://www.oschin
Stella981 Stella981
2年前
SpringBoot报错:Invalid bound statement (not found)
错误原因:没有发现Mybatis配置文件的路径解决方法:1.检查Mapper包名与xml文件<mapper标签的namespace数据名称是否相同<mappernamespace"com.tuyrk._161_java_socket.project6.dao.FileMapper"</mapper2.Mapper中定义的方法
Wesley13 Wesley13
2年前
DAO设计模式
jsp只关注于数据的显示,而不关心数据是从哪里来,所以jsp中不应该使用任何sql包,数据库操作代码最好使用PreparedStatement。j2ee的组件层次:客户端表示层业务层数据层DAO属于j2ee数据层的操作,操作数据库,DAO封装了数据库中表的全部操作。实例:假设表: createtableperson
Easter79 Easter79
2年前
Spring如何整合Mybatis,源码不难嘛!
Spring整合Mybtais会进行如下的配置(条条大路通罗马,方式不唯一)。privatestaticfinalStringONE_MAPPER_BASE_PACKAGE"com.XXX.dao.mapper.one";@BeanpublicMapperScannerConfigureroneMapperS
Wesley13 Wesley13
2年前
DAO 四个包的建立
一、DAO四个包的建立,降低代码之间的耦合性?  之前写代码,都是在一个包下。代码耦合性较高,不利于后期的维护。  dao(代码分层?)有利于后期的维护代码,修改方便。com.aaa.dao存放dao相关的类型处理数据库的链接存取数据。com.aaa.servlet存放serv
Stella981 Stella981
2年前
BlockingQueue队列生产者消费者示例
package org.web.controller.queue;import java.util.Random;import java.util.concurrent.BlockingQueue;import java.util.concurrent.TimeUnit;import java.uti
LeeFJ LeeFJ
1年前
Foxnic-SQL (8) —— DAO 特性 : 数据查询
FoxnicSQL的DAO对象包含了非常丰富的查询功能,可以查询记录、数据实体(Po对象)、单值。针对不同的数据库DAO对象已经实现了默认的分页功能。DAO中所有的查询方法都支持SQL字符串查询、SQL对象查询。下面我们来具体看一下这些功能。