主要是做数据持久层的工作,负责与数据库进行联络的一些任务都封装在此,DAO层的设计首先是设计DAO的接口,然后就可在模块中调用此接口来进行数据业务的处理,而不用关心此接口的具体实现类是哪个类,显得结构非常清晰,DAO层的数据源配置。
业务逻辑层,完成功能的设计 和Dao层一样都是先设计接口,再创建要实现的类,然后在配置文件中进行配置其实现的关联。接下来就可以在service层调用Dao层的接口进行业务逻辑应用的处理。service的impl是把mapper和service进行整合的文件 封装Service层的业务逻辑有利于业务逻辑的独立性和重复利用性,程序显得非常简洁。
service层经常要调用Dao层的方法对数据进行增删改查的操作,现实开发中,对业务的操作会涉及到数据的操作,而对数据操作常常要用到数据库,所以service层会经常调用Dao层的方法。
称之为过滤器,它是Servlet技术中最实用的技术,Web开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或静态 html 文件等进行拦截,从而实现一些特殊的功能。
即Plain Ordinary Java Object(普通的java对象),也有人称其为model、domain、bean等,pojo层是对应的数据库表的实体类。它不包含业务逻辑或持久逻辑等,但不是JavaBean、EntityBean等,不具有任何特殊角色和不继承或不实现任何其它Java框架的类或接口。
POJO 和JavaBean是我们常见的两个关键字,一般容易混淆,POJO全称是Plain Ordinary Java Object / Pure Ordinary Java Object,中文可以翻译成:普通Java类,具有一部分getter/setter方法的那种类就可以称作POJO,但是JavaBean则比 POJO复杂很多, Java Bean 是可复用的组件,对 Java Bean 并没有严格的规范,理论上讲,任何一个 Java 类都可以是一个 Bean 。但通常情况下,由于 Java Bean 是被容器所创建(如 Tomcat) 的,所以 Java Bean 应具有一个无参的构造器,另外,通常 Java Bean 还要实现 Serializable 接口用于实现 Bean 的持久性。 Java Bean 是不能被跨进程访问的。JavaBean是一种组件技术,就好像你做了一个扳子,而这个扳子会在很多地方被拿去用,这个扳子也提供多种功能(你可以拿这个扳子扳、锤、撬等等),而这个扳子就是一个组件。一般在web应用程序中建立一个数据库的映射对象时,我们只能称它为POJO。POJO(Plain Old Java Object)这个名字用来强调它是一个普通java对象,而不是一个特殊的对象,其主要用来指代那些没有遵从特定的Java对象模型、约定或框架(如EJB)的Java对象。理想地讲,一个POJO是一个不受任何限制的Java对象(除了Java语言规范)。
Util是utiliy的缩写,是一个多功能、基于工具的包。
java.util是包含集合框架、遗留的 collection 类、事件模型、日期和时间设施、国际化和各种实用工具类(字符串标记生成器、随机数生成器和位数组、日期Date类、堆栈Stack类、向量Vector类等)。集合类、时间处理模式、日期时间工具等各类常用工具包。
Java的实用工具类库java.util包。在这个包中,Java提供了一些实用的方法和数据结构。例如,Java提供日期(Data)类、日历(Calendar)类来产生和获取日期及时间,提供随机数(Random)类产生各种类型的随机数,还提供了堆栈(Stack)、向量(Vector) 、位集合(Bitset)以及哈希表(Hashtable)等类来表示相应的数据结构。
1、简单来说servlet是运行在服务器上的java程序,servlet由servlet容器管理,servlet容器也叫 servlet引擎,是servlet的运行环境,给发送的请求和响应之上提供网络服务
2、servlet的作用
通俗来讲servlet专门用来接收客户端的请求,专门接收客户端的请求数据,然后调用底层service处理数据并生成结果
浏览器http请求------》tomcat服务器-------》到达servlet-----》执行doget,dopost方法----》返回数据
<1>客户端发送请求到服务器端
<2>服务器将请求信息发送至Servlet
<3>Servlet生成响应内容并将其传给服务器。
<4>服务器将响应返回给客户端。
3、servlet里的三大作用域:
request(请求):它的作用范围是一次请求和响应,是三个作用域中最小的。
session(会话):它的作用比request要大一点,一次会话过程中,它的作用域就一直存在,(默认是30分钟)
servletcontext:它作用范围最大,作用于整个服务器中。(Application)
接口层,用户访问请求时对接。
Controller层负责具体的业务模块流程的控制,在此层里面要调用Serice层的接口来控制业务流程,控制的配置也同样是在Spring的配置文件里面进行,针对具体的业务流程,会有不同的控制器,我们具体的设计过程中可以将流程进行抽象归纳,设计出可以重复利用的子单元流程模块,这样不仅使程序结构变得清晰,也大大减少了代码量。
在项目开始之前,我们首先要对项目的整体架构分析一下,该项目一共分为四个模块,登录注销、用户管理、订单管理、供应商管理,其中用户管理、订单管理以及供应商管理都是需要对数据库进行crud的。项目的整体架构图如下:
项目的架构分析完成之后,我们首先就需要进行一些前期准备,创建项目。首先创建一个Maven项目:
在Maven项目创建完毕之后,我们需要对配置文件进行修改
对web.xml的修改如下:
<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="false">
<welcome-file-list>
<welcome-file>login.jspwelcome-file>
welcome-file-list>
<session-config>
<session-timeout>30session-timeout>
session-config>
web-app>
对pom.xml进行配置,导入相关的依赖如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>smbms-JavaWebartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>smbms-JavaWeb Maven Webappname>
<url>http://www.example.comurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.7maven.compiler.source>
<maven.compiler.target>1.7maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.4version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.29version>
dependency>
<dependency>
<groupId>taglibsgroupId>
<artifactId>standardartifactId>
<version>1.1.2version>
dependency>
<dependency>
<groupId>javax.servlet.jsp.jstlgroupId>
<artifactId>jstl-apiartifactId>
<version>1.2version>
dependency>
dependencies>
<build>
<finalName>smbms-JavaWebfinalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-pluginartifactId>
<version>3.1.0version>
plugin>
<plugin>
<artifactId>maven-resources-pluginartifactId>
<version>3.0.2version>
plugin>
<plugin>
<artifactId>maven-compiler-pluginartifactId>
<version>3.8.0version>
plugin>
<plugin>
<artifactId>maven-surefire-pluginartifactId>
<version>2.22.1version>
plugin>
<plugin>
<artifactId>maven-war-pluginartifactId>
<version>3.2.2version>
plugin>
<plugin>
<artifactId>maven-install-pluginartifactId>
<version>2.5.2version>
plugin>
<plugin>
<artifactId>maven-deploy-pluginartifactId>
<version>2.8.2version>
plugin>
plugins>
pluginManagement>
build>
project>
在jsp中,我们使用jstl表达式时需要使用到jstl.jar。
jstl.jar:(jsp standard taglib)jstl的核心标签库。
standard.jar :jstl的类库,包含TLD 和标记句柄。
将Maven配置完成后,我们需要对Tomcat进行配置:
Tomcat配置完成之后,我们需要连接数据库
package com.wenhua.pojo;
import java.math.BigDecimal;
import java.util.Date;
/**
* 订单
*/
public class Bill {
private Integer id; //id
private String billCode; //账单编码
private String productName; //商品名称
private String productDesc; //商品描述
private String productUnit; //商品单位
private BigDecimal productCount; //商品数量
private BigDecimal totalPrice; //总金额
private Integer isPayment; //是否支付
private Integer providerId; //供应商ID
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate;//更新时间
private String providerName;//供应商名称
@Override
public String toString() {
return "Bill{" +
"id=" + id +
", billCode='" + billCode + '\'' +
", productName='" + productName + '\'' +
", productDesc='" + productDesc + '\'' +
", productUnit='" + productUnit + '\'' +
", productCount=" + productCount +
", totalPrice=" + totalPrice +
", isPayment=" + isPayment +
", providerId=" + providerId +
", createdBy=" + createdBy +
", creationDate=" + creationDate +
", modifyBy=" + modifyBy +
", modifyDate=" + modifyDate +
", providerName='" + providerName + '\'' +
'}';
}
public String getProviderName() {
return providerName;
}
public void setProviderName(String providerName) {
this.providerName = providerName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBillCode() {
return billCode;
}
public void setBillCode(String billCode) {
this.billCode = billCode;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductDesc() {
return productDesc;
}
public void setProductDesc(String productDesc) {
this.productDesc = productDesc;
}
public String getProductUnit() {
return productUnit;
}
public void setProductUnit(String productUnit) {
this.productUnit = productUnit;
}
public BigDecimal getProductCount() {
return productCount;
}
public void setProductCount(BigDecimal productCount) {
this.productCount = productCount;
}
public BigDecimal getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(BigDecimal totalPrice) {
this.totalPrice = totalPrice;
}
public Integer getIsPayment() {
return isPayment;
}
public void setIsPayment(Integer isPayment) {
this.isPayment = isPayment;
}
public Integer getProviderId() {
return providerId;
}
public void setProviderId(Integer providerId) {
this.providerId = providerId;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
package com.wenhua.pojo;
import java.util.Date;
/**
* 供应商
*/
public class Provider {
private Integer id; //id
private String proCode; //供应商编码
private String proName; //供应商名称
private String proDesc; //供应商描述
private String proContact; //供应商联系人
private String proPhone; //供应商电话
private String proAddress; //供应商地址
private String proFax; //供应商传真
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate;//更新时间
@Override
public String toString() {
return "Provider{" +
"id=" + id +
", proCode='" + proCode + '\'' +
", proName='" + proName + '\'' +
", proDesc='" + proDesc + '\'' +
", proContact='" + proContact + '\'' +
", proPhone='" + proPhone + '\'' +
", proAddress='" + proAddress + '\'' +
", proFax='" + proFax + '\'' +
", createdBy=" + createdBy +
", creationDate=" + creationDate +
", modifyBy=" + modifyBy +
", modifyDate=" + modifyDate +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProCode() {
return proCode;
}
public void setProCode(String proCode) {
this.proCode = proCode;
}
public String getProName() {
return proName;
}
public void setProName(String proName) {
this.proName = proName;
}
public String getProDesc() {
return proDesc;
}
public void setProDesc(String proDesc) {
this.proDesc = proDesc;
}
public String getProContact() {
return proContact;
}
public void setProContact(String proContact) {
this.proContact = proContact;
}
public String getProPhone() {
return proPhone;
}
public void setProPhone(String proPhone) {
this.proPhone = proPhone;
}
public String getProAddress() {
return proAddress;
}
public void setProAddress(String proAddress) {
this.proAddress = proAddress;
}
public String getProFax() {
return proFax;
}
public void setProFax(String proFax) {
this.proFax = proFax;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
package com.wenhua.pojo;
import java.util.Date;
/**
* 角色
*/
public class Role {
private Integer id; //id
private String roleCode; //角色编码
private String roleName; //角色名称
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate;//更新时间
@Override
public String toString() {
return "Role{" +
"id=" + id +
", roleCode='" + roleCode + '\'' +
", roleName='" + roleName + '\'' +
", createdBy=" + createdBy +
", creationDate=" + creationDate +
", modifyBy=" + modifyBy +
", modifyDate=" + modifyDate +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleCode() {
return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
package com.wenhua.pojo;
import java.util.Date;
/**
* 用户
*/
public class User {
private Integer id; //id
private String userCode; //用户编码
private String userName; //用户名称
private String userPassword; //用户密码
private Integer gender; //性别
private Date birthday; //出生日期
private String phone; //电话
private String address; //地址
private Integer userRole; //用户角色
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate; //更新时间
private Integer age;//年龄
private String userRoleName; //用户角色名称
public String getUserRoleName() {
return userRoleName;
}
public void setUserRoleName(String userRoleName) {
this.userRoleName = userRoleName;
}
public Integer getAge() {
/*long time = System.currentTimeMillis()-birthday.getTime();
Integer age = Long.valueOf(time/365/24/60/60/1000).IntegerValue();*/
Date date = new Date();
Integer age = date.getYear() - birthday.getYear();
return age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userCode='" + userCode + '\'' +
", userName='" + userName + '\'' +
", userPassword='" + userPassword + '\'' +
", gender=" + gender +
", birthday=" + birthday +
", phone='" + phone + '\'' +
", address='" + address + '\'' +
", userRole=" + userRole +
", createdBy=" + createdBy +
", creationDate=" + creationDate +
", modifyBy=" + modifyBy +
", modifyDate=" + modifyDate +
", age=" + age +
", userRoleName='" + userRoleName + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getUserRole() {
return userRole;
}
public void setUserRole(Integer userRole) {
this.userRole = userRole;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
因为我们每一个模块都会涉及到对数据库的crud,以及对数据库的资源的连接和关闭。是一个有着大量重复性的操作,所以我们需要编写一个公共类来实现这些操作,这样在编写每一个模块的时候就可以直接调用。
/**
* 操作数据库的基类--静态类
*/
public class BaseDao {
private static String driver;
private static String url;
private static String username;
private static String password;
//静态代码块,在类加载的时候执行
static {
//通过类加载读取响应的资源
Properties params = new Properties();
String configFile = "db.properties";
InputStream is = BaseDao.class.getClassLoader().getResourceAsStream(configFile);
try {
params.load(is);
} catch (IOException e) {
e.printStackTrace();
}
driver = params.getProperty("driver");
url = params.getProperty("url");
username = params.getProperty("username");
password = params.getProperty("password");
}
//获取数据库连接
public static Connection getConnection() {
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
//查询数据库的公共操作 执行sql查询语句
public static ResultSet execute(Connection connection, PreparedStatement pstm, ResultSet rs, String sql, Object[] params) {
try {
pstm = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pstm.setObject(i + 1, params[i]);
}
rs = pstm.executeQuery();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return rs;
}
//更新数据库的公共操作 对数据库进行crud
public static int execute(Connection connection, PreparedStatement pstm, String sql, Object[] params) {
int updateRows = 0;
try {
pstm = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pstm.setObject(i + 1, params[i]);
}
updateRows = pstm.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return updateRows;
}
//关闭数据库资源 释放资源
public static boolean closeResource(Connection connection, PreparedStatement pstm, ResultSet rs) {
boolean flag = true;
if (rs != null) {
try {
rs.close();
rs = null;//GC回收
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if (pstm != null) {
try {
pstm.close();
pstm = null;//GC回收
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if (connection != null) {
try {
connection.close();
connection = null;//GC回收
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
return flag;
}
}
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=UTC
username=root
password=123456
driver = com.mysql.jdbc.Driver (mysql 5)
driver = com.mysql.cj.jdbc.Driver (mysql 8)
"useUnicode=true&characterEncoding=UTF-8"的作用是:指定字符的编码、解码格式
MySQL在高版本需要指明是否进行SSL连接
(保障Internet数据传输安全利用数据加密)需要在url后面添加useSSL=true或者false不然在运行时控制台会出现红色警告。
useSSL=true 需要连接
useSSL=false 不需要连接
SSL是一种安全套接层协议,是Web浏览器与Web服务器之间安全交换信息的协议,提供两个基本的安全服务:鉴别与保密。
SSL协议的三个特性
① 保密:在握手协议中定义了会话密钥后,所有的消息都被加密;
② 鉴别:可选的客户端认证,和强制的服务器端认证;
③ 完整性:传送的消息包括消息完整性检查(使用MAC)。
serverTimezone=UTC 设置时区
/**
* 字符编码过滤器
* 过滤所有请求 /*
*/
@WebFilter("/*")
public class CharacterEncoding implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
编写了过滤器之后,我们还需要到web.xml中去注册才能实现过滤功能(拦截请求,过滤响应)
<filter>
<filter-name>filterfilter-name>
<filter-class>com.wenhua.filter.CharacterEncodingfilter-class>
filter>
<filter-mapping>
<filter-name>filterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
分析可以得知,我们进入登录界面之后,会通过login.do来判断是否登录成功,在我们发起登录请求的时候,就会将请求转发到后台,然后后台去查看数据库,将账号和密码进行判断,如果登录成功就会跳转到后台首页,否则依然停留在登录页面,并提示用户账号或密码错误
在导入静态资源后,有一个login.jsp文件,这就是我们的登录页面了,我们需要做的是在服务器启动的时候默认访问该文件,那么我们就应该在配置文件中修改首页。
我们在web.xml文件下加入下列代码就能使服务器启动的时候默认访问login.jsp
<welcome-file-list>
<welcome-file>login.jspwelcome-file>
welcome-file-list>
登录页面解决了,我们现在需要解决的就是首先就是账号和密码验证的问题了,由于浏览器发送请求给web端之后,web服务器会调用servlet来接受这个请求,所以我们就需要通过servlet来接受请求,处理完请求之后再反馈给浏览器。
因此我们需要一个底层来操作数据库(Dao),一层业务层来进行数据库数据和请求数据的比对来进行判断,判断完成后在返回给servlet,因此我们要实现三层的代码;
首先我们先对数据库进行操作,也就是dao层,在我们获得了数据库的数据后以及后台接受的数据,我们要进行比对,就在业务层完成。完成后我们我们将得到的用户返回给servlet层,如果该用户不为空,则证明登录成功,否则登录失败。并将结果反馈给浏览器。
//得到要登录的用户
@Override
public User getLoginUser(Connection connection, String userCode) {
PreparedStatement pstm = null;
ResultSet rs = null;
User user = null;
try {
if (null != connection) {
String sql = "select * from smbms_user where userCode=?";
Object[] params = {userCode};
rs = BaseDao.execute(connection, pstm, rs, sql, params);
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"));
}
}
BaseDao.closeResource(null, pstm, rs);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return user;
}
/**
* service层捕获异常,进行事务处理
* 事务处理:调用不同dao的多个方法,必须使用同一个connection(connection作为参数传递)
* 事务完成之后,需要在service层进行connection的关闭,在dao层关闭(PreparedStatement和ResultSet对象)
*
* @author Administrator
*/
//用户登录实现
@Override
public User login(String userCode, String userPassword) {
Connection connection = null;
User user = null;
try {
//获取与数据库的连接
connection = BaseDao.getConnection();
//通过业务层调用对应的具体数据库操作
user = userDao.getLoginUser(connection, userCode);
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭连接
BaseDao.closeResource(connection, null, null);
}
//匹配密码
if (null != user) {
if (!user.getUserPassword().equals(userPassword)) {
user = null;
}
}
return user;
}
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
//Servlet:控制层,调用业务层代码
private static final long serialVersionUID = -4672709233628500722L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取用户名和密码
String userCode = request.getParameter("userCode");
String userPassword = request.getParameter("userPassword");
//调用业务层service方法,和数据库中用户进行匹配
UserService userService = new UserServiceImpl();
User user = userService.login(userCode, userPassword);
//这里已经把登录的人查出来了
if (null != user) {//如果用户存在,则登录成功
//将用户的信息放入Session中
request.getSession().setAttribute(Constants.USER_SESSION, user);
//页面重定向(跳转到主页 frame.jsp)
response.sendRedirect("jsp/frame.jsp");
} else {//查无此人,无法登陆
//页面转发回登录界面(login.jsp)带出提示信息--用户名和密码错误
request.setAttribute("error", "用户名或密码不正确");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
<servlet>
<servlet-name>LoginServletservlet-name>
<servlet-class>com.wenhua.servlet.user.LoginServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>LoginServletservlet-name>
<url-pattern>/login.dourl-pattern>
servlet-mapping>
注销我们在接受请求后,重定向到登录界面即可。为了防止没有登录直接输入链接进入后台界面,我们同样需要一个过滤器来阻挡这些请求.
@WebFilter("/jsp/*")
public class SysFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest rq = (HttpServletRequest) request;
HttpServletResponse rp = (HttpServletResponse) response;
//过滤器,从session中获取用户
User userSession = (User) rq.getSession().getAttribute("userSession");
//用户信息已经被移除或者注销,或者未登录
if (null == userSession) {
rp.sendRedirect("/error.jsp");
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
<filter>
<filter-name>SysFilterfilter-name>
<filter-class>com.wenhua.filter.SysFilterfilter-class>
filter>
<filter-mapping>
<filter-name>SysFilterfilter-name>
<url-pattern>/jsp/*url-pattern>
filter-mapping>
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//移除用户的Session
req.getSession().removeAttribute(Constants.USER_SESSION);
resp.sendRedirect(req.getContextPath() + "/login.jsp");//返回登录界面
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>LogoutServletservlet-name>
<servlet-class>com.wenhua.servlet.user.LogoutServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>LogoutServletservlet-name>
<url-pattern>/jsp/logout.dourl-pattern>
servlet-mapping>
通过查看我们可以知道要显示如下信息:
因此我们首先需要获得RoleList也就是角色列表,通过下面一张图片我们可以判断出来queryUserName 和RoleList都是查询的条件,我们需要点击按钮来进行查询,所以我们需要在底层首先写一个获得角色列表的类,在用户点击查询按钮之后,我们还要获得queryUserName,并且根据这两个属性去进行查询。
在这张图片中我们可以看到页面所显示的还有关于页码以及页数的信息,所以我们所做出来的查询需要将页数相关的信息也传到前端去
package com.wenhua.util;
public class PageSupport {
//当前页码-来自于用户输入
private int currentPageNo = 1;
//总数量(表)
private int totalCount = 0;
//页面容量
private int pageSize = 0;
//总页数-totalCount/pageSize(+1)
private int totalPageCount = 1;
public int getCurrentPageNo() {
return currentPageNo;
}
public void setCurrentPageNo(int currentPageNo) {
if (currentPageNo > 0) {
this.currentPageNo = currentPageNo;
}
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
if (totalCount > 0) {
this.totalCount = totalCount;
//设置总页数
this.setTotalPageCountByRs();
}
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
if (pageSize > 0) {
this.pageSize = pageSize;
}
}
public int getTotalPageCount() {
return totalPageCount;
}
public void setTotalPageCount(int totalPageCount) {
this.totalPageCount = totalPageCount;
}
public void setTotalPageCountByRs() {
if (this.totalCount % this.pageSize == 0) {
this.totalPageCount = this.totalCount / this.pageSize;
} else if (this.totalCount % this.pageSize > 0) {
this.totalPageCount = this.totalCount / this.pageSize + 1;
} else {
this.totalPageCount = 0;
}
}
}
@Override
public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize)
throws Exception {
PreparedStatement pstm = null;
ResultSet rs = null;
List<User> userList = new ArrayList<User>();
if (connection != null) {
StringBuffer sql = new StringBuffer();
sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id");
List<Object> list = new ArrayList<Object>();
if (!StringUtils.isNullOrEmpty(userName)) {
sql.append(" and u.userName like ?");
list.add("%" + userName + "%");
}
if (userRole > 0) {
sql.append(" and u.userRole = ?");
list.add(userRole);
}
//在mysql数据库中,分页使用 limit startIndex,pageSize ; 总数
sql.append(" order by creationDate DESC limit ?,?");
currentPageNo = (currentPageNo - 1) * pageSize;
list.add(currentPageNo);
list.add(pageSize);
Object[] params = list.toArray();
System.out.println("sql ----> " + sql.toString());
rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);
while (rs.next()) {
User _user = new User();
_user.setId(rs.getInt("id"));
_user.setUserCode(rs.getString("userCode"));
_user.setUserName(rs.getString("userName"));
_user.setGender(rs.getInt("gender"));
_user.setBirthday(rs.getDate("birthday"));
_user.setPhone(rs.getString("phone"));
_user.setUserRole(rs.getInt("userRole"));
_user.setUserRoleName(rs.getString("userRoleName"));
userList.add(_user);
}
BaseDao.closeResource(null, pstm, rs);
}
return userList;
}
@Override
public int getUserCount(Connection connection, String userName, int userRole) throws Exception {
PreparedStatement pstm = null;
ResultSet rs = null;
int count = 0;
if (connection != null) {
StringBuffer sql = new StringBuffer();
sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id");
//List用来储存我们的参数
List<Object> list = new ArrayList();
if (!StringUtils.isNullOrEmpty(userName)) {
sql.append(" and u.userName like ?");
list.add("%" + userName + "%");
}
if (userRole > 0) {
sql.append(" and u.userRole = ?");
list.add(userRole);
}
Object[] params = list.toArray();
System.out.println("sql ----> " + sql.toString());
rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);
if (rs.next()) {
count = rs.getInt("count");
}
BaseDao.closeResource(null, pstm, rs);
}
return count;
}
}
@Override
public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) {
Connection connection = null;
List<User> userList = null;
try {
//获取与数据库的连接
connection = BaseDao.getConnection();
userList = userDao.getUserList(connection, queryUserName, queryUserRole, currentPageNo, pageSize);
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭连接
BaseDao.closeResource(connection, null, null);
}
return userList;
}
@Override
public int getUserCount(String queryUserName, int queryUserRole) {
Connection connection = null;
int count = 0;
try {
connection = BaseDao.getConnection();
count = userDao.getUserCount(connection, queryUserName, queryUserRole);
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return count;
}
private void getRoleList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Role> roleList = null;
RoleService roleService = new RoleServiceImpl();
roleList = roleService.getRoleList();
//把RoleList转换成json对象输出
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(roleList));
outPrintWriter.flush();
outPrintWriter.close();
}
private void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//查询用户列表
//从前端获取数据
String queryUserName = request.getParameter("queryname");
String temp = request.getParameter("queryUserRole");
String pageIndex = request.getParameter("pageIndex");
int queryUserRole = 0;
UserService userService = new UserServiceImpl();
List<User> userList = null;
//第一次走这个请求,一定是第一页,页面大小是固定的
//设置页面容量
int pageSize = Constants.pageSize;
//默认当前页码
int currentPageNo = 1;
if (queryUserName == null) {
queryUserName = "";
}
if (temp != null && !temp.equals("")) {
queryUserRole = Integer.parseInt(temp);
}
if (pageIndex != null) {
try {
currentPageNo = Integer.valueOf(pageIndex);
} catch (NumberFormatException e) {
response.sendRedirect("error.jsp");
}
}
//总数量(表) 获取用户的总数
int totalCount = userService.getUserCount(queryUserName, queryUserRole);
//总页数
PageSupport pages = new PageSupport();
pages.setCurrentPageNo(currentPageNo); //设置当前页数
pages.setPageSize(pageSize); //设置页数记录数
pages.setTotalCount(totalCount); //设置所有记录数目(总数量)
int totalPageCount = pages.getTotalPageCount(); //总页面数量
//控制首页和尾页
//如果页面小于第一页,就显示第一页
if (currentPageNo < 1) {
currentPageNo = 1;
//如果当前页面大于最后一页,当前页等于最后一页即可
} else if (currentPageNo > totalPageCount) {
currentPageNo = totalPageCount;
}
//获取用户列表展示
userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
request.setAttribute("userList", userList);
//获取角色列表
List<Role> roleList = null;
RoleService roleService = new RoleServiceImpl();
roleList = roleService.getRoleList();
request.setAttribute("roleList", roleList);
request.setAttribute("queryUserName", queryUserName);
request.setAttribute("queryUserRole", queryUserRole);
request.setAttribute("totalPageCount", totalPageCount);
request.setAttribute("totalCount", totalCount);
request.setAttribute("currentPageNo", currentPageNo);
//返回前端
request.getRequestDispatcher("userlist.jsp").forward(request, response);
}
我们将图中的信息取出来进行添加即可
在useradd的js代码中我们可以看到此处使用ajax对填写usercode的时候已经在判定是否存在,所以我们还需要对用户的编码进行判定是否已经存在该用户
AJAX
全称(Async Javascript and XML)
即异步的JavaScript
和XML
,是一种创建交互式网页应用的网页开发技术,可以在不重新加载整个网页的情况下,与服务器交换数据,并且更新部分网页
Ajax
的原理简单来说通过XmlHttpRequest
对象来向服务器发异步请求,从服务器获得数据,然后用JavaScript
来操作DOM
而更新页面
@Override
public int add(Connection connection, User user) {
PreparedStatement pstm = null;
int updateRows = 0;
if (null != connection) {
String sql = "insert into smbms_user (userCode,userName,userPassword," +
"userRole,gender,birthday,phone,address,creationDate,createdBy) " +
"values(?,?,?,?,?,?,?,?,?,?)";
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, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return updateRows;
}
@Override
public boolean add(User user) {
// TODO Auto-generated method stub
boolean flag = false;
Connection connection = null;
try {
connection = BaseDao.getConnection();
connection.setAutoCommit(false);
//开启JDBC事务管理,同时设置提交为false
int updateRows = userDao.add(connection, user);
connection.commit();
if (updateRows > 0) {
flag = true;
System.out.println("add success!");
} else {
System.out.println("add failed!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
System.out.println("rollback==================");
connection.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
//在service层进行connection连接的关闭
BaseDao.closeResource(connection, null, null);
}
return flag;
}
private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userCode = request.getParameter("userCode");
String userName = request.getParameter("userName");
String userPassword = request.getParameter("userPassword");
String gender = request.getParameter("gender");
String birthday = request.getParameter("birthday");
String phone = request.getParameter("phone");
String address = request.getParameter("address");
String userRole = request.getParameter("userRole");
User user = new 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) {
e.printStackTrace();
}
user.setGender(Integer.valueOf(gender));
user.setPhone(phone);
user.setUserRole(Integer.valueOf(userRole));
user.setCreationDate(new Date());
user.setCreatedBy(((User) request.getSession().getAttribute(Constants.USER_SESSION)).getId());
UserService userService = new UserServiceImpl();
if (userService.add(user)) {
response.sendRedirect(request.getContextPath() + "/jsp/user.do?method=query");
} else {
request.getRequestDispatcher("useradd.jsp").forward(request, response);
}
}
private void userCodeExist(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//判断用户账号是否可用
String userCode = request.getParameter("userCode");
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();//关闭流
}
删除用户与添加用户同理,获得用户之后进行删除
@Override
public int deleteUserById(Connection connection, Integer delId) throws Exception {
PreparedStatement pstm = null;
int flag = 0;
if (null != connection) {
String sql = "delete from smbms_user where id=?";
Object[] params = {delId};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
@Override
public boolean deleteUserById(Integer delId) {
Connection connection = null;
boolean flag = false;
try {
connection = BaseDao.getConnection();
if (userDao.deleteUserById(connection, delId) > 0) {
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return flag;
}
private void delUser(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("uid");
Integer delId = 0;
try {
delId = Integer.parseInt(id);
} catch (Exception e) {
// TODO: handle exception
delId = 0;
}
HashMap<String, String> resultMap = new HashMap<String, String>();
if (delId <= 0) {
resultMap.put("delResult", "notexist");
} else {
UserService userService = new UserServiceImpl();
if (userService.deleteUserById(delId)) {
resultMap.put("delResult", "true");
} else {
resultMap.put("delResult", "false");
}
}
//把resultMap转换成json对象输出
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();
outPrintWriter.close();
}
我们可以看到,一个修改功能实际上需要两个实现,我们不难想到,在我们进入修改界面的时候,我们首先获取的是该户的已有信息,因此我们会先获取对应的用户,在我们点击确认按钮之后,会调用另一个功能,获取我们所填写的信息。因此我们需要在servlet层编写两个函数
@Override
public int modify(Connection connection, User user) throws Exception {
int flag = 0;
PreparedStatement pstm = null;
if (null != connection) {
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()};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
@Override
public boolean modify(User user) {
// TODO Auto-generated method stub
Connection connection = null;
boolean flag = false;
try {
connection = BaseDao.getConnection();
if (userDao.modify(connection, user) > 0) {
flag = true;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return flag;
}
private void modify(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("uid");
String userName = request.getParameter("userName");
String gender = request.getParameter("gender");
String birthday = request.getParameter("birthday");
String phone = request.getParameter("phone");
String address = request.getParameter("address");
String userRole = request.getParameter("userRole");
User user = new User();
user.setId(Integer.valueOf(id));
user.setUserName(userName);
user.setGender(Integer.valueOf(gender));
try {
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
user.setPhone(phone);
user.setAddress(address);
user.setUserRole(Integer.valueOf(userRole));
user.setModifyBy(((User) request.getSession().getAttribute(Constants.USER_SESSION)).getId());
user.setModifyDate(new Date());
UserService userService = new UserServiceImpl();
if (userService.modify(user)) {
response.sendRedirect(request.getContextPath() + "/jsp/user.do?method=query");
} else {
request.getRequestDispatcher("usermodify.jsp").forward(request, response);
}
}
private void getUserById(HttpServletRequest request, HttpServletResponse response, String url)
throws ServletException, IOException {
String id = request.getParameter("uid");
if (!StringUtils.isNullOrEmpty(id)) {
//调用后台方法得到user对象
UserService userService = new UserServiceImpl();
User user = userService.getUserById(id);
request.setAttribute("user", user);
request.getRequestDispatcher(url).forward(request, response);
}
}
获得该用户信息后跳转到对应界面即可
@Override
public User getUserById(Connection connection, String id) throws Exception {
User user = null;
PreparedStatement pstm = null;
ResultSet rs = null;
if (null != connection) {
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, pstm, rs, sql, params);
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, pstm, rs);
}
return user;
}
@Override
public User getUserById(String id) {
// TODO Auto-generated method stub
User user = null;
Connection connection = null;
try {
//获取与数据库的连接
connection = BaseDao.getConnection();
//获取用户
user = userDao.getUserById(connection, id);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
user = null;
} finally {
//关闭连接
BaseDao.closeResource(connection, null, null);
}
return user;
}
private void getUserById(HttpServletRequest request, HttpServletResponse response, String url)
throws ServletException, IOException {
String id = request.getParameter("uid");
if (!StringUtils.isNullOrEmpty(id)) {
//调用后台方法得到user对象
UserService userService = new UserServiceImpl();
User user = userService.getUserById(id);
request.setAttribute("user", user);
request.getRequestDispatcher(url).forward(request, response);
}
}
@Override
public int updatePwd(Connection connection, int id, String pwd) throws Exception {
int flag = 0;
PreparedStatement pstm = null;
if (connection != null) {
String sql = "update smbms_user set userPassword= ? where id = ?";
Object[] params = {pwd, id};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
@Override
public boolean updatePwd(int id, String pwd) {
boolean flag = false;
Connection connection = null;
try {
connection = BaseDao.getConnection();
if (userDao.updatePwd(connection, id, pwd) > 0) {
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return flag;
}
private void updatePwd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Object o = request.getSession().getAttribute(Constants.USER_SESSION);
String newpassword = request.getParameter("newpassword");
boolean flag = false;
if (o != null && !StringUtils.isNullOrEmpty(newpassword)) {
UserService userService = new UserServiceImpl();
flag = userService.updatePwd(((User) o).getId(), newpassword);
if (flag) {
request.setAttribute(Constants.SYS_MESSAGE, "修改密码成功,请退出并使用新密码重新登录!");
request.getSession().removeAttribute(Constants.USER_SESSION);//session注销
} else {
request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败!");
}
} else {
request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败!");
}
//修改成功后转发就行了
request.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(request, response);
}
//通过ajax验证旧密码,到session拿即可
private void getPwdByUserId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//从Session里面拿Id
Object o = request.getSession().getAttribute(Constants.USER_SESSION);
String oldpassword = request.getParameter("oldpassword");
Map<String, String> resultMap = new HashMap();
if (null == o) {//session过期
resultMap.put("result", "sessionerror");
} else if (StringUtils.isNullOrEmpty(oldpassword)) {//旧密码输入为空
resultMap.put("result", "error");
} else {
String sessionPwd = ((User) o).getUserPassword(); //获取Session中用户的密码
if (oldpassword.equals(sessionPwd)) {
resultMap.put("result", "true");
} else {//旧密码输入不正确
resultMap.put("result", "false");
}
}
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();
outPrintWriter.close();
}
与用户管理的功能一样,因此直接展示代码
package com.wenhua.dao.provider;
import com.wenhua.pojo.Provider;
import java.sql.Connection;
import java.util.List;
public interface ProviderDao {
/**
* 增加供应商
*
* @param connection
* @param provider
* @return
* @throws Exception
*/
int add(Connection connection, Provider provider) throws Exception;
/**
* 通过供应商名称、编码获取供应商列表-模糊查询-providerList
*
* @param connection
* @param proName
* @return
* @throws Exception
*/
List<Provider> getProviderList(Connection connection, String proName, String proCode) throws Exception;
/**
* 通过proId删除Provider
*
* @param delId
* @return
* @throws Exception
*/
int deleteProviderById(Connection connection, String delId) throws Exception;
/**
* 通过proId获取Provider
*
* @param connection
* @param id
* @return
* @throws Exception
*/
Provider getProviderById(Connection connection, String id) throws Exception;
/**
* 修改用户信息
*
* @param connection
* @param provider
* @return
* @throws Exception
*/
int modify(Connection connection, Provider provider) throws Exception;
}
package com.wenhua.dao.provider;
import com.mysql.cj.util.StringUtils;
import com.wenhua.dao.BaseDao;
import com.wenhua.pojo.Provider;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class ProviderDaoImpl implements ProviderDao {
@Override
public int add(Connection connection, Provider provider)
throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstm = null;
int flag = 0;
if (null != connection) {
String sql = "insert into smbms_provider (proCode,proName,proDesc," +
"proContact,proPhone,proAddress,proFax,createdBy,creationDate) " +
"values(?,?,?,?,?,?,?,?,?)";
Object[] params = {provider.getProCode(), provider.getProName(), provider.getProDesc(),
provider.getProContact(), provider.getProPhone(), provider.getProAddress(),
provider.getProFax(), provider.getCreatedBy(), provider.getCreationDate()};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
@Override
public List<Provider> getProviderList(Connection connection, String proName, String proCode)
throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstm = null;
ResultSet rs = null;
List<Provider> providerList = new ArrayList<Provider>();
if (connection != null) {
StringBuffer sql = new StringBuffer();
sql.append("select * from smbms_provider where 1=1 ");
List<Object> list = new ArrayList<Object>();
if (!StringUtils.isNullOrEmpty(proName)) {
sql.append(" and proName like ?");
list.add("%" + proName + "%");
}
if (!StringUtils.isNullOrEmpty(proCode)) {
sql.append(" and proCode like ?");
list.add("%" + proCode + "%");
}
Object[] params = list.toArray();
System.out.println("sql ----> " + sql.toString());
rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);
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, pstm, rs);
}
return providerList;
}
@Override
public int deleteProviderById(Connection connection, String delId)
throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstm = null;
int flag = 0;
if (null != connection) {
String sql = "delete from smbms_provider where id=?";
Object[] params = {delId};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
@Override
public Provider getProviderById(Connection connection, String id)
throws Exception {
// TODO Auto-generated method stub
Provider provider = null;
PreparedStatement pstm = null;
ResultSet rs = null;
if (null != connection) {
String sql = "select * from smbms_provider where id=?";
Object[] params = {id};
rs = BaseDao.execute(connection, pstm, rs, sql, params);
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, pstm, rs);
}
return provider;
}
@Override
public int modify(Connection connection, Provider provider)
throws Exception {
// TODO Auto-generated method stub
int flag = 0;
PreparedStatement pstm = null;
if (null != connection) {
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()};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
}
package com.wenhua.service.provider;
import com.wenhua.pojo.Provider;
import java.util.List;
public interface ProviderService {
/**
* 增加供应商
*
* @param provider
* @return
*/
public boolean add(Provider provider);
/**
* 通过供应商名称、编码获取供应商列表-模糊查询-providerList
*
* @param proName
* @return
*/
public List<Provider> getProviderList(String proName, String proCode);
/**
* 通过proId删除Provider
*
* @param delId
* @return
*/
public int deleteProviderById(String delId);
/**
* 通过proId获取Provider
*
* @param id
* @return
*/
public Provider getProviderById(String id);
/**
* 修改用户信息
*
* @param user
* @return
*/
public boolean modify(Provider provider);
}
package com.wenhua.service.provider;
import com.wenhua.dao.BaseDao;
import com.wenhua.dao.bill.BillDao;
import com.wenhua.dao.bill.BillDaoImpl;
import com.wenhua.dao.provider.ProviderDao;
import com.wenhua.dao.provider.ProviderDaoImpl;
import com.wenhua.pojo.Provider;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class ProviderServiceImpl implements ProviderService {
private ProviderDao providerDao;
private BillDao billDao;
public ProviderServiceImpl() {
providerDao = new ProviderDaoImpl();
billDao = new BillDaoImpl();
}
@Override
public boolean add(Provider provider) {
// TODO Auto-generated method stub
boolean flag = false;
Connection connection = null;
try {
connection = BaseDao.getConnection();
connection.setAutoCommit(false);//开启JDBC事务管理
if (providerDao.add(connection, provider) > 0)
flag = true;
connection.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
System.out.println("rollback==================");
connection.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
//在service层进行connection连接的关闭
BaseDao.closeResource(connection, null, null);
}
return flag;
}
@Override
public List<Provider> getProviderList(String proName, String proCode) {
// TODO Auto-generated method stub
Connection connection = null;
List<Provider> providerList = null;
System.out.println("query proName ---- > " + proName);
System.out.println("query proCode ---- > " + proCode);
try {
connection = BaseDao.getConnection();
providerList = providerDao.getProviderList(connection, proName, proCode);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return providerList;
}
/**
* 业务:根据ID删除供应商表的数据之前,需要先去订单表里进行查询操作
* 若订单表中无该供应商的订单数据,则可以删除
* 若有该供应商的订单数据,则不可以删除
* 返回值billCount
* 1> billCount == 0 删除---1 成功 (0) 2 不成功 (-1)
* 2> billCount > 0 不能删除 查询成功(0)查询不成功(-1)
*
* ---判断
* 如果billCount = -1 失败
* 若billCount >= 0 成功
*/
@Override
public int deleteProviderById(String delId) {
// TODO Auto-generated method stub
Connection connection = null;
int billCount = -1;
try {
connection = BaseDao.getConnection();
connection.setAutoCommit(false);
billCount = billDao.getBillCountByProviderId(connection, delId);
if (billCount == 0) {
providerDao.deleteProviderById(connection, delId);
}
connection.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
billCount = -1;
try {
connection.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
BaseDao.closeResource(connection, null, null);
}
return billCount;
}
@Override
public Provider getProviderById(String id) {
// TODO Auto-generated method stub
Provider provider = null;
Connection connection = null;
try {
connection = BaseDao.getConnection();
provider = providerDao.getProviderById(connection, id);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
provider = null;
} finally {
BaseDao.closeResource(connection, null, null);
}
return provider;
}
@Override
public boolean modify(Provider provider) {
// TODO Auto-generated method stub
Connection connection = null;
boolean flag = false;
try {
connection = BaseDao.getConnection();
if (providerDao.modify(connection, provider) > 0)
flag = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return flag;
}
}
package com.wenhua.servlet.provider;
import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.wenhua.pojo.Provider;
import com.wenhua.pojo.User;
import com.wenhua.service.provider.ProviderService;
import com.wenhua.service.provider.ProviderServiceImpl;
import com.wenhua.util.Constants;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@WebServlet("/jsp/provider.do")
public class ProviderServlet extends HttpServlet {
private static final long serialVersionUID = -3029814594716051531L;
/**
* Destruction of the servlet.
*/
@Override
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String method = request.getParameter("method");
if (method != null && method.equals("query")) {
this.query(request, response);
} else if (method != null && method.equals("add")) {
this.add(request, response);
} else if (method != null && method.equals("view")) {
this.getProviderById(request, response, "providerview.jsp");
} else if (method != null && method.equals("modify")) {
this.getProviderById(request, response, "providermodify.jsp");
} else if (method != null && method.equals("modifysave")) {
this.modify(request, response);
} else if (method != null && method.equals("delprovider")) {
this.delProvider(request, response);
}
}
private void delProvider(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("proid");
HashMap<String, String> resultMap = new HashMap<String, String>();
if (!StringUtils.isNullOrEmpty(id)) {
ProviderService providerService = new ProviderServiceImpl();
int flag = providerService.deleteProviderById(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");
}
//把resultMap转换成json对象输出
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();
outPrintWriter.close();
}
private 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("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 getProviderById(HttpServletRequest request, HttpServletResponse response, String url)
throws ServletException, IOException {
String id = request.getParameter("proid");
if (!StringUtils.isNullOrEmpty(id)) {
ProviderService providerService = new ProviderServiceImpl();
Provider provider = null;
provider = providerService.getProviderById(id);
request.setAttribute("provider", provider);
request.getRequestDispatcher(url).forward(request, response);
}
}
private void add(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String proCode = request.getParameter("proCode");
String proName = request.getParameter("proName");
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");
Provider provider = new Provider();
provider.setProCode(proCode);
provider.setProName(proName);
provider.setProContact(proContact);
provider.setProPhone(proPhone);
provider.setProFax(proFax);
provider.setProAddress(proAddress);
provider.setProDesc(proDesc);
provider.setCreatedBy(((User) request.getSession().getAttribute(Constants.USER_SESSION)).getId());
provider.setCreationDate(new Date());
boolean flag = false;
ProviderService providerService = new ProviderServiceImpl();
flag = providerService.add(provider);
if (flag) {
response.sendRedirect(request.getContextPath() + "/jsp/provider.do?method=query");
} else {
request.getRequestDispatcher("provideradd.jsp").forward(request, response);
}
}
private void query(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String queryProName = request.getParameter("queryProName");
String queryProCode = request.getParameter("queryProCode");
if (StringUtils.isNullOrEmpty(queryProName)) {
queryProName = "";
}
if (StringUtils.isNullOrEmpty(queryProCode)) {
queryProCode = "";
}
List<Provider> providerList = new ArrayList<Provider>();
ProviderService providerService = new ProviderServiceImpl();
providerList = providerService.getProviderList(queryProName, queryProCode);
request.setAttribute("providerList", providerList);
request.setAttribute("queryProName", queryProName);
request.setAttribute("queryProCode", queryProCode);
request.getRequestDispatcher("providerlist.jsp").forward(request, response);
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
@Override
public void init() throws ServletException {
// Put your code here
}
}
订单管理跟之前也没有太大的出入,直接展示代码
package com.wenhua.dao.bill;
import com.wenhua.pojo.Bill;
import java.sql.Connection;
import java.util.List;
public interface BillDao {
/**
* 增加订单
*
* @param connection
* @param bill
* @return
* @throws Exception
*/
int add(Connection connection, Bill bill) throws Exception;
/**
* 通过查询条件获取供应商列表-模糊查询-getBillList
*
* @param connection
* @param bill
* @return
* @throws Exception
*/
List<Bill> getBillList(Connection connection, Bill bill) throws Exception;
/**
* 通过delId删除Bill
*
* @param connection
* @param delId
* @return
* @throws Exception
*/
int deleteBillById(Connection connection, String delId) throws Exception;
/**
* 通过billId获取Bill
*
* @param connection
* @param id
* @return
* @throws Exception
*/
Bill getBillById(Connection connection, String id) throws Exception;
/**
* 修改订单信息
*
* @param connection
* @param bill
* @return
* @throws Exception
*/
int modify(Connection connection, Bill bill) throws Exception;
/**
* 根据供应商ID查询订单数量
*
* @param connection
* @param providerId
* @return
* @throws Exception
*/
int getBillCountByProviderId(Connection connection, String providerId) throws Exception;
}
package com.wenhua.dao.bill;
import com.mysql.cj.util.StringUtils;
import com.wenhua.dao.BaseDao;
import com.wenhua.pojo.Bill;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class BillDaoImpl implements BillDao {
@Override
public int add(Connection connection, Bill bill) throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstm = null;
int flag = 0;
if (null != connection) {
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()};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
System.out.println("dao--------flag " + flag);
}
return flag;
}
@Override
public List<Bill> getBillList(Connection connection, Bill bill)
throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstm = null;
ResultSet rs = null;
List<Bill> billList = new ArrayList<Bill>();
if (connection != 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>();
if (!StringUtils.isNullOrEmpty(bill.getProductName())) {
sql.append(" and productName like ?");
list.add("%" + bill.getProductName() + "%");
}
if (bill.getProviderId() > 0) {
sql.append(" and providerId = ?");
list.add(bill.getProviderId());
}
if (bill.getIsPayment() > 0) {
sql.append(" and isPayment = ?");
list.add(bill.getIsPayment());
}
Object[] params = list.toArray();
System.out.println("sql --------- > " + sql.toString());
rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);
while (rs.next()) {
Bill _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.setCreationDate(rs.getTimestamp("creationDate"));
_bill.setCreatedBy(rs.getInt("createdBy"));
billList.add(_bill);
}
BaseDao.closeResource(null, pstm, rs);
}
return billList;
}
@Override
public int deleteBillById(Connection connection, String delId)
throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstm = null;
int flag = 0;
if (null != connection) {
String sql = "delete from smbms_bill where id=?";
Object[] params = {delId};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
@Override
public Bill getBillById(Connection connection, String id) throws Exception {
// TODO Auto-generated method stub
Bill bill = null;
PreparedStatement pstm = null;
ResultSet rs = null;
if (null != connection) {
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(connection, pstm, rs, sql, params);
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, pstm, rs);
}
return bill;
}
@Override
public int modify(Connection connection, Bill bill) throws Exception {
// TODO Auto-generated method stub
int flag = 0;
PreparedStatement pstm = null;
if (null != connection) {
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()};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
@Override
public int getBillCountByProviderId(Connection connection, String providerId)
throws Exception {
// TODO Auto-generated method stub
int count = 0;
PreparedStatement pstm = null;
ResultSet rs = null;
if (null != connection) {
String sql = "select count(1) as billCount from smbms_bill where" +
" providerId = ?";
Object[] params = {providerId};
rs = BaseDao.execute(connection, pstm, rs, sql, params);
if (rs.next()) {
count = rs.getInt("billCount");
}
BaseDao.closeResource(null, pstm, rs);
}
return count;
}
}
package com.wenhua.service.bill;
import com.wenhua.pojo.Bill;
import java.util.List;
public interface BillService {
/**
* 增加订单
*
* @param bill
* @return
*/
public boolean add(Bill bill);
/**
* 通过条件获取订单列表-模糊查询-billList
*
* @param bill
* @return
*/
public List<Bill> getBillList(Bill bill);
/**
* 通过billId删除Bill
*
* @param delId
* @return
*/
public boolean deleteBillById(String delId);
/**
* 通过billId获取Bill
*
* @param id
* @return
*/
public Bill getBillById(String id);
/**
* 修改订单信息
*
* @param bill
* @return
*/
public boolean modify(Bill bill);
}
package com.wenhua.service.bill;
import com.wenhua.dao.BaseDao;
import com.wenhua.dao.bill.BillDao;
import com.wenhua.dao.bill.BillDaoImpl;
import com.wenhua.pojo.Bill;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class BillServiceImpl implements BillService {
private BillDao billDao;
public BillServiceImpl() {
billDao = new BillDaoImpl();
}
@Override
public boolean add(Bill bill) {
// TODO Auto-generated method stub
boolean flag = false;
Connection connection = null;
try {
connection = BaseDao.getConnection();
connection.setAutoCommit(false);//开启JDBC事务管理
if (billDao.add(connection, bill) > 0)
flag = true;
connection.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
System.out.println("rollback==================");
connection.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
//在service层进行connection连接的关闭
BaseDao.closeResource(connection, null, null);
}
return flag;
}
@Override
public List<Bill> getBillList(Bill bill) {
// TODO Auto-generated method stub
Connection connection = null;
List<Bill> billList = null;
System.out.println("query productName ---- > " + bill.getProductName());
System.out.println("query providerId ---- > " + bill.getProviderId());
System.out.println("query isPayment ---- > " + bill.getIsPayment());
try {
connection = BaseDao.getConnection();
billList = billDao.getBillList(connection, bill);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return billList;
}
@Override
public boolean deleteBillById(String delId) {
// TODO Auto-generated method stub
Connection connection = null;
boolean flag = false;
try {
connection = BaseDao.getConnection();
if (billDao.deleteBillById(connection, delId) > 0)
flag = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return flag;
}
@Override
public Bill getBillById(String id) {
// TODO Auto-generated method stub
Bill bill = null;
Connection connection = null;
try {
connection = BaseDao.getConnection();
bill = billDao.getBillById(connection, id);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
bill = null;
} finally {
BaseDao.closeResource(connection, null, null);
}
return bill;
}
@Override
public boolean modify(Bill bill) {
// TODO Auto-generated method stub
Connection connection = null;
boolean flag = false;
try {
connection = BaseDao.getConnection();
if (billDao.modify(connection, bill) > 0)
flag = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return flag;
}
}
package com.wenhua.servlet.bill;
import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.wenhua.pojo.Bill;
import com.wenhua.pojo.Provider;
import com.wenhua.pojo.User;
import com.wenhua.service.bill.BillService;
import com.wenhua.service.bill.BillServiceImpl;
import com.wenhua.service.provider.ProviderService;
import com.wenhua.service.provider.ProviderServiceImpl;
import com.wenhua.util.Constants;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@WebServlet("/jsp/bill.do")
public class BillServlet extends HttpServlet {
private static final long serialVersionUID = -1898446683172394681L;
/**
* Destruction of the servlet.
*/
@Override
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*String totalPrice = request.getParameter("totalPrice");
//23.234 45
BigDecimal totalPriceBigDecimal =
//设置规则,小数点保留两位,多出部分,ROUND_DOWN 舍弃
//ROUND_HALF_UP 四舍五入(5入) ROUND_UP 进位
//ROUND_HALF_DOWN 四舍五入(5不入)
new BigDecimal(totalPrice).setScale(2,BigDecimal.ROUND_DOWN);*/
String method = request.getParameter("method");
if (method != null && method.equals("query")) {
this.query(request, response);
} else if (method != null && method.equals("add")) {
this.add(request, response);
} else if (method != null && method.equals("view")) {
this.getBillById(request, response, "billview.jsp");
} else if (method != null && method.equals("modify")) {
this.getBillById(request, response, "billmodify.jsp");
} else if (method != null && method.equals("modifysave")) {
this.modify(request, response);
} else if (method != null && method.equals("delbill")) {
this.delBill(request, response);
} else if (method != null && method.equals("getproviderlist")) {
this.getProviderlist(request, response);
}
}
private void getProviderlist(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("getproviderlist ========================= ");
List<Provider> providerList = new ArrayList<Provider>();
ProviderService providerService = new ProviderServiceImpl();
providerList = providerService.getProviderList("", "");
//把providerList转换成json对象输出
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(providerList));
outPrintWriter.flush();
outPrintWriter.close();
}
private void getBillById(HttpServletRequest request, HttpServletResponse response, String url)
throws ServletException, IOException {
String id = request.getParameter("billid");
if (!StringUtils.isNullOrEmpty(id)) {
BillService billService = new BillServiceImpl();
Bill bill = null;
bill = billService.getBillById(id);
request.setAttribute("bill", bill);
request.getRequestDispatcher(url).forward(request, response);
}
}
private void modify(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("modify===============");
String id = request.getParameter("id");
String productName = request.getParameter("productName");
String productDesc = request.getParameter("productDesc");
String productUnit = request.getParameter("productUnit");
String productCount = request.getParameter("productCount");
String totalPrice = request.getParameter("totalPrice");
String providerId = request.getParameter("providerId");
String isPayment = request.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) request.getSession().getAttribute(Constants.USER_SESSION)).getId());
bill.setModifyDate(new Date());
boolean flag = false;
BillService billService = new BillServiceImpl();
flag = billService.modify(bill);
if (flag) {
response.sendRedirect(request.getContextPath() + "/jsp/bill.do?method=query");
} else {
request.getRequestDispatcher("billmodify.jsp").forward(request, response);
}
}
private void delBill(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("billid");
HashMap<String, String> resultMap = new HashMap<String, String>();
if (!StringUtils.isNullOrEmpty(id)) {
BillService billService = new BillServiceImpl();
boolean flag = billService.deleteBillById(id);
if (flag) {//删除成功
resultMap.put("delResult", "true");
} else {//删除失败
resultMap.put("delResult", "false");
}
} else {
resultMap.put("delResult", "notexit");
}
//把resultMap转换成json对象输出
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();
outPrintWriter.close();
}
private void add(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String billCode = request.getParameter("billCode");
String productName = request.getParameter("productName");
String productDesc = request.getParameter("productDesc");
String productUnit = request.getParameter("productUnit");
String productCount = request.getParameter("productCount");
String totalPrice = request.getParameter("totalPrice");
String providerId = request.getParameter("providerId");
String isPayment = request.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) request.getSession().getAttribute(Constants.USER_SESSION)).getId());
bill.setCreationDate(new Date());
boolean flag = false;
BillService billService = new BillServiceImpl();
flag = billService.add(bill);
System.out.println("add flag -- > " + flag);
if (flag) {
response.sendRedirect(request.getContextPath() + "/jsp/bill.do?method=query");
} else {
request.getRequestDispatcher("billadd.jsp").forward(request, response);
}
}
private void query(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Provider> providerList = new ArrayList<Provider>();
ProviderService providerService = new ProviderServiceImpl();
providerList = providerService.getProviderList("", "");
request.setAttribute("providerList", providerList);
String queryProductName = request.getParameter("queryProductName");
String queryProviderId = request.getParameter("queryProviderId");
String queryIsPayment = request.getParameter("queryIsPayment");
if (StringUtils.isNullOrEmpty(queryProductName)) {
queryProductName = "";
}
List<Bill> billList = new ArrayList<Bill>();
BillService billService = new BillServiceImpl();
Bill bill = new Bill();
if (StringUtils.isNullOrEmpty(queryIsPayment)) {
bill.setIsPayment(0);
} else {
bill.setIsPayment(Integer.parseInt(queryIsPayment));
}
if (StringUtils.isNullOrEmpty(queryProviderId)) {
bill.setProviderId(0);
} else {
bill.setProviderId(Integer.parseInt(queryProviderId));
}
bill.setProductName(queryProductName);
billList = billService.getBillList(bill);
request.setAttribute("billList", billList);
request.setAttribute("queryProductName", queryProductName);
request.setAttribute("queryProviderId", queryProviderId);
request.setAttribute("queryIsPayment", queryIsPayment);
request.getRequestDispatcher("billlist.jsp").forward(request, response);
}
public static void main(String[] args) {
System.out.println(new BigDecimal("23.235").setScale(2, BigDecimal.ROUND_HALF_DOWN));
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
@Override
public void init() throws ServletException {
// Put your code here
}
}
在完成这个项目期间出现了很多问题,也找错找了很长时间,幸运的是我最后还是找到了错误