Javaweb学习

简介: 【10月更文挑战第1天】Javaweb学习

首先需要安装JDK

设置环境变量,JAVA_HOME这个环境变量

然后通过java -version命令来确定是否安装成功。

然后安装tomcat

配置完打开startup.bat然后访问lacalhost:8080来访问,如果能访问到就证明ok。

安装MAVEN

安装,配置环境变量

  • M2_HOME maven目录下的bin目录
  • MAVEN_HOME maven的目录
  • 在系统的path中配置%MAVEN_HOME%\bin

然后使用阿里云镜像

<mirror>
    <id>nexus-aliyun</id>  
    <mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf>  
    <name>Nexus aliyun</name>  
    <url>http://maven.aliyun.com/nexus/content/groups/public</url> 
</mirror>

安装编译器IDEA

将tomcat配置到IDEA中:

第一步运行的地方:

第二步添加一个组件:并选择tomcat server

第三步填配置:

然后选择Deployment添加war包

这样就算是配置成功了。

pom.xml配置文件

使用HelloServlet,

删除src文件,在基础下我们就可以创建多个子项目了

在父项目中要有,为的是能在父项目中找到子项目在父项目中的pom.xml文件中有这个

<modules>
  <module>servlet-01</module>
</modules>

子项目中要有

<parent>
  <artifactId>javaweb-02</artifactId>
  <groupId>com.kuang</groupId>
  <version>1.0-SNAPSHOT</version>
</parent>

可以暂时欺骗所有的人,你甚至可以永远欺骗一部分人,但你不能永远欺骗所有的人

父项目中的java子项目可以直接使用

son extends father
public class HelloServlet extends HttpServlet {
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)

}

表明文件地址,存放地方(适当解释为什么放这个地方)

servletContext

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>cn.study.HelloServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>


  <servlet>
    <servlet-name>getc</servlet-name>
    <servlet-class>cn.study.GetServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>getc</servlet-name>
    <url-pattern>/getc</url-pattern>
  </servlet-mapping>

</web-app>

helloservlet.java

package cn.study;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //this.getInitParameter()   初始化参数
        //this.getServletConfig()   Servlet配置
        //this.getServletContext()  Servlet上下文
        ServletContext context = this.getServletContext();


        String username = "你好"; //数据
//key 为user为 username,值为你好
        context.setAttribute("username",username); //将一个数据保存在了ServletContext中,名字为:username 。值 username

    }

}
package cn.study;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String username = (String) context.getAttribute("username");
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().print("名字"+username);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

获取参数:

    <!--配置一些web应用初始化参数-->
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
    </context-param>
public class Demo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String url = context.getInitParameter("url");
        resp.getWriter().print(url);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

请求转发:

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入了Demo1");
        ServletContext context = this.getServletContext();
        RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");//请求转发路径
        requestDispatcher.forward(req, resp);//调用forwoard方法
    }

请求转发中的路径不变化

重定向的路径是变化的。

相同点:页面都会实现跳转

读取资源

  • 在java目录下新建properties
  • 在resources目录下新建properties

发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath:

只需要一个文件流

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        Properties properties = new Properties();
        properties.load(is);//加载流
        String username = properties.getProperty("username");//获取key
        String password = properties.getProperty("password");//获取key
        resp.getWriter().println(username + ":" + password);

    }

HttpServletResponse

web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest 对象,代表响应的一个HttpServletResponse;

  • 如果要获取客户端请求过来的参数:找HttpServletRequest
  • 如果要给客户端响应一些信息:找HttpServletResponse

都有哪些类别

负责向浏览器发送数据的方法

 servletOutputstream getOutputstream() throws IOException;
 Printwriter getwriter() throws IOException;

负责向浏览器发送响应头的方法

void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long var1);
void setContentType(String var1);
void setDateHeader(String varl,long var2)
void addDateHeader(String var1,long var2)
void setHeader(String var1,String var2);
void addHeader(String var1,String var2);
void setIntHeader(String var1,int var2);
void addIntHeader(String varl,int var2);

响应码常量

响应成功:200
找不到:404
  1. 前面在说的都是想浏览器输出消息
  2. 下载文件
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 要获取下载文件的路径
        String realPath = "E:\\java\\demo\\untitled\\respons\\src\\main\\resources\\img.png";
        System.out.println("下载文件的路径:"+realPath);
        // 2. 下载的文件名是啥?
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        // 3. 设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名URLEncoder.encode编码,否则有可能乱码
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        // 4. 获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);
        // 5. 创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        // 6. 获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
        // 7. 将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端!
        while ((len=in.read(buffer))>0){
            out.write(buffer,0,len);
        }

        in.close();
        out.close();
    }

验证码功能:

web.xml

<servlet>
    <servlet-name>ImageServlet</servlet-name>
    <servlet-class>cn.study.ImageServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ImageServlet</servlet-name>
    <url-pattern>/img</url-pattern>
  </servlet-mapping>

java

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //如何让浏览器3秒自动刷新一次;
        resp.setHeader("refresh","3");

        //在内存中创建一个图片
        BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
        //得到图片
        Graphics2D g = (Graphics2D) image.getGraphics(); //笔
        //设置图片的背景颜色
        g.setColor(Color.white);
        g.fillRect(0,0,80,20);
        //给图片写数据
        g.setColor(Color.BLUE);
        g.setFont(new Font(null,Font.BOLD,20));
        g.drawString(makeNum(),0,20);

        //告诉浏览器,这个请求用图片的方式打开
        resp.setContentType("image/jpeg");
        //网站存在缓存,不让浏览器缓存
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");//缓存策略
        resp.setHeader("Pragma","no-cache");//

        //把图片写给浏览器
        ImageIO.write(image,"jpg", resp.getOutputStream());

    }

    //生成随机数
    private String makeNum(){
        Random random = new Random();
        String num = random.nextInt(9999999) + "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 7-num.length() ; i++) {
            sb.append("0");
        }
        num = sb.toString() + num;
        return num;
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

重定向:

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入这个请求额");
        //处理方求
        String username = req.getParameter( "username");
        String password = req.getParameter( "password");
        System.out.println(username+":"+password);
        resp.sendRedirect("/r/susses.jsp"); ///重定向到这个页面
    }

HttpServletRequest

HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息。

功能:获取前端传递的参数

请求转发:

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doGet(req, resp);
        resp.setCharacterEncoding("UTF-8");// 修改乱码
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username+"********************************");
        System.out.println(password);
        //通过请求转发
        System.out.println(req.getContextPath());
        req.getRequestDispatcher("/susses.jsp").forward(req, resp);//这里只要/susses.js就行就不用加前缀了,这里的/代表web应用

注意项:最常见也是最有可能发生的情况的解决方法:提升web.xml文件中web-app标签所包含的版本等级
创建项目步骤就是:导入web包,然后配置tomcat(也可以设置/)。然后把web中的头换了,还有就是导入包的问题。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">

Cookie,Session

会话cookie

会话就是用户打开一个浏览器,点击了很多链接,访问多个web资源,关闭浏览器,这个过程就称为会话。

保存会话的两种技术:

Session

什么是Session:

  • 服务器会给每一个用户(浏览器)创建一个Seesion对象;
  • 一个Seesion独占一个浏览器,只要浏览器没有关闭,这个Session就存在;
  • 用户登录之后,整个网站它都可以访问!–> 保存用户的信息;保存购物车的信息……

Session与Cookie的区别

Cookie是把用户的数据写给用户的浏览器,浏览器保存 (可以保存多个)
Session把用户的数据写到用户独占Session中,服务器端保存 (保存重要的信息,减少服务器资源的浪费)
Session对象由服务创建;

什么是JSP
Java Server Pages : Java服务器端页面,也和Servlet一样,用于动态Web技术!

最大的特点:

写JSP就像在写HTML
区别:
HTML只给用户提供静态的数据
JSP页面中可以嵌入JAVA代码,为用户提供动态数据;
8.2、JSP原理

思路:JSP到底怎么执行的!

  • 代码层面没有任何问题
  • 服务器内部工作

    Tomcat中有一个work目录;

    IDEA中使用Tomcat的会在IDEA的Tomcat中生产一个work目录

总结重点

Servlet层

Servlet主要功能就是负责对接客户端(web浏览器),包括接收客户端的信息(HttpServletRequest),发送到客户端信息(HttpServletResponse),可以调用业务逻辑层(service层)。

  1. HttpServletRequest
    • 接收HttpServletRequest 接口代表客户端(如浏览器)发送到服务器的请求。它封装了客户端发送的所有请求信息,包括请求参数、头信息、路径信息等。
    • 用途:开发者可以通过这个接口获取请求中的数据,比如查询字符串参数、表单数据、上传的文件、HTTP头信息等。
  2. HttpServletResponse
    • 发送HttpServletResponse 接口代表服务器向客户端发送的响应。它允许开发者设置响应的状态码、响应头信息以及响应体内容。
    • 用途:开发者可以通过这个接口向客户端发送响应数据,比如设置HTTP状态码、添加响应头、发送响应体内容(如HTML页面、JSON数据等)。

Service层(业务逻辑层):

主要就是提供Servlet调用,和调用Dao层,还可以做一些事务层面的操作。

  • 业务逻辑处理:Service层包含应用的核心业务逻辑,如用户认证、数据处理、业务规则的实现等。
  • 数据转换:Service层通常负责将从DAO层获取的数据转换为业务逻辑所需的格式。
  • 事务管理:Service层可以管理事务,确保数据的一致性和完整性。
  • 服务接口定义:Service层定义了业务逻辑的接口,供上层调用,如Servlet层或Spring MVC的Controller层。

DAO层(数据访问对象层):

Dao层主要对接数据库,就是对数据库进行操作。

  • 数据库交互:DAO层负责与数据库进行交互,执行CRUD(创建、读取、更新、删除)操作。
  • 数据访问抽象:DAO层提供了数据访问的抽象,使得上层代码不需要关心具体的数据库实现细节。
  • 数据持久化:DAO层负责将业务对象持久化到数据库中,或者从数据库中检索业务对象。
  • 数据映射:DAO层可以将数据库中的记录映射到Java对象,或者将Java对象映射回数据库记录。

添加用户

画一下底层架构就是如下:

编写UserDao。

//增加用户
    public int add(Connection connection, User user)throws Exception;

编写UserDaoImpl实现类。

 @Override
    public int add(Connection connection, User user) throws Exception {
        PreparedStatement ps = null;
        int updateRows = 0;
        if (connection != null) {
            String sql = "insert into smbms_user (userCode,userName,userPassword,userRole,gender,birthday,phone,address,creationDate,createdBy) values(?,?,?,?,?,?,?,?,?,?)";
            System.out.println("SQLadd="+sql);
            Object[] params = {user.getUserCode(), user.getUserName(), user.getUserPassword(),
            user.getUserRole(), user.getGender(), user.getBirthday(), user.getPhone(),
            user.getAddress(), user.getCreationDate(), user.getCreatedBy()};//从前端接手过来的参数,
            updateRows = BaseDao.execute(connection,sql,params,ps);//执行sql语句
            BaseDao.closeResource(null,null,ps);//关闭资源
        }
        return updateRows;//是否成功
    }

UserService层

//添加用户
    public boolean add(User user) throws SQLException;

    //检查是否用户名已存在 ,这是在添加用户时需要检测的一项
    public User selectUserCodeExist(String userCode);

UserServiceImpl实现类

//检测是否有同名文件
    @Override
    public User selectUserCodeExist(String userCode) {
        Connection connection = null;
        User user = null;
        try {
            connection = BaseDao.getConnection();
            user = userDao.getLoginUser(connection, userCode);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            BaseDao.closeResource(connection, null, null);
        }
        return user;
    }

    //增加用户
    @Override
    public boolean add(User user) {
        Connection conn = null;
        boolean flag = false;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);//开启JDBC事务管理 用于回滚数据
            int updateRows = userDao.add(conn, user);
            conn.commit();
            if (updateRows > 0) {
                flag = true;
                System.out.println("add success");
            } else {
                System.out.println("add failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                System.out.println("rollback===");//失败回滚
                conn.rollback();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } finally {
            BaseDao.closeResource(conn, null, null);
        }
        return flag;
    }

编写Servlet层,首先在doGet函数中加入判断函数,1加入add添加函数,2加入ucexist是否存在同名函数。

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        //先去获取method里面穿的是什么值,再决定执行那个方法
        if (method.equals("add") && method != null) {
            System.out.println("add");
            this.add(req, resp);
        }else if (method.equals( "savepwd")  && method != null) {
            this.updatePwd(req, resp);
        }else if (method.equals("pwdmodify") && method != null) {
            this.pwdModify(req, resp);
        }else if (method.equals("query") && method != null) {
            this.query(req, resp);
        }else if(method != null && method.equals("ucexist")){
            this.userCodeExist(req, resp);
        }
    }

然后写this.add(req, resp);this.userCodeExist(req, resp);函数。

//判断用户账号是否可用
    private void userCodeExist(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //从页面中拿到userCode
        String userCode = request.getParameter("userCode");
        //hashmap用于传递给前端
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(StringUtils.isNullOrEmpty(userCode)){//如果为空
            //userCode == null || userCode.equals("")
            resultMap.put("userCode", "exist"); //返回到前端对应的值
        }else{//如果不为空
            UserService userService = new UserServiceImpl();
            User user = userService.selectUserCodeExist(userCode);//创建业务层进行下一步操作,
            if(null != user){ // 数据库里存在同名的数据,返回到前端
                resultMap.put("userCode","exist");
            }else{//数据库不存在同名数据。
                resultMap.put("userCode", "notexist");
            }
        }

        //把resultMap转为json字符串以json的形式输出
        //配置上下文的输出类型
        response.setContentType("application/json");
        //从response对象中获取往外输出的writer对象
        PrintWriter outPrintWriter = response.getWriter();
        //把resultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();//刷新
        outPrintWriter.close();//关闭流
    }
//添加用户 通过前端接收到数据
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过前端获取信息
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender"); //这个地方从前端过去的都是字符串
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();//创建一个User对象用于存放上面接收到的信息
        user.setUserCode(userCode);//把用户编码放进去
        user.setUserName(userName);//把用户名放进去
        user.setUserPassword(userPassword);//把用户密码放进去
        user.setAddress(address);//把用户地址放进去
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));//放进去出生日期
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        user.setGender(Integer.valueOf(gender));//在这个地方存放就需要强转成原本的类型
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());//先创建一个Date类 就是当前时间,
        user.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId()); //通过session分配id

        System.out.println(user+"==================");
        UserServiceImpl userService = new UserServiceImpl();//创建service,为的是进行service层的操作
        if (userService.add(user)){//如果service返回操作成功,则跳转页面
            resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
        }else {//如果失败则返回到添加页面
            req.getRequestDispatcher("useradd.jsp").forward(req,resp);
        }

    }

这样添加用户就算操作完成了,一定不要忘了检测userCode,因为在js文件中有这个判断的,如果不判断是无法提交的。

用户删除:

首先我们要知道js中这几个属性

1:是表示点击事件是method对应的是deluser,这个不能乱设置要与这里一一对应

2:是表示获取id的名字必须是userid,如果是其他的是获取不到id信息的,

3:是设置键值对是键必须是delResult是其他的无法传到前端。

删除的底层逻辑与添加用户差不多

删除中使用Integer id,与int id都是可以的,只不过servlet层时需要将String类型转化成int类型需要用到Integer.parseInt(userid);所以两个类型都是可以,都表示整数类型,只不过Integer可以为空。

Dao层

//删除用户
    public int deleteUserById(Connection connection, Integer id)throws Exception;
//删除用户
    @Override
    public int deleteUserById(Connection connection, Integer id) throws Exception {
        PreparedStatement ps = null;
        int updateRows = 0;
        if (connection != null) {
            String sql = "delete from smbms_user where id=?";
            Object[] params = {id};
            updateRows = BaseDao.execute(connection,sql,params,ps);
            BaseDao.closeResource(null,null,ps);
        }
        return updateRows;
    }

service层

 //删除用户
    public boolean deleteUserById(Integer id);

service层实现类

//删除用户
    @Override
    public boolean deleteUserById(Integer id) {
        Connection conn = null;
        boolean flag = false;
        try {
            conn = BaseDao.getConnection();
            if (userDao.deleteUserById(conn,id) > 0){
                flag = true;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(conn, null, null);
        }
        return flag;
    }

method选择,这里就是上面说的1处

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        //先去获取method里面穿的是什么值,再决定执行那个方法
        if (method.equals("add") && method != null) {
            System.out.println("add");
            this.add(req, resp);
        }else if (method.equals( "savepwd")  && method != null) {
            this.updatePwd(req, resp);
        }else if (method.equals("pwdmodify") && method != null) {
            this.pwdModify(req, resp);
        }else if (method.equals("query") && method != null) {
            this.query(req, resp);
        }else if(method != null && method.equals("ucexist")){
            this.userCodeExist(req, resp);
        }else if(method != null && method.equals("deluser")) { //这个method主要看js代码中的method值,而不是jsp中的class值
            this.deleteUser(req,resp);
        }
    }

servlet层代码 这里又上面说的2,3处

//删除用户
    public void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userid = req.getParameter("uid");//看js文件中转化成了什么
        Integer id = 0;
        try{
            id = Integer.parseInt(userid);
        }catch (Exception e) {
            id = 0;
        }
        HashMap<String, String> resultMap = new HashMap<String,String>();
        if (id<=0){
            resultMap.put("delResult","notexist"); //第一个键取决于js文件中的键。
        }else {
            UserService userService = new UserServiceImpl();
            if (userService.deleteUserById(id)){//是否操作成功
                resultMap.put("delResult","true");
            }else {
                resultMap.put("delResult","false");
            }
        }

        //把resultMap转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }

用户信息查看

dao层:

//查看用户
    public User getUserById(Connection connection, String id)throws Exception;

dao层实现类

//获取用户全部信息
    @Override
    public User getUserById(Connection connection, String id) throws Exception {
        User user = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        if (connection != null) {
            String sql = "select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.id=? and u.userRole = r.id";
            Object[] params = {id};
            rs = BaseDao.execute(connection,sql,params,ps,rs);
            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUserCode(rs.getString("userCode"));
                user.setUserName(rs.getString("userName"));
                user.setUserPassword(rs.getString("userPassword"));
                user.setGender(rs.getInt("gender"));
                user.setBirthday(rs.getDate("birthday"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                user.setUserRole(rs.getInt("userRole"));
                user.setCreatedBy(rs.getInt("createdBy"));
                user.setCreationDate(rs.getTimestamp("creationDate"));
                user.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getTimestamp("modifyDate"));
                user.setUserRoleName(rs.getString("userRoleName"));
            }
            BaseDao.closeResource(null,rs,ps);
        }
        return user;
    }

service层

//查看用户详细信息
    public User getUserById(String id);

service层实现类

//    显示用户详细信息
    @Override
    public User getUserById(String id) {
        User user = null;//为之后存放用户信息
        Connection conn = null;
        try {
            conn = BaseDao.getConnection();
            user = userDao.getUserById(conn,id);
        }catch (Exception e) {
            e.printStackTrace();
            user = null;
        }finally {
            BaseDao.closeResource(conn, null, null);
        }
        return user;
    }

servlet类

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        //先去获取method里面穿的是什么值,再决定执行那个方法
        if (method.equals("add") && method != null) {
            System.out.println("add");
            this.add(req, resp);
        }else if (method.equals( "savepwd")  && method != null) {
            this.updatePwd(req, resp);
        }else if (method.equals("pwdmodify") && method != null) {
            this.pwdModify(req, resp);
        }else if (method.equals("query") && method != null) {
            this.query(req, resp);
        }else if(method != null && method.equals("ucexist")){
            this.userCodeExist(req, resp);
        }else if(method != null && method.equals("deluser")) { //这个method主要看js代码中的method值,而不是jsp中的class值
            this.deleteUser(req,resp);
        }else if (method != null && method.equals("view")) {//
            this.view(req,resp,"userview.jsp");
        }
    }
//查看用户
    public void view(HttpServletRequest req, HttpServletResponse resp,String url) throws ServletException, IOException {
        String userid = req.getParameter("uid");
        if (!StringUtils.isNullOrEmpty(userid)){//如果存在
            //调用后台方法获取对象
            UserService userService = new UserServiceImpl();
            User user = userService.getUserById(userid);
            req.setAttribute("user",user);//把用户所有信息返回到前端
            //重定向到url页面
            req.getRequestDispatcher(url).forward(req,resp);
        }
    }

用户信息修改

 //修改用户
    public int modeify(Connection connection, User user)throws Exception;
@Override
    public int modeify(Connection connection, User user) throws Exception {
        PreparedStatement ps = null;
        int flag = 0;
        if (connection != null) {
            String sql = "update smbms_user set userName=?,gender=?,birthday=?,phone=?,address=?,userRole=?,modifyBy=?,modifyDate=? where id = ? ";
            Object[] params = {user.getUserName(), user.getGender(), user.getBirthday(),user.getPhone(),user.getAddress(),
                    user.getUserRole(),user.getModifyBy(),user.getModifyDate(),user.getId()};//按照上面sql语句中的?来填写一一对应。
            flag = BaseDao.execute(connection,sql,params,ps);
            BaseDao.closeResource(null,null,ps);
        }
        return flag;
    }
//修改用户信息
    public int updateUserInfo(User user);
//修改用户
    @Override
    public int updateUserInfo(User user) {
        int flag = 0;
        Connection conn = null;
        try{
            conn = BaseDao.getConnection();
            flag = userDao.modeify(conn,user);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(conn, null, null);
        }
        return flag;
    }

供应商

供应商查询

将映射写进web.xml

<servlet>
        <servlet-name>ProviderServlet</servlet-name>
        <servlet-class>cn.edu.qdu.servlet.provider.ProviderServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ProviderServlet</servlet-name>
        <url-pattern>/jsp/provider.do</url-pattern>
    </servlet-mapping>

然后写

//通过供应商名称,编码获取供应商列表
    public List<Provider> getProviderList(Connection conn,String proName,String proCode) throws Exception;
@Override
    public List<Provider> getProviderList(Connection conn, String proName, String proCode) throws Exception {
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Provider> providerList = new ArrayList<Provider>();
        if (conn != null) {
            StringBuffer sql = new StringBuffer();
            sql.append("select * from smbms_provider where 1=1 ");//全部取出
            List<Object> objectList = new ArrayList<Object>();
            if (!StringUtils.isNullOrEmpty(proName)) {//模糊名字
                sql.append(" and proName like ?");
                objectList.add("%" + proName + "%");
            }
            if (!StringUtils.isNullOrEmpty(proCode)) {//模糊code
                sql.append(" and proCode like ?");
                objectList.add("%" + proCode + "%");
            }
            Object[] params = objectList.toArray(); //将存放的数据放进params里面
            System.out.println("SDL->"+sql.toString());
            rs = BaseDao.execute(conn,sql.toString(),params,ps,rs);
            while (rs.next()){
                Provider provider = new Provider();
                provider.setId(rs.getInt("id"));
                provider.setProCode(rs.getString("proCode"));
                provider.setProName(rs.getString("proName"));
                provider.setProDesc(rs.getString("proDesc"));
                provider.setProContact(rs.getString("proContact"));
                provider.setProPhone(rs.getString("proPhone"));
                provider.setProAddress(rs.getString("proAddress"));
                provider.setProFax(rs.getString("proFax"));
                provider.setCreationDate(rs.getTimestamp("creationDate"));
                providerList.add(provider);//放进去
            }
            BaseDao.closeResource(null,rs,ps);
        }
        return providerList;
    }
//通过供应商名称,编码获取供应商列表。
    public List<Provider> getProviders(String proName, String proCode);
private ProviderDao providerDao;
    public ProviderServiceImpl() {
        providerDao = new ProviderDaoImpl();
    }

    //通过名字和编码查询全部
    @Override
    public List<Provider> getProviders(String proName, String proCode) {
        Connection conn = null;
        List<Provider> providers = new ArrayList<Provider>();
        try {
            conn = BaseDao.getConnection();
            providers = providerDao.getProviderList(conn, proName, proCode);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(conn, null, null);
        }
        return providers;
    }
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("query")) {
            this.query(req,resp);
        }
    }

    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String queryProName = req.getParameter("queryProName");
        String queryProCode = req.getParameter("queryProCode");
        if(StringUtils.isNullOrEmpty(queryProCode)){
            queryProCode = "";
        }
        if (StringUtils.isNullOrEmpty(queryProName)){
            queryProName = "";
        }

        List<Provider> providerList = new ArrayList<Provider>();
        ProviderService providerService = new ProviderServiceImpl();
        providerList = providerService.getProviders(queryProName,queryProCode);
        req.setAttribute("providerList", providerList);
        req.setAttribute("queryProName", queryProName);
        req.setAttribute("queryProCode", queryProCode);
        req.getRequestDispatcher("providerlist.jsp").forward(req, resp);

    }

增删改查,只有查的Dao层需要返回对象类型,以为要传递给service层信息,进而传递给Servlet层,然后显示到前端,而其他,,则不需要显示到前端

而对于参数来说,是只需要获取id,然后通过id对其进行操作即可,不需要传入对象类型的全部信息,而,就必须要对象类型的全部信息,增加一条信息肯定是全部,修改信息也需要将所有信息拿过来。

供应商增删改查

//添加供应商
    public int add(Connection conn,Provider provider) throws Exception;
    //删除供应商
    public int delete(Connection conn,String id) throws Exception;
    //查看供应商详情
    public Provider view(Connection conn, String id) throws Exception;
    //修改供应商详情
    public int modify(Connection conn,Provider provider) throws Exception;
//添加供应商
    @Override
    public int add(Connection conn, Provider provider) throws Exception {
        PreparedStatement ps = null;
        int result = 0;
        if (conn != null) {
            String sql = "insert into smbms_provider (proCode,proName,proContact," +
                    "proPhone,proAddress,proFax,proDesc,createdBy,creationDate) values(?,?,?,?,?,?,?,?,?)";
            Object[] params = {provider.getProCode(), provider.getProName(), provider.getProContact(),
            provider.getProPhone(), provider.getProAddress(), provider.getProFax(),
            provider.getProDesc(), provider.getCreatedBy(), provider.getCreationDate()};
            result = BaseDao.execute(conn,sql,params,ps);
            BaseDao.closeResource(null,null,ps);
        }
        return result;
    }
    //删除供应商
    @Override
    public int delete(Connection conn, String id) throws Exception {
        int flag = 0;
        PreparedStatement ps = null;
        if (conn != null) {
            String sql = "delete from smbms_provider where id=?";
            Object[] params = {id};
            flag = BaseDao.execute(conn,sql,params,ps);
            BaseDao.closeResource(null,null,ps);
        }
        return flag;
    }
    //查看供应商
    @Override
    public Provider view(Connection conn, String id) throws Exception {
        PreparedStatement ps = null;
        ResultSet rs = null;
        Provider provider = null;
        if (conn != null) {
            String sql = "select * from smbms_provider where id=?";
            Object[] params = {id};
            rs = BaseDao.execute(conn,sql,params,ps,rs);
            if (rs.next()){
                provider = new Provider();
                provider.setId(rs.getInt("id"));
                provider.setProCode(rs.getString("proCode"));
                provider.setProName(rs.getString("proName"));
                provider.setProDesc(rs.getString("proDesc"));
                provider.setProContact(rs.getString("proContact"));
                provider.setProPhone(rs.getString("proPhone"));
                provider.setProAddress(rs.getString("proAddress"));
                provider.setProFax(rs.getString("proFax"));
                provider.setCreatedBy(rs.getInt("createdBy"));
                provider.setCreationDate(rs.getTimestamp("creationDate"));
                provider.setModifyBy(rs.getInt("modifyBy"));
                provider.setModifyDate(rs.getTimestamp("modifyDate"));
            }
            BaseDao.closeResource(null,rs,ps);
        }
        return provider;
    }
    //修改供应商
    @Override
    public int modify(Connection conn, Provider provider) throws Exception {
            PreparedStatement ps = null;
            int result = 0;
        if (conn != null) {
            String sql = "update smbms_provider set proName=?,proDesc=?,proContact=?," +
                    "proPhone=?,proAddress=?,proFax=?,modifyBy=?,modifyDate=? where id = ? ";
            Object[] params = {provider.getProName(),provider.getProDesc(),provider.getProContact(),provider.getProPhone(),provider.getProAddress(),
                    provider.getProFax(),provider.getModifyBy(),provider.getModifyDate(),provider.getId()};
            result = BaseDao.execute(conn,sql,params,ps);
            BaseDao.closeResource(null,null,ps);
        }
        return result;
    }
// 添加供应商
    public boolean add(Provider provider);
    // 删除供应商
    public int delete(String id);
    //查看供应商
    public Provider viewProvider(String id);
    //修改供应商
    public boolean modify(Provider provider);
//添加供应商
    @Override
    public boolean add(Provider provider) {
        Connection conn = null;
        boolean result = false;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);
            if (providerDao.add(conn, provider) > 0) {
                result = true;
            }
            conn.commit();
        }catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();//回滚
            }catch (Exception e1) {
                e1.printStackTrace();
            }
        }finally {
            BaseDao.closeResource(conn, null, null);
        }
        return result;
    }
    //删除供应商
    @Override
    public int delete(String id) {
        Connection conn = null;
        int result = -1;
        try{
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);
            result = billDao.getBillCount(conn, id);
            if (result==0) {
                providerDao.delete(conn, id);
            }
            conn.commit();
        }catch (Exception e) {
            e.printStackTrace();
            result = -1;
            try {
                conn.rollback();
            }catch (Exception e1) {
                e1.printStackTrace();
            }
        }finally {
            BaseDao.closeResource(conn, null, null);
        }
        return result;
    }
    //查看供应商
    @Override
    public Provider viewProvider(String id) {
        Connection conn = null;
        Provider provider = null;
        try {
            conn = BaseDao.getConnection();
            provider = providerDao.view(conn, id);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(conn, null, null);
        }
        return provider;
    }
    //修改供应商
    @Override
    public boolean modify(Provider provider) {
        Connection conn = null;
        boolean result = false;
        try {
            conn = BaseDao.getConnection();
            if (providerDao.modify(conn, provider) > 0) {
                result = true;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(conn, null, null);
        }
        return result;
    }
package cn.edu.qdu.servlet.provider;

import cn.edu.qdu.pojo.Provider;
import cn.edu.qdu.pojo.User;
import cn.edu.qdu.service.provider.ProviderService;
import cn.edu.qdu.service.provider.ProviderServiceImpl;
import cn.edu.qdu.util.Constants;
import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class ProviderServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method !=null&&method.equals("query")) {
            this.query(req,resp);
        } else if (method !=null&&method.equals("add")) {
            this.add(req,resp);
        }else if (method !=null&&method.equals("delprovider")) {//删除
            this.delete(req,resp);
        }else if (method !=null&&method.equals("view")) { //查看
            this.view(req,resp,"providerview.jsp");
        }else if (method !=null&&method.equals("modify")) {//修改
            this.view(req,resp,"providermodify.jsp");
        }else if (method !=null&&method.equals("modifysave")) {//修改提交
            this.modify(req,resp);
        }
    }
    //删除
    public void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("proid");
        int id1 = Integer.parseInt(id);
        HashMap<String,String> resultMap = new HashMap<String,String>();
//        if (id1<=0){
//            resultMap.put("delResult","notexist");
//        }else {
//            ProviderService providerService = new ProviderServiceImpl();
//            if (providerService.delete(id)){
//                resultMap.put("delResult","true");
//            }else {
//                resultMap.put("delResult","false");
//            }
//        }
        if(!StringUtils.isNullOrEmpty(id)){
            ProviderService providerService = new ProviderServiceImpl();
            int flag = providerService.delete(id);
            if(flag == 0){//删除成功
                resultMap.put("delResult", "true");
            }else if(flag == -1){//删除失败
                resultMap.put("delResult", "false");
            }else if(flag > 0){//该供应商下有订单,不能删除,返回订单数
                resultMap.put("delResult", String.valueOf(flag));
            }
        }else{
            resultMap.put("delResult", "notexit");
        }
        //转换类型
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }
    //查看
    public void view(HttpServletRequest req, HttpServletResponse resp, String path) throws ServletException, IOException {
        String id = req.getParameter("proid");
        if (!StringUtils.isNullOrEmpty(id)){
            ProviderService providerService = new ProviderServiceImpl();
            Provider provider = providerService.viewProvider(id);
            req.setAttribute("provider",provider);
            //重定向到url页面
            req.getRequestDispatcher(path).forward(req, resp);
        }
    }
    //修改
    public void modify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String proContact = request.getParameter("proContact");
        String proPhone = request.getParameter("proPhone");
        String proAddress = request.getParameter("proAddress");
        String proFax = request.getParameter("proFax");
        String proDesc = request.getParameter("proDesc");
        String id = request.getParameter("proid");
        System.out.println("id:"+id);
        Provider provider = new Provider();
        provider.setId(Integer.valueOf(id));
        provider.setProContact(proContact);
        provider.setProPhone(proPhone);
        provider.setProFax(proFax);
        provider.setProAddress(proAddress);
        provider.setProDesc(proDesc);
        provider.setModifyBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
        provider.setModifyDate(new Date());
        boolean flag = false;
        ProviderService providerService = new ProviderServiceImpl();
        flag = providerService.modify(provider);
        if(flag){
            response.sendRedirect(request.getContextPath()+"/jsp/provider.do?method=query");
        }else{
            request.getRequestDispatcher("providermodify.jsp").forward(request, response);
        }

    }
    //添加
    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //收起前端得到的数据
        String proCode = req.getParameter("proCode");
        String proName = req.getParameter("proName");
        String proContact = req.getParameter("proContact");
        String proPhone = req.getParameter("proPhone");
        String proAddress = req.getParameter("proAddress");
        String proFax = req.getParameter("proFax");
        String proDesc = req.getParameter("proDesc");

        Provider pro = new Provider();//用于存放
        pro.setProCode(proCode);
        pro.setProName(proName);
        pro.setProContact(proContact);
        pro.setProPhone(proPhone);
        pro.setProAddress(proAddress);
        pro.setProFax(proFax);
        pro.setProDesc(proDesc);
        pro.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        pro.setCreationDate(new Date());
        //然后交给service操作
        ProviderService providerService = new ProviderServiceImpl();
        if (providerService.add(pro)){
            resp.sendRedirect(req.getContextPath()+"/jsp/provider.do?method=query");
        }else {
            req.getRequestDispatcher("provideradd.jsp").forward(req, resp);
        }

    }

    //查询全部
    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String queryProName = req.getParameter("queryProName");
        String queryProCode = req.getParameter("queryProCode");
        if(StringUtils.isNullOrEmpty(queryProCode)){
            queryProCode = "";
        }
        if (StringUtils.isNullOrEmpty(queryProName)){
            queryProName = "";
        }

        List<Provider> providerList = new ArrayList<Provider>();
        ProviderService providerService = new ProviderServiceImpl();
        providerList = providerService.getProviders(queryProName,queryProCode);
        req.setAttribute("providerList", providerList);
        req.setAttribute("queryProName", queryProName);
        req.setAttribute("queryProCode", queryProCode);
        req.getRequestDispatcher("providerlist.jsp").forward(req, resp);

    }
}

在修改里注意,供应商修改页面写的不全:

providermodify.jsp文件中的form表单中添加

<input type="hidden" name="method" value="modifysave">
              <input type="hidden" name="proid" value="${provider.id }"/>

订单管理:

public interface BillDao {

    //查询获取当单列表
    public List<Bill> getBillList(Connection conn,Bill bill)throws Exception;
    //添加
    public int addBill(Connection conn,Bill bill)throws Exception;
    //删除
    public int deleteBill(Connection conn,String id)throws Exception;
    //查看
    public Bill getBill(Connection conn,String id)throws Exception;
    //修改
    public int updateBill(Connection conn,Bill bill)throws Exception;
    //通过供应商id查询订单数量
    public int getBillCount(Connection conn,String providerId)throws Exception;
}
public class BillDaoImpl implements BillDao {
    //查询
    @Override
    public List<Bill> getBillList(Connection conn, Bill bill) throws Exception {
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Bill> billList = new ArrayList<Bill>();//存放结果
        if(conn!=null){
            StringBuffer sql = new StringBuffer();//为了字符拼接
            sql.append("select b.*,p.proName as providerName from smbms_bill b," +
                    "smbms_provider p where b.providerId = p.id");
            List<Object> list = new ArrayList<Object>();
            System.out.println("Name:"+bill.getProductName());
            if (!StringUtils.isNullOrEmpty(bill.getProductName())) {//如果传过来的查询项有名字
//              启用模糊查询
                sql.append(" and productName like ?");
                list.add("%" + bill.getProductName() + "%");//模糊查询需要加上%
            }
            if (bill.getProviderId()>0) {//通过id有查询
                sql.append(" and providerId = ?");
                list.add(bill.getProviderId());
            }
            if(bill.getIsPayment()>0){
                sql.append(" and isPayment = ?");
                list.add(bill.getIsPayment());
            }
            Object[] params = list.toArray();//转换成Object类型
            System.out.println("sql->"+sql.toString());
            rs = BaseDao.execute(conn,sql.toString(),params,ps,rs);
            while(rs.next()){
                Bill bill1 = new Bill();
                bill1.setId(rs.getInt("id"));
                bill1.setProviderId(rs.getInt("providerId"));
                bill1.setBillCode(rs.getString("billCode"));
                bill1.setProviderName(rs.getString("providerName"));
                bill1.setProductName(rs.getString("productName"));
                bill1.setProductDesc(rs.getString("productDesc"));
                bill1.setProductUnit(rs.getString("productUnit"));
                bill1.setProductCount(rs.getBigDecimal("productCount"));
                bill1.setIsPayment(rs.getInt("isPayment"));
                bill1.setTotalPrice(rs.getBigDecimal("totalPrice"));
                bill1.setCreationDate(rs.getDate("creationDate"));
                bill1.setCreatedBy(rs.getInt("createdBy"));
                billList.add(bill1);
            }
            BaseDao.closeResource(conn,rs,ps);
        }
        return billList;
    }
    //添加
    @Override
    public int addBill(Connection conn, Bill bill) throws Exception {
        PreparedStatement ps = null;
        int result = 0;
        if(conn!=null){
            String sql = "insert into smbms_bill (billCode,productName,productDesc," +
                    "productUnit,productCount,totalPrice,isPayment,providerId,createdBy,creationDate)" +
                    "values(?,?,?,?,?,?,?,?,?,?)";
            Object[] params = {bill.getBillCode(),bill.getProductName(),bill.getProductDesc(),
                    bill.getProductUnit(),bill.getProductCount(),bill.getTotalPrice(),bill.getIsPayment(),
                    bill.getProviderId(),bill.getCreatedBy(),bill.getCreationDate()};
            result = BaseDao.execute(conn,sql,params,ps);
            BaseDao.closeResource(null,null,ps);
        }
        return result;
    }
//删除
    @Override
    public int deleteBill(Connection conn, String id) throws Exception {
        PreparedStatement ps = null;
        int result = 0;
        if(conn!=null){
            String sql = "delete from smbms_bill where id = ?";
            Object[] params = {id};
            result = BaseDao.execute(conn,sql,params,ps);
            BaseDao.closeResource(null,null,ps);
        }
        return result;
    }
//查看详情
    @Override
    public Bill getBill(Connection conn, String id) throws Exception {
        Bill bill = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        if(conn!=null){
            String sql = "select b.*,p.proName as providerName from smbms_bill b, smbms_provider p " +
                    "where b.providerId = p.id and b.id=?";
            Object[] params = {id};
            rs = BaseDao.execute(conn,sql,params,ps,rs);
            if(rs.next()){
                bill = new Bill();
                bill.setId(rs.getInt("id"));
                bill.setBillCode(rs.getString("billCode"));
                bill.setProductName(rs.getString("productName"));
                bill.setProductDesc(rs.getString("productDesc"));
                bill.setProductUnit(rs.getString("productUnit"));
                bill.setProductCount(rs.getBigDecimal("productCount"));
                bill.setTotalPrice(rs.getBigDecimal("totalPrice"));
                bill.setIsPayment(rs.getInt("isPayment"));
                bill.setProviderId(rs.getInt("providerId"));
                bill.setProviderName(rs.getString("providerName"));
                bill.setModifyBy(rs.getInt("modifyBy"));
                bill.setModifyDate(rs.getTimestamp("modifyDate"));
            }
            BaseDao.closeResource(null,null,ps);
        }
        return bill;
    }
//修改
    @Override
    public int updateBill(Connection conn, Bill bill) throws Exception {
        int result = 0;
        PreparedStatement ps = null;
        if(conn!=null){
            String sql = "update smbms_bill set productName=?," +
                    "productDesc=?,productUnit=?,productCount=?,totalPrice=?," +
                    "isPayment=?,providerId=?,modifyBy=?,modifyDate=? where id = ? ";
            Object[] params = {bill.getProductName(),bill.getProductDesc(),
                    bill.getProductUnit(),bill.getProductCount(),bill.getTotalPrice(),bill.getIsPayment(),
                    bill.getProviderId(),bill.getModifyBy(),bill.getModifyDate(),bill.getId()};
            result = BaseDao.execute(conn,sql,params,ps);
            BaseDao.closeResource(null,null,ps);
        }
        return result;
    }

    @Override
    public int getBillCount(Connection conn, String providerId) throws Exception {
        int count = 0;
        PreparedStatement ps = null;
        ResultSet rs = null;
        if(conn!=null){
            String sql = "select count(1) from smbms_bill where providerId = ?";
            Object[] params = {providerId};
            rs = BaseDao.execute(conn,sql,params,ps,rs);
            if(rs.next()){
                count = rs.getInt("billCount");
            }
            BaseDao.closeResource(null,null,ps);
        }
        return count;
    }
}

public interface BillService {
    //查看
    public List<Bill> getBillList(Bill bill);

    //添加
    public boolean addBill(Bill bill);
    //删除
    public boolean deleteBill(String id);
    //详情
    public Bill getBill(String id);
    //修改
    public boolean updateBill(Bill bill);
}

public class BillServiceImpl implements BillService {
    private BillDao billDao;
    public BillServiceImpl(){
        billDao = new BillDaoImpl();
    }
    // 查看
    @Override
    public List<Bill> getBillList(Bill bill) {
        Connection conn = null;
        List<Bill> billList = null;
        try {
            conn = BaseDao.getConnection();
            billList = billDao.getBillList(conn, bill);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(conn, null, null);
        }
        return billList;
    }

    @Override
    public boolean addBill(Bill bill) {
        boolean flag = false;
        Connection conn = null;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);//开启事务
            if (billDao.addBill(conn,bill)>0){
                flag = true;
            }
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                conn.rollback();//回滚
            }catch (Exception e1){
                e1.printStackTrace();
            }
        }finally {
            BaseDao.closeResource(conn, null, null);
        }
        return flag;
    }

    @Override
    public boolean deleteBill(String id) {
        Connection conn = null;
        boolean flag = false;
        try {
            conn = BaseDao.getConnection();
            if (billDao.deleteBill(conn,id)>0){
                flag = true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(conn, null, null);
        }
        return flag;
    }

    @Override
    public Bill getBill(String id) {
        Connection conn = null;
        Bill bill = null;
        try {
            conn = BaseDao.getConnection();
            bill = billDao.getBill(conn,id);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(conn, null, null);
        }
        return bill;
    }

    @Override
    public boolean updateBill(Bill bill) {
        boolean flag = false;
        Connection conn = null;
        try {
            conn = BaseDao.getConnection();
            if (billDao.updateBill(conn,bill)>0){
                flag = true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(conn, null, null);
        }
        return flag;
    }
}
public class BillServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("query")) {
            this.query(req,resp);
        }else if (method.equals("add")) {
            this.add(req,resp);
        }else if (method.equals("view")) {
            this.getBill(req,resp,"billview.jsp");
        }else if (method.equals("modify")) {
            this.getBill(req,resp,"billmodify.jsp");
        }else if (method.equals("delbill")) {
            this.delete(req,resp);
        }else if (method.equals("modifysave")) {
            this.modify(req,resp);
        }else if (method.equals("getproviderlist")) {
            this.getProviderlist(req,resp);
        }
    }
    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String billCode = req.getParameter("billCode");
        String productName = req.getParameter("productName");
        String productDesc = req.getParameter("productDesc");
        String productUnit = req.getParameter("productUnit");

        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String providerId = req.getParameter("providerId");
        String isPayment = req.getParameter("isPayment");

        Bill bill = new Bill();
        bill.setBillCode(billCode);
        bill.setProductName(productName);
        bill.setProductDesc(productDesc);
        bill.setProductUnit(productUnit);
        bill.setProductCount(new BigDecimal(productCount).setScale(2,BigDecimal.ROUND_DOWN));
        bill.setIsPayment(Integer.parseInt(isPayment));
        bill.setTotalPrice(new BigDecimal(totalPrice).setScale(2,BigDecimal.ROUND_DOWN));
        bill.setProviderId(Integer.parseInt(providerId));
        bill.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        bill.setCreationDate(new Date());

        boolean flag = false;
        BillService billService = new BillServiceImpl();
        flag = billService.addBill(bill);
        if (flag) {
            resp.sendRedirect(req.getContextPath() + "/jsp/bill.do?method=query");
        }else {
            req.getRequestDispatcher("billadd.jsp").forward(req, resp);
        }
    }
    private void getBill(HttpServletRequest req, HttpServletResponse resp,String url) throws ServletException, IOException {
        String billid = req.getParameter("billid");
        if (!StringUtils.isNullOrEmpty(billid)) {
            BillService billService = new BillServiceImpl();
            Bill bill = billService.getBill(billid);
            req.setAttribute("bill", bill);
            req.getRequestDispatcher(url).forward(req, resp);
        }
    }
    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String billid = req.getParameter("billid");
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (!StringUtils.isNullOrEmpty(billid)) {
            BillService billService = new BillServiceImpl();
            boolean flag = billService.deleteBill(billid);
            if (flag) {
                resultMap.put("delResult","true");
            }else {
                resultMap.put("delResult","false");
            }
        }else {
            resultMap.put("delResult", "notexit");
        }
        //转换形式
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }
    private void modify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String productName = req.getParameter("productName");
        String productDesc = req.getParameter("productDesc");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String providerId = req.getParameter("providerId");
        String isPayment = req.getParameter("isPayment");

        Bill bill = new Bill();
        bill.setId(Integer.valueOf(id));
        bill.setProductName(productName);
        bill.setProductDesc(productDesc);
        bill.setProductUnit(productUnit);
        bill.setProductCount(new BigDecimal(productCount).setScale(2,BigDecimal.ROUND_DOWN));
        bill.setIsPayment(Integer.parseInt(isPayment));
        bill.setTotalPrice(new BigDecimal(totalPrice).setScale(2,BigDecimal.ROUND_DOWN));
        bill.setProviderId(Integer.parseInt(providerId));

        bill.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        bill.setModifyDate(new Date());
        boolean flag = false;
        BillService billService = new BillServiceImpl();
        flag = billService.updateBill(bill);
        if (flag) {
            resp.sendRedirect(req.getContextPath()+"/jsp/bill.do?method=query");
        }else{
            req.getRequestDispatcher("billmodify.jsp").forward(req, resp);
        }

    }
    private void getProviderlist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Provider> providers = new ArrayList<Provider>();
        ProviderService providerService = new ProviderServiceImpl();
        providers = providerService.getProviders("","");

        //把providerList转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(providers));
        outPrintWriter.flush();
        outPrintWriter.close();
    }
    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取信息
        List<Provider> providerList = new ArrayList<Provider>();
        ProviderService providerService = new ProviderServiceImpl();
        providerList = providerService.getProviders("","");//获得供应商全部信息
        req.setAttribute("providerList", providerList);

        String queryProductName = req.getParameter("queryProductName");
        String queryProviderId = req.getParameter("queryProviderId");
        String queryIsPayment = req.getParameter("queryIsPayment");
        if (StringUtils.isNullOrEmpty(queryProductName)) {
            queryProductName = "";
        }

        List<Bill> billList = new ArrayList<Bill>();
        BillService billService = new BillServiceImpl();
        Bill bill = new Bill();
        if (StringUtils.isNullOrEmpty(queryProviderId)) {
            bill.setProviderId(0);
        }else {
            bill.setProviderId(Integer.parseInt(queryProviderId));
        }
        if (StringUtils.isNullOrEmpty(queryIsPayment)) {
            bill.setIsPayment(0);
        }else {
            bill.setIsPayment(Integer.parseInt(queryIsPayment));
        }
        bill.setProductName(queryProductName);
        System.out.println("Name:====="+bill.getProviderName());
        billList = billService.getBillList(bill);
        req.setAttribute("billList", billList);
        req.setAttribute("queryProductName", queryProductName);
        req.setAttribute("queryProviderId", queryProviderId);
        req.setAttribute("queryIsPayment", queryIsPayment);
        req.getRequestDispatcher("billlist.jsp").forward(req, resp);
    }
}
目录
相关文章
|
2月前
|
XML Java 编译器
Java学习十六—掌握注解:让编程更简单
Java 注解(Annotation)是一种特殊的语法结构,可以在代码中嵌入元数据。它们不直接影响代码的运行,但可以通过工具和框架提供额外的信息,帮助在编译、部署或运行时进行处理。
91 43
Java学习十六—掌握注解:让编程更简单
|
22天前
|
Java 大数据 API
14天Java基础学习——第1天:Java入门和环境搭建
本文介绍了Java的基础知识,包括Java的简介、历史和应用领域。详细讲解了如何安装JDK并配置环境变量,以及如何使用IntelliJ IDEA创建和运行Java项目。通过示例代码“HelloWorld.java”,展示了从编写到运行的全过程。适合初学者快速入门Java编程。
|
2月前
|
存储 SQL 小程序
JVM知识体系学习五:Java Runtime Data Area and JVM Instruction (java运行时数据区域和java指令(大约200多条,这里就将一些简单的指令和学习))
这篇文章详细介绍了Java虚拟机(JVM)的运行时数据区域和JVM指令集,包括程序计数器、虚拟机栈、本地方法栈、直接内存、方法区和堆,以及栈帧的组成部分和执行流程。
36 2
JVM知识体系学习五:Java Runtime Data Area and JVM Instruction (java运行时数据区域和java指令(大约200多条,这里就将一些简单的指令和学习))
|
1月前
|
JavaScript Java 项目管理
Java毕设学习 基于SpringBoot + Vue 的医院管理系统 持续给大家寻找Java毕设学习项目(附源码)
基于SpringBoot + Vue的医院管理系统,涵盖医院、患者、挂号、药物、检查、病床、排班管理和数据分析等功能。开发工具为IDEA和HBuilder X,环境需配置jdk8、Node.js14、MySQL8。文末提供源码下载链接。
|
2月前
|
小程序 Oracle Java
JVM知识体系学习一:JVM了解基础、java编译后class文件的类结构详解,class分析工具 javap 和 jclasslib 的使用
这篇文章是关于JVM基础知识的介绍,包括JVM的跨平台和跨语言特性、Class文件格式的详细解析,以及如何使用javap和jclasslib工具来分析Class文件。
49 0
JVM知识体系学习一:JVM了解基础、java编译后class文件的类结构详解,class分析工具 javap 和 jclasslib 的使用
|
2月前
|
存储 缓存 Java
【用Java学习数据结构系列】HashMap与TreeMap的区别,以及Map与Set的关系
【用Java学习数据结构系列】HashMap与TreeMap的区别,以及Map与Set的关系
39 1
|
2月前
|
存储 搜索推荐 算法
【用Java学习数据结构系列】七大排序要悄咪咪的学(直接插入,希尔,归并,选择,堆排,冒泡,快排)以及计数排序(非比较排序)
【用Java学习数据结构系列】七大排序要悄咪咪的学(直接插入,希尔,归并,选择,堆排,冒泡,快排)以及计数排序(非比较排序)
26 1
|
2月前
|
存储 算法 Java
带你学习java的数组军队列
带你学习java的数组军队列
35 0
|
2月前
|
Java 大数据 开发工具
java学习——环境准备(1)
java学习——环境准备(1)
42 0
|
7月前
|
存储 Java
【JAVA学习之路 | 进阶篇】Map接口及其实现类及常用方法
【JAVA学习之路 | 进阶篇】Map接口及其实现类及常用方法