SMBMS项目
一、前提准备
1、导入SQL
2、创建普通Maven项目
3、加入web支持
4、配置Tomcat
5、导入相关的包
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring基础包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<!-- springMVC相关包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<!-- springMVC相关包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<!-- springMVC相关包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<!-- springMVC相关包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.1</version>
</dependency>
<!-- 添加mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- 添加mybatis/spring整合包依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 添加mysql驱动依赖 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.5.0</version>
</dependency>
<!-- 添加日志相关jar包 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.5.Final</version>
</dependency>
<!-- 文件上传所需的包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jsp-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
6、将包导入Artifacts
二、导入静态资源
Jsp、Html、Js、css、image等
三、配置项目环境
1、通过web.xml配置DispatcherServlet和乱码过滤器
<!-- 配置DispatcherDervlet前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置DispatcherServlet的一个初始化参数:配置SpringMVC配置文件的位置和名称 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 解决post乱码问题的过滤器 放在过滤器最前面-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2、编写db.properties和mybatis配置文件
db.properties
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=gbk&serverTimezone=GMT%2B8
mysql.name=root
mysql.password=password
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 这个配置使全局的映射器启用或禁用二级缓存-->
<setting name="cacheEnabled" value="true" />
<setting name="logImpl" value="LOG4J"/>
<!-- 指定 MyBatis 如何自动映射列到属性:
PARTIAL 只会自动映射简单, 没有嵌套的结果。
FULL 会自动映射任意复杂的结果(嵌套的或其他情况) -->
<setting name="autoMappingBehavior" value="FULL" />
<!--设置超时时间, 它决定驱动等待一个数据库响应的时间 -->
<setting name="defaultStatementTimeout" value="25" />
<!--是否开启自动驼峰命名规则映射,即从经典数据库列名A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。 默认false -->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
<!-- 开启别名 -->
<typeAliases>
<package name="com.dong.pojo"/>
</typeAliases>
<!-- 配制分页插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
<!-- sql映射文件注册 -->
<mappers>
<package name="com.dong.dao"/>
</mappers>
</configuration>
log4j.properties
log4j.rootLogger=DEBUG,Console
log4j.logger.org.springframework=INFO
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache.ibatis=INFO
log4j.logger.org.mybatis.spring=INFO
3、配置applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 组件扫描 -->
<context:component-scan base-package="com.dong"/>
<!-- 引入数据库参数文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配制数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${mysql.driver}"></property>
<property name="url" value="${mysql.url}"></property>
<property name="username" value="${mysql.name}"></property>
<property name="password" value="${mysql.password}"></property>
<!-- 初始化连接数 -->
<property name="initialSize" value="30"/>
<!-- 最大连接数 -->
<property name="maxOpenPreparedStatements" value="150"/>
<!-- 最小空闲连接 -->
<property name="minIdle" value="10"/>
<!-- 最大空闲连接 -->
<property name="maxIdle" value="30"/>
<!-- 等待超时时间单位毫秒 -->
<property name="maxWaitMillis" value="500"/>
</bean>
<!-- 配制会话工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 引入mybatis配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<!-- 配制数据映射器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 为映射器接口文件设置基本的包路径。 你可以使用分号或逗号 作为分隔符设置多于一个的包路径。 -->
<property name="basePackage" value="com.dong.dao"/>
</bean>
<!--配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 声明使用注解式事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 处理静态资源 -->
<mvc:default-servlet-handler/>
<!-- mvc的注解驱动 -->
<mvc:annotation-driven>
<!-- 处理异步请求json数据乱码 -->
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="defaultCharset" value="utf-8"></property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 配置视图解释器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 过滤器 -->
<!-- 页面跳转 -->
<mvc:view-controller path="user/frame" view-name="frame"/>
<mvc:view-controller path="user/pwdModify" view-name="pwdmodify"/>
</beans>
四、写工具类
这里写了一个工具类,用来封装数据
ResultData.class
public class ResultData {
private String msg;
private Integer flag;
private Object data;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Integer getFlag() {
return flag;
}
public void setFlag(Integer flag) {
this.flag = flag;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return "ResultData{" +
"msg='" + msg + '\'' +
", flag=" + flag +
", data=" + data +
'}';
}
}
五、为每个表创建对应的实体类
我在实体类中使用了Lombok插件,如果不使用插件的话可以使用set和get方法代替@Data
表smbms_address对应的实体类
@Data
public class Address {
private Long id;
private String contact;
private String addressDesc;
private String postCode;
private String tel;
private Long createdBy;
private Date creationDate;
private Long modifyBy;
private Date modifyDate;
private Long userId;
}
表smbms_bill对应的实体类
这里的BigDecimal功能和double,float效果类似,但更精确
@Data
public class Bill {
private Long id;
private String billCode;
private String productName;
private String productDesc;
private String productUnit;
private BigDecimal productCount;
private BigDecimal totalPrice;
private Integer isPayment;
private Long createdBy;
private Date creationDate;
private Long modifyBy;
private Date modifyDate;
private Integer providerId;
}
表smbms_provider对应的实体类
@Data
public class Provider {
private Long id;
private String proCode;
private String proName;
private String proDesc;
private String proContact;
private String proPhone;
private String proAddress;
private String proFax;
private Long createdBy;
private Date creationDate;
private Date modifyDate;
private Long modifyBy;
}
表smbms_role对应的实体类
@Data
public class Role {
private Long id;
private String roleCode;
private String roleName;
private Long createdBy;
private Date creationDate;
private Long modifyBy;
private Date modifyDate;
}
表smbms_user对应的实体类
这里使用@DateTimeFormat( )注解格式化日期
@Data
public class User {
private Long id;
private String userCode;
private String userName;
private String userPassword;
private Integer gender;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birthday;
private String phone;
private String address;
private Integer userRole;
private Long createdBy;
private Date creationDate;
private Long modifyBy;
private Date modifyDate;
}
六、完成登录功能
1、视图层
使用了Ajax实现发送post请求
$(function(){
$("#login").click(function(){
var userCode = $("#userCode").val();
var password = $("#userPassword").val();
//以post发送请求
$.post(
//发送数据的url
"user/gologin",
//请求携带的数据data
{"userCode":userCode,"password":password},
//运行成功后,执行的方法result为后台返回的数据
function(result){
//这里根据控制器层返回的JSON对象进行判断
if(result != null){
if(result.flag==0){
//登录成功
//保存用户名称到cookie,以便自动登录系统
var date = new Date();
//获取过期时间(单位:毫秒)
date.setTime(date.getTime()+parseInt($("#time").val())*1000);
//保存cookie信息
$.cookie("usercode",result.data.userCode,{expires:date,path:"/"});
//跳转到首页
location.href="user/frame";
}else{ //登录失败
//显示失败信息
$(".info").html(result.msg);
}
}
},"json");
})
})
2、持久化层
(DAO层)(这里使用了注解直接进行查询,没有创建对应的Mapper.xml文件)
public interface UserMapper {
@Select("select * from smbms_user where userCode = #{userCode}")
User SelectByUserCode(String userCode);
}
(Service层)(在这里对账号密码进行判断,并将结果封装到工具类中返回)
public interface UserService {
ResultData SelectByUserCode(String userCode,String password);
}
@Service
@Transactional//注解开启事务
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
public ResultData SelectByUserCode(String userCode,String password) {
User user = userMapper.SelectByUserCode(userCode);
ResultData rd = new ResultData();
if (user==null){
rd.setMsg("用户编码错误!");
rd.setFlag(2);
return rd;
}
if (!password.equals(user.getUserPassword())){
rd.setMsg("用户密码错误!");
rd.setFlag(1);
return rd;
}
rd.setMsg("登录成功!");
rd.setFlag(0);
rd.setData(user);
return rd;
}
}
3、控制器层
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private HttpSession session;
@RequestMapping("/gologin")
@ResponseBody
public String goLogin(String userCode,String password){
ResultData rd = userService.SelectByUserCode(userCode, password);
//只有在用户名和密码都正确情况下,service层才会把user放入rd中的Data中
if(rd.getData()!=null){
//登录成功后将这次登录的信息保存在session中
session.setAttribute("user",rd.getData());
}
//这里测试下rd转化后的字符串
System.out.println(JSONObject.toJSONString(rd));
//将rd对象转化成JSON字符串传给前端
return JSONObject.toJSONString(rd);
}
}
七、配置拦截器实现自动登录
AutoLoginInterceptor.class
自定义拦截器,实现HandlerInterceptor接口
public class AutoLoginInterceptor implements HandlerInterceptor {
@Autowired
private UserMapper userMapper;
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//获得所有的Cookie信息
Cookie[] cookies = request.getCookies();
//非空判断
if(cookies!=null){
//遍历cookie
for(Cookie cookie:cookies){
//取出cookie中usercode字段对应的值
if("usercode".equals(cookie.getName())){
String userCode = cookie.getValue();
System.out.println(userCode);
//根据userCode查询信息
User user = userMapper.SelectByUserCode(userCode);
if (user!=null){
//getSession的参数为true 当找不到session时会自动创建
//getSession的参数为false 当找不到session时会直接返回null
request.getSession(true).setAttribute("user",user);
System.out.println(user);
response.sendRedirect(request.getContextPath()+"/user/frame");
return false;
}
}
}
}
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
在applicationContext.xml中配置拦截器
<!-- 拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/login.html"/>
<bean class="com.dong.interceptor.AutoLoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
八、实现退出功能
不需要与数据库进行交互,没有持久化层
1、视图层
<a href="javascript:if(confirm('您真的要退出吗?')){location.href='${pageContext.request.contextPath}/user/logout'}">退出</a>
<a href="javascript:if(confirm('您真的要退出吗?')){location.href='${pageContext.request.contextPath}/user/logout'}">退出系统</a>
2、控制器层
在UserController.class中继续写
@RequestMapping("/logout")
public String logout(HttpServletResponse response){
//删除session中的数据
session.removeAttribute("user");
//删除cookie中的数据
Cookie cookie = new Cookie("usercode", "-1");
//将cookie的生命周期设置为0 立即失效
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
return "redirect:/login.html";
}
九、实现密码修改
第一步:修改密码页面跳转
视图层
<a href="${pageContext.request.contextPath}/user/pwdModify">密码修改</a>
控制器层
@RequestMapping("/pwdModify")
public String goPwdModify(){
return "pwdmodify";
}
第二步:通过Ajax实现旧密码的校验
视图层
当旧密码框失去焦点时判断旧密码是否正确
$(function(){
$("#oldpassword").blur(function(){
var pwd = $(this).val();
var id = $("#userid").val();
$.post("${pageContext.request.contextPath }/user/isPwd",{"pwd":pwd,"id":id},function(result){
if(result.flag==0){
$("#oldpassword").next().html(result.msg).css("color","#0f0");
}else{
$("#oldpassword").next().html(result.msg).css("color","#f00");
}
},"json");
})
持久化层
UserMapper.class
User SelectById(Long id);
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dong.dao.UserMapper">
<!-- 保证数据库中的列名 和 java类中的字段名一致 -->
<resultMap id="BaseResultMap" type="user">
<id property="id" column="id"/>
<result property="userCode" column="userCode"/>
<result property="userName" column="userName"/>
<result property="userPassword" column="userPassword"/>
<result property="gender" column="gender"/>
<result property="birthday" column="birthday"/>
<result property="phone" column="phone"/>
<result property="address" column="address"/>
<result property="userRole" column="userRole"/>
<result property="createdBy" column="createdBy"/>
<result property="creationDate" column="creationDate"/>
<result property="modifyBy" column="modifyBy"/>
<result property="modifyDate" column="modifyDate"/>
</resultMap>
<!--数据库smbms_user表中的所有列名,用来代替* -->
<sql id="userList"> id,userCode,userName,userPassword,gender,birthday,phone,address,userRole,createdBy,creationDate,modifyBy,modifyDate
</sql>
<select id="SelectById" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<!--这里导入所有的列名,这里和使用*的功能一样 -->
<include refid="userList"></include>
from smbms_user where id = #{id};
</select>
</mapper>
UserService.class
ResultData isPwd(Long id,String password);
UserServiceImpl.class
//验证旧密码
public ResultData isPwd(Long id,String password) {
User user = userMapper.SelectById(id);
ResultData rd = new ResultData();
if (user!=null){
if(password.equals(user.getUserPassword())){
rd.setFlag(0);
rd.setMsg("密码正确");
}else {
rd.setFlag(1);
rd.setMsg("密码错误");
}
}else {
rd.setFlag(2);
rd.setMsg("未知异常");
}
return rd;
}
控制器层
@RequestMapping("/isPwd")
@ResponseBody
public String isPwd(String pwd,Long id){
ResultData rd = userService.isPwd(id, pwd);
return JSONObject.toJSONString(rd);
}
第三步:使用前端对两次新密码校验
$("#rnewpassword").blur(function(){
var newpwd = $("#newpassword").val();
var rnewpwd = $("#rnewpassword").val();
if (newpwd != '' && rnewpwd != '') {
if (newpwd == rnewpwd) {
$("#rnewpassword").next().html("密码一致!").css("color","#0f0");
} else {
$("#rnewpassword").next().html("密码不一致!").css("color","#f00");
}
} else {
$("#rnewpassword").next().html("密码不能为空!").css("color","#f00");
}
})
})
第四步:实现密码修改
视图层
定义一个提交的函数
function save() {
var id = $("#userid").val();
var userpassword = $("#rnewpassword").val();
var newpwd = $("#newpassword").val();
var rnewpwd = $("#rnewpassword").val();
if (newpwd == rnewpwd) {
$.post("${pageContext.request.contextPath }/user/pwdupdate",{"userpassword":userpassword,"id":id},function(result){
if(result > 0){
alert("密码修改成功,请重新登录!");
location.href="${pageContext.request.contextPath }/login.html";
}else{
$(".info").next().html("修改失败").css("color","#f00");
}
},"json");
} else {
alert("密码不一致!请重新输入!");
}
}
实现提交
<input type="button" οnclick="save()" name="save" id="save" value="保存" class="input-button">
持久化层
UserMapper.class
@Update("update smbms_user set userPassword = #{pwd} where id = #{id}")
int UpdatePwd(@Param("id") Long id,@Param("pwd") String password);
UserService.class
int UpdatePwd(Long id,String password);
UserServiceImpl.class
//密码修改
public int UpdatePwd(Long id, String password) {
return userMapper.UpdatePwd(id, password);
}
控制器层
@RequestMapping("/pwdupdate")
@ResponseBody
public String updatePwd(String userpassword,Long id){
int i = userService.UpdatePwd(id, userpassword);
return JSONObject.toJSONString(i);
}
十、实现用户管理的检索功能
1、这里的分页功能使用了Mybatis的PageHelper实现要配置插件
带入依赖jar包(之前已经导过了)
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.4</version>
</dependency>
在mybatis-config.xml中配置插件(之前已经配置好了)
<!-- 配制分页插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
PageInfo的参数
当前页
private int pageNum;
每页的数量
private int pageSize;
当前页的数量
private int size;
//由于startRow和endRow不常用,这里说个具体的用法
//可以在页面中"显示startRow到endRow 共size条数据"
当前页面第一个元素在数据库中的行号
private int startRow;
当前页面最后一个元素在数据库中的行号
private int endRow;
总记录数
private long total;
总页数
private int pages;
结果集
private List<T> list;
第一页
private int firstPage;
前一页
private int prePage;
是否为第一页
private boolean isFirstPage = false;
是否为最后一页
private boolean isLastPage = false;
是否有前一页
private boolean hasPreviousPage = false;
是否有下一页
private boolean hasNextPage = false;
导航页码数
private int navigatePages;
所有导航页号
private int[] navigatepageNums;
2、这里需要建立一个对应页面显示的POJO类
页面数据显示,大部分都是user类中的,只多了一项roleName
@Data
public class UserRole extends User {
private String roleName;
}
3、持久化层
DAO层不需要考虑分页问题,按照所有数据进行查询
这里新建一个接口RoleMapper.class,用来实现检索条件中下拉列表数据的查询
public interface RoleMapper {
@Select("select roleName from smbms_role")
List<String> SelectRoleNameAll();
}
UserMapper.class
List<UserRole> SelectAllBypage(@Param("username") String username,@Param("rolename") String rolename);
UserMapper.xml
<!--实现UserRole类中的字段和数据库字段一一对应-->
<resultMap id="UserRoleResultMap" type="userRole">
<id property="id" column="id"/>
<result property="userCode" column="userCode"/>
<result property="userName" column="userName"/>
<result property="userPassword" column="userPassword"/>
<result property="gender" column="gender"/>
<result property="birthday" column="birthday"/>
<result property="phone" column="phone"/>
<result property="address" column="address"/>
<result property="userRole" column="userRole"/>
<result property="createdBy" column="createdBy"/>
<result property="creationDate" column="creationDate"/>
<result property="modifyBy" column="modifyBy"/>
<result property="modifyDate" column="modifyDate"/>
<result property="roleName" column="roleName"/>
</resultMap>
<!--利用if判断字段是否为空,实现动态SQL-->
<select id="SelectAllBypage" resultMap="UserRoleResultMap">
select u.*,r.roleName from smbms_user u,smbms_role r where u.userRole=r.id
<if test="username!=''">
and userName like concat('%',#{username},'%')
</if>
<if test="rolename!=''">
and roleName = #{rolename}
</if>
</select>
Service层
//查询检索信息
PageInfo getUserListPage(String username,String rolename,Integer n, Integer pageSize);
//查询下拉列表的数据
List<String> getRoleName();
//检索查询
public PageInfo getUserListPage(String username, String rolename, Integer n, Integer pageSize) {
//这里使用插件实现分页,查询语句必须紧跟PageHelper.startPage(n,pageSize);写才有效
PageHelper.startPage(n,pageSize);
List<UserRole> userRoles = userMapper.SelectAllBypage(username, rolename);
PageInfo<UserRole> pageInfo = new PageInfo<UserRole>(userRoles,3);
return pageInfo;
}
//查询角色名称列表
public List<String> getRoleName() {
return roleMapper.SelectRoleNameAll();
}
4、控制器层
/*
*Model对象:通过给方法添加引用Model对象入参,直接往Model对象添加属性值。那么哪些类型的入参才能够引用Model对象,
* 有三种类型,分别是
* org.springframework.ui.Model、
* org.springframework.ui.ModelMap
* java.uti.Map。
* 只要是这些类型的入参,都是指向Model对象的,而且不管定义多少个这些类型的入参都是指向同一个Model对象!
* */
//这里的参数Map和Model一个作用
//这里的n是查询的页数,默认查询第一页
//这里的pagesize是每页数据的条数,默认一页五条
@RequestMapping("/userlist")
public String goUserList(
@RequestParam(value = "username",defaultValue = "")String username,
@RequestParam(value = "rolename",defaultValue = "") String rolename,
@RequestParam(value = "n",defaultValue = "1") Integer n,
@RequestParam(value = "pagesize",defaultValue = "5") Integer pagesize,Map<String,Object> map){
PageInfo pageinfo = userService.getUserListPage(username, rolename, n, pagesize);
List<String> roleName = userService.getRoleName();
map.put("pageInfo",pageinfo);
map.put("roleNames",roleName);
//下面两条用来做检索数据回显
map.put("username",username);
map.put("rolename",rolename);
return "userlist";
}
5、视图层
<%--使用EL表达式实现数据回显--%>
<input name="username" class="input-text" type="text" value="${username}">
<select name="rolename">
<option value="">--请选择--</option>
<%--Jstl对角色名称进行遍历显示--%>
<%--${rolename==rname}这里判断哪一条是回显数据,令回显的先设置为selected默认选择--%>
<c:forEach items="${roleNames}" var="rname">
<option value="${rname}" <c:if test="${rolename==rname}">selected</c:if>>${rname}</option>
</c:forEach>
</select>
<%--Jstl对用户信息进行遍历显示--%>
<c:forEach items="${pageInfo.list}" var="ur">
<tr>
<td>
<span>${ur.userCode}</span>
</td>
<td>
<span>${ur.userName}</span>
</td>
<td>
<span>${ur.roleName }</span>
</td>
<td>
<span>${ur.gender==1?"男":"女" }</span>
</td>
<td>
<span><f:formatDate value="${ur.birthday}" pattern="yyyy-MM-dd"/></span>
</td>
<td>
<span>${ur.phone}</span>
</td>
<td>
<span><a class="viewUser" href="${pageContext.request.contextPath }/user/userview?id=${ur.id}"><img src="${pageContext.request.contextPath }/images/read.png" alt="查看" title="查看"/></a></span>
<span><a class="modifyUser" href="${pageContext.request.contextPath }/user/usermodify?id=${ur.id}&flag=update"><img src="${pageContext.request.contextPath }/images/xiugai.png" alt="修改" title="修改"/></a></span>
<span><a class="deleteUser" href="${pageContext.request.contextPath }/user/userdel?id=${ur.id}"><img src="${pageContext.request.contextPath }/images/schu.png" alt="删除" title="删除"/></a></span>
</td>
</tr>
</c:forEach>
<%--这里翻页相关的,总记录条数,页数,上一页下一页等--%>
<ul class="page-num-ul clearfix">
<li>共${pageInfo.total}条记录 ${pageInfo.pageNum}/${pageInfo.pages}页</li>
<a href="${pageContext.request.contextPath }/user/userlist?n=${pageInfo.firstPage}&username=${username}&rolename=${rolename}">首页</a>
<a href="${pageContext.request.contextPath }/user/userlist?n=${pageInfo.prePage<1?1:pageInfo.prePage}&username=${username}&rolename=${rolename}">上一页</a>
<c:forEach items="${pageInfo.navigatepageNums}" var="num">
<a href="${pageContext.request.contextPath }/user/userlist?n=${num}&username=${username}&rolename=${rolename}">${num}</a>
</c:forEach>
<a href="${pageContext.request.contextPath }/user/userlist?n=${pageInfo.nextPage==0?pageInfo.pages:pageInfo.nextPage}&username=${username}&rolename=${rolename}">下一页</a>
<a href="${pageContext.request.contextPath }/user/userlist?n=${pageInfo.lastPage}&username=${username}&rolename=${rolename}">最后一页</a>
</ul>
十一、实现用户管理的用户添加
一、添加页面跳转
1、视图层
<a href="${pageContext.request.contextPath }/user/useradd">添加用户</a>
2、持久化层
RoleMapper.class(查询添加页面中的下来列表信息)
@Select("select id,roleName from smbms_role")
List<Role> SelectRoleNameAndId();
UserService.class
List<Role> getRoleNameAndId();
UserServiceImpl.class
//查询角色名称和id
public List<Role> getRoleNameAndId(){
return roleMapper.SelectRoleNameAndId();
}
3、控制器层
@RequestMapping("/useradd")
public String toUserAdd(Map<String,Object> map){
List<Role> roles = userService.getRoleNameAndId();
map.put("roles",roles);
return "useradd";
}
二、实现添加功能
1、视图层
$(function () {
$("#ruserPassword").blur(
function () {
var pwd = $("#userPassword").val();
var rpwd = $("#ruserPassword").val();
if(pwd!=""&&rpwd!=""){
if (pwd==rpwd){
$("#ruserPassword").next().html("密码一致").css("color","#0f0")
}else {
$("#ruserPassword").next().html("密码不一致").css("color","#f00")
}
}else {
$("#ruserPassword").next().html("密码不可为空").css("color","#f00")
}
}
)
})
<form id="userForm" name="userForm" method="post" action="${pageContext.request.contextPath }/user/add">
<div>
<label for="userCode">用户编码:</label>
<input type="text" name="userCode" id="userCode" value="${addUser.userCode}">
<!-- 放置提示信息 -->
<font color="red"></font>
</div>
<div>
<label for="userName">用户名称:</label>
<input type="text" name="userName" id="userName" value="${addUser.userName}">
<font color="red"></font>
</div>
<div>
<label for="userPassword">用户密码:</label>
<input type="password" name="userPassword" id="userPassword" value="${addUser.userPassword}">
<font color="red"></font>
</div>
<div>
<label for="ruserPassword">确认密码:</label>
<input type="password" name="ruserPassword" id="ruserPassword" value="${addUser.userPassword}">
<font color="red"></font>
</div>
<div>
<label >用户性别:</label>
<select name="gender" id="gender">
<option value="1" <c:if test="${addUser.gender==1}">selected</c:if>>男</option>
<option value="2" <c:if test="${addUser.gender==2}">selected</c:if>>女</option>
</select>
</div>
<div>
<%-- http://www.my97.net/demo/resource/3.asp--%>
<label for="birthday">出生日期:</label>
<input type="text" Class="Wdate" id="birthday" name="birthday"
readonly="readonly" οnclick="WdatePicker();">
<font color="red"></font>
</div>
<div>
<label for="phone">用户电话:</label>
<input type="text" name="phone" id="phone" value="${addUser.phone}">
<font color="red"></font>
</div>
<div>
<label for="address">用户地址:</label>
<input name="address" id="address" value="${addUser.address}">
</div>
<div>
<label >用户角色:</label>
<!-- 列出所有的角色分类 -->
<select name="userRole">
<option value="">--请选择--</option>
<c:forEach items="${roles}" var="roles">
<option value="${roles.id}" <c:if test="${addUser.userRole==roles.id}">selected</c:if>>${roles.roleName}</option>
</c:forEach>
</select>
</div>
<div class="providerAddBtn">
<input type="submit" name="add" id="add" value="保存" >
<input type="button" id="back" name="back" οnclick="javascript:window.history.back(-1);" value="返回"/>
</div>
</form>
2、持久层
UserMapper.class
int insertSelective(User record);
UserMapper.xml(使用动态SQL筛选非空的添加)
<insert id="insertSelective" parameterType="user">
insert into smbms_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id!=null">
id,
</if>
<if test="userCode != null" >
userCode,
</if>
<if test="userName != null" >
userName,
</if>
<if test="userPassword != null" >
userPassword,
</if>
<if test="gender != null" >
gender,
</if>
<if test="birthday != null" >
birthday,
</if>
<if test="phone != null" >
phone,
</if>
<if test="address != null" >
address,
</if>
<if test="userRole != null" >
userRole,
</if>
<if test="createdBy != null" >
createdBy,
</if>
<if test="creationDate != null" >
creationDate,
</if>
<if test="modifyBy != null" >
modifyBy,
</if>
<if test="modifyDate != null" >
modifyDate,
</if>
</trim>
<trim prefix="values(" suffix=")" suffixOverrides=",">
<if test="id != null" >
#{id},
</if>
<if test="userCode != null" >
#{userCode},
</if>
<if test="userName != null" >
#{userName},
</if>
<if test="userPassword != null" >
#{userPassword},
</if>
<if test="gender != null" >
#{gender},
</if>
<if test="birthday != null" >
#{birthday},
</if>
<if test="phone != null" >
#{phone},
</if>
<if test="address != null" >
#{address},
</if>
<if test="userRole != null" >
#{userRole},
</if>
<if test="createdBy != null" >
#{createdBy},
</if>
<if test="creationDate != null" >
#{creationDate},
</if>
<if test="modifyBy != null" >
#{modifyBy},
</if>
<if test="modifyDate != null" >
#{modifyDate},
</if>
</trim>
</insert>
UserService.class
int userAdd(User user);
UserServiceImpl.class
//添加用户
public int userAdd(User user) {
return userMapper.insertSelective(user);
}
3、控制器层
(简单做了一个数据回显,这里很难出现错误,因为数据库中的字段除了自增ID其他都可以为空)
@RequestMapping("/add")
public String addUser(User user,Map<String, Object> map){
int a = 0;
//指定创建时间
user.setCreationDate(new Date());
//指定修改人
User onlineUser = (User) session.getAttribute("user");
if(onlineUser!=null){
System.out.println(user.getId());
user.setCreatedBy(onlineUser.getId());
a = userService.userAdd(user);
}
if(a<1){
map.put("addUser",user);
return "forward:useradd";
}
return "forward:userlist";
}
十二、实现用户管理的详细信息
1、视图层
用来跳转的链接
<a class="viewUser" href="${pageContext.request.contextPath }/user/userview?id=${ur.id}"><img src="${pageContext.request.contextPath }/images/read.png" alt="查看" title="查看"/></a>
用来接受数据的前端
<f:formatDate value="" pattern=“yyyy-MM-dd”/>可以将数据库中Date数据格式化并展示,前提引入标签库<%@taglib prefix=“f” uri=“http://java.sun.com/jsp/jstl/fmt” %>
<div class="providerView">
<input type="hidden" id="uid" value="${userRole.id}" />
<p><strong>用户名称:</strong><span>${userRole.userName}</span></p>
<p><strong>用户性别:</strong><span>${userRole.gender==1?'男':'女'}</span></p>
<p><strong>出生日期:</strong><span><f:formatDate value="${userRole.birthday}" pattern="yyyy-MM-dd"/></span></p>
<p><strong>用户电话:</strong><span>${userRole.phone}</span></p>
<p><strong>用户地址:</strong><span>${userRole.address}</span></p>
<p><strong>用户角色:</strong><span>${userRole.roleName}</span></p>
</div>
2、持久层
UserMapper.class
UserRole SelectByUserId(@Param("id") Long id);
UserMapper.xml
<select id="SelectByUserId" parameterType="java.lang.Long" resultMap="UserRoleResultMap">
select u.*,r.roleName from smbms_user u,smbms_role r where u.userRole=r.id and u.id = #{id}
</select>
UserService.class
UserRole SelectByUserId(Long id);
UserServiceImpl
//根据id检索用户信息
public UserRole SelectByUserId(Long id) {
return userMapper.SelectByUserId(id);
}
3、控制器层
@GetMapping("/userview")
public String userview(Long id,Map<String,Object> map){
UserRole userRole = userService.SelectByUserId(id);
map.put("userRole",userRole);
return "userview";
}
十三、实现用户管理的修改功能
一、实现页面跳转及数据显示
1、视图层
<a class="modifyUser" href="${pageContext.request.contextPath }/user/usermodify?id=${ur.id}&flag=update"><img src="${pageContext.request.contextPath }/images/xiugai.png" alt="修改" title="修改"/></a>
2、持久层
UserMapper.class
(这个接口在修改密码时,对旧密码的查询时就已经写了,这里拿过来直接用)
User SelectById(Long id);
UserMapper.xml
(这个和接口一起写的,这里直接复用)
<select id="SelectById" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="userList"></include>
from smbms_user where id = #{id};
</select>
UserService.class
User getUserById(Long id);
UserServiceImpl.class
//根据id查询需要修改用户的信息
public User getUserById(Long id) {
return userMapper.SelectById(id);
}
3、控制器层
@GetMapping("/usermodify")
public String gousermodify() {
return "usermodify";
}
@ModelAttribute
public void ModelAttributeUpdate(Long id, String flag, Map<String, Object> map) {
if ("update".equals(flag)) {
User UpdateUser = userService.getUserById(id);
List<Role> roles = userService.getRoleNameAndId();
map.put("userUpdate", UpdateUser);
map.put("rnids", roles);
}
}
二、数据展示及修改数据
这里存在一个时区的问题,我在db.properties中更改了,加了8个时区,GMT%2B8
在GMT基础上加8个时区
1、视图层
这里用到了Spring的标签实现的数据展示(对我来说时新知识)
这里链接一个博客简单了解https://blog.youkuaiyun.com/qq_38198467/article/details/90602361
<s:form method="post" action="${pageContext.request.contextPath }/user/update" modelAttribute="userUpdate">
<s:hidden path="id"/>
<div>
<label for="userName">用户名称:</label>
<s:input path="userName"/>
<font color="red"></font>
</div>
<div>
<label >用户性别:</label>
<s:radiobutton path="gender" value="1"/>男
<s:radiobutton path="gender" value="2"/>女
</div>
<div>
<label>出生日期:</label>
<s:input path="birthday" cssClass="Wdate" readonly="true" οnclick="WdatePicker();"/>
<font color="red"></font>
</div>
<div>
<label >用户电话:</label>
<s:input path="phone"/>
<font color="red"></font>
</div>
<div>
<label >用户地址:</label>
<s:input path="address"/>
</div>
<div>
<label >用户角色:</label>
<!-- 列出所有的角色分类 -->
<s:select path="userRole" items="${rnids}" itemValue="id" itemLabel="roleName"></s:select>
<font color="red"></font>
</div>
<div class="providerAddBtn">
<input type="submit" name="save" id="save" value="保存" />
<input type="button" id="back" name="back" οnclick="javascript:window.history.back(-1);" value="返回"/>
</div>
</s:form>
2、持久化层
UserMapper.class
int UpdateUser(User record);
UserMapper.xml(简单的动态SQL)
<update id="UpdateUser" parameterType="user">
update smbms_user
<set>
<if test="userCode != null" >
userCode = #{userCode},
</if>
<if test="userName != null" >
userName = #{userName},
</if>
<if test="gender != null" >
gender = #{gender},
</if>
<if test="birthday != null" >
birthday = #{birthday},
</if>
<if test="phone != null" >
phone = #{phone},
</if>
<if test="address != null" >
address = #{address},
</if>
<if test="userRole != null" >
userRole= #{userRole},
</if>
<if test="createdBy != null" >
createdBy= #{createdBy},
</if>
<if test="creationDate != null" >
creationDate= #{creationDate},
</if>
<if test="modifyBy != null" >
modifyBy=#{modifyBy},
</if>
<if test="modifyDate != null" >
modifyDate= #{modifyDate},
</if>
</set>
where id =#{id}
</update>
UserService.class
int updateUser(User user);
UserServiceImpl.class
//修改用户信息
public int updateUser(User user) {
return userMapper.UpdateUser(user);
}
3、控制器层
@PostMapping("/update")
public String updateUser(User user,Map<String,Object> map){
int i =0;
user.setCreationDate(new Date());
User user1 = (User) session.getAttribute("user");
if(user1!=null){
user.setCreatedBy(user1.getId());
}
i = userService.updateUser(user);
if (i<1){
map.put("userUpdate",user);
return "forward:usermodify";
}
return "forward:userlist";
}
十四、实现用户管理的删除功能
1、视图层
<a class="deleteUser" href="javascript:if(confirm('您真的要删除吗?')){location.href='${pageContext.request.contextPath }/user/userdel?id=${ur.id}'}"><img src="${pageContext.request.contextPath }/images/schu.png" alt="删除" title="删除"/></a>
2、持久化层
UserMapper.class
int DeleteUserById(@Param("id") Long id);
UserMapper.xml
<delete id="DeleteUserById" parameterType="java.lang.Long">
delete from smbms_user where id= #{id};
</delete>
UserService.class
int deleteUserById(Long id);
UserServiceImpl.class
//删除用户信息
public int deleteUserById(Long id) {
return userMapper.DeleteUserById(id);
}
3、控制器层
@GetMapping("/userdel")
public String deleteUser(@RequestParam("id") Long id){
userService.deleteUserById(id);
return "forward:userlist";
}
十五、实现供应商管理的检索功能
1、视图层
(包括跳转和数据显示两部分)
跳转
<a href="${pageContext.request.contextPath}/provider/providerlist">供应商管理</a>
数据检索条件
<div class="search">
<form method="get" action="${pageContext.request.contextPath }/provider/providerlist">
<!-- <input name="method" value="query" type="hidden"> -->
<span>供应商联系人:</span>
<input name="proContact" type="text" value="${proContact}">
<span>供应商名称:</span>
<input name="proName" type="text" value="${proName}">
<input value="查 询" type="submit" id="searchbutton">
<a href="${pageContext.request.contextPath }/provider/provideradd">添加供应商</a>
</form>
</div>
数据显示
<c:forEach items="${pageInfo.list}" var="pr">
<tr>
<td>
<span>${pr.proCode}</span>
</td>
<td>
<span>${pr.proName}</span>
</td>
<td>
<span>${pr.proContact}</span>
</td>
<td>
<span>${pr.proPhone}</span>
</td>
<td>
<span>${pr.proFax}</span>
</td>
<td>
<span>
${pr.proAddress}
</span>
</td>
<td>
<span><f:formatDate value="${pr.creationDate}" pattern="yyyy-MM-dd"/></span>
</td>
<td>
<span><a class="viewProvider" href="${pageContext.request.contextPath }/provider/providerview?id=${pr.id}&flag=update"><img src="${pageContext.request.contextPath }/images/read.png" alt="查看" title="查看"/></a></span>
<span><a class="modifyProvider" href="${pageContext.request.contextPath }/provider/providermodify?id=${pr.id}&flag=update"><img src="${pageContext.request.contextPath }/images/xiugai.png" alt="修改" title="修改"/></a></span>
<span><a class="deleteProvider" href="${pageContext.request.contextPath }/provider/providerdel?id=${pr.id}"><img src="${pageContext.request.contextPath }/images/schu.png" alt="删除" title="删除"/></a></span>
</td>
</tr>
</c:forEach>
翻页系统
<ul class="page-num-ul clearfix">
<li>共${pageInfo.total}条记录 ${pageInfo.pageNum}/${pageInfo.pages}页</li>
<a href="${pageContext.request.contextPath }/provider/providerlist?proContact=${proContact}&proName=${proName}">首页</a>
<a href="${pageContext.request.contextPath }/provider/providerlist?n=${pageInfo.prePage<1?1:pageInfo.prePage}&proContact=${proContact}&proName=${proName}">上一页</a>
<c:forEach items="${pageInfo.navigatepageNums}" var="num">
<a href="${pageContext.request.contextPath }/provider/providerlist?n=${num}&proContact=${proContact}&proName=${proName}">${num}</a>
</c:forEach>
<a href="${pageContext.request.contextPath }/provider/providerlist?n=${pageInfo.nextPage<1?pageInfo.pages:pageInfo.nextPage}&proContact=${proContact}&proName=${proName}">下一页</a>
<a href="${pageContext.request.contextPath }/provider/providerlist?n=${pageInfo.lastPage}&proContact=${proContact}&proName=${proName}">最后一页</a>
</ul>
2、持久层
ProviderMapper.java
public interface ProviderMapper {
List<Provider> SelectProviderListPage(@Param("proContact") String proContact,@Param("proName") String proName);
}
ProviderMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dong.dao.ProviderMapper">
<resultMap id="BaseResultMap" type="provider">
<id property="id" column="id"/>
<result property="proCode" column="proCode"/>
<result property="proName" column="proName"/>
<result property="proDesc" column="proDesc"/>
<result property="proContact" column="proContact"/>
<result property="proPhone" column="proPhone"/>
<result property="proAddress" column="proAddress"/>
<result property="proFax" column="proFax"/>
<result property="createdBy" column="createdBy"/>
<result property="creationDate" column="creationDate"/>
<result property="modifyDate" column="modifyDate"/>
<result property="modifyBy" column="modifyBy"/>
</resultMap>
<sql id="Base_Column_List">
id, proCode, proName, proDesc, proContact, proPhone, proAddress, proFax, createdBy,
creationDate, modifyDate, modifyBy
</sql>
<select id="SelectProviderListPage" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"></include>
from smbms_provider
<where>
<if test="proContact!=''">
and proContact like concat('%',#{proContact},'%')
</if>
<if test="proName!=''">
and proName like concat('%',#{proName},'%')
</if>
</where>
</select>
</mapper>
ProviderService.class
public interface ProviderService {
PageInfo SelectProviderListPage(String proName, String proContact, Integer n, Integer pageSize);
}
ProviderServiceImpl.class
@Service
@Transactional
public class ProviderServiceImpl implements ProviderService {
@Autowired
private ProviderMapper providerMapper;
public PageInfo SelectProviderListPage(String proName, String proContact, Integer n, Integer pageSize) {
PageHelper.startPage(n,pageSize);
List<Provider> providers = providerMapper.SelectProviderListPage(proContact, proName);
PageInfo<Provider> pageInfo = new PageInfo<Provider>(providers);
return pageInfo;
}
}
3、控制器层
@Controller
@RequestMapping("/provider")
public class ProviderController {
@Autowired
private ProviderService providerService;
//session域对象
@Autowired
private HttpSession session;
@RequestMapping("/providerlist")
public String goProviderlist(@RequestParam(value = "proContact",defaultValue = "") String proContact,
@RequestParam(value = "proName",defaultValue = "")String proName,
@RequestParam(value = "n",defaultValue = "1") Integer n,
@RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize,
Map<String,Object> map){
PageInfo pageInfo = providerService.SelectProviderListPage(proName, proContact, n, pageSize);
map.put("pageInfo",pageInfo);
map.put("proContact",proContact);
map.put("proName",proName);
return "providerlist";
}
}
十六、实现供应商管理的添加功能
1、视图层
跳转
<a href="${pageContext.request.contextPath }/provider/provideradd">添加供应商</a>
输入数据
<form id="providerForm" name="providerForm" method="post" action="${pageContext.request.contextPath }/provider/add">
<div class="">
<label for="procode">供应商编码:</label>
<input type="text" name="proCode" id="procode" value="${provideradd.proCode}">
<font color="red"></font>
</div>
<div>
<label for="proname">供应商名称:</label>
<input type="text" name="proName" id="proname" value="${provideradd.proName}">
<font color="red"></font>
</div>
<div>
<label for="procontact">联系人:</label>
<input type="text" name="proContact" id="procontact" value="${provideradd.proContact}">
<font color="red"></font>
</div>
<div>
<label for="prophone">联系电话:</label>
<input type="text" name="proPhone" id="prophone" value="${provideradd.proPhone}">
<font color="red"></font>
</div>
<div>
<label for="proaddress">联系地址:</label>
<input type="text" name="proAddress" id="proaddress" value="${provideradd.proAddress}">
</div>
<div>
<label for="profax">传真:</label>
<input type="text" name="proFax" id="profax" value="${provideradd.proFax}">
</div>
<div>
<label for="prodesc">描述:</label>
<input type="text" name="proDesc" id="proDesc" value="${provideradd.proDesc}">
</div>
<div class="providerAddBtn">
<input type="submit" name="add" id="add" value="保存">
<input type="button" id="back" name="back" οnclick="javascript:window.history.back(-1);" value="返回"/>
</div>
</form>
2、持久化层
ProviderMapper.class
int InsertProvider(Provider provider);
ProviderMapper.xml
<insert id="InsertProvider" parameterType="provider">
insert into smbms_provider
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id!=null">
id,
</if>
<if test="proCode!=null">
proCode,
</if>
<if test="proName!=null">
proName,
</if>
<if test="proDesc!=null">
proDesc,
</if>
<if test="proContact!=null">
proContact,
</if>
<if test="proPhone!=null">
proPhone,
</if>
<if test="proAddress!=null">
proAddress,
</if>
<if test="proFax!=null">
proFax,
</if>
<if test="createdBy!=null">
createdBy,
</if>
<if test="creationDate!=null">
creationDate,
</if>
<if test="modifyDate!=null">
modifyDate,
</if>
<if test="modifyBy!=null">
modifyBy,
</if>
</trim>
<trim prefix="values(" suffix=")" suffixOverrides=",">
<if test="id!=null">
#{id},
</if>
<if test="proCode!=null">
#{proCode},
</if>
<if test="proName!=null">
#{proName},
</if>
<if test="proDesc!=null">
#{proDesc},
</if>
<if test="proContact!=null">
#{proContact},
</if>
<if test="proPhone!=null">
#{proPhone},
</if>
<if test="proAddress!=null">
#{proAddress},
</if>
<if test="proFax!=null">
#{proFax},
</if>
<if test="createdBy!=null">
#{createdBy},
</if>
<if test="creationDate!=null">
#{creationDate},
</if>
<if test="modifyDate!=null">
#{modifyDate},
</if>
<if test="modifyBy!=null">
#{modifyBy},
</if>
</trim>
</insert>
3、控制器层
//页面跳转
@RequestMapping("/provideradd")
public String goprovideradd(){
return "provideradd";
}
//添加
@RequestMapping("/add")
public String addProvider(Provider provider,Map<String,Object> map){
int i =0;
provider.setCreationDate(new Date());
User user = (User) session.getAttribute("user");
if (user!=null){
provider.setCreatedBy(user.getId());
}
i = providerService.InsertProvider(provider);
if(i<1){
map.put("provideradd",provider);
return "redirect:provideradd";
}
return "redirect:providerlist";
}
十七、实现供应商管理的详细信息
1、试图层
跳转
<a class="viewProvider" href="${pageContext.request.contextPath }/provider/providerview?id=${pr.id}"><img src="${pageContext.request.contextPath }/images/read.png" alt="查看" title="查看"/></a>
数据显示
<div class="providerView">
<input type="hidden" id="id" value="${viewprovider.id}" />
<p><strong>供应商编码:</strong><span>${viewprovider.proCode}</span></p>
<p><strong>供应商名称:</strong><span>${viewprovider.proName}</span></p>
<p><strong>联系人:</strong><span>${viewprovider.proContact}</span></p>
<p><strong>联系电话:</strong><span>${viewprovider.proPhone}</span></p>
<p><strong>传真:</strong><span>${viewprovider.proFax}</span></p>
<p><strong>描述:</strong><span>${viewprovider.proDesc}</span></p>
<div class="providerAddBtn">
<input type="button" id="back" name="back" οnclick="javascript:window.history.back(-1);" value="返回"/>
</div>
</div>
2、持久化层
ProviderMapper.class
Provider SelectProviderById(@Param("id") Long id);
ProviderMapper.xml
<select id="SelectProviderById" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"></include>
from smbms_provider where id = #{id};
</select>
ProviderService.java
Provider SelectProviderById(Long id);
ProviderServiceImpl.java
public Provider SelectProviderById(Long id) {
return providerMapper.SelectProviderById(id);
}
3、控制器层
@RequestMapping("/providerview")
public String providerview(Long id,Map<String,Object> map){
Provider provider = providerService.SelectProviderById(id);
map.put("viewprovider",provider);
return "providerview";
}
十八、实现供应商管理的修改功能
一、实现页面跳转和数据查询
1、视图层
<a class="modifyProvider" href="${pageContext.request.contextPath }/provider/providermodify?id=${pr.id}&flag=update"><img src="${pageContext.request.contextPath }/images/xiugai.png" alt="修改" title="修改"/></a>
2、持久化层
这里的持久化层直接使用了十七里的根据Id查询的持久化层
Provider SelectProviderById(@Param("id") Long id);
<select id="SelectProviderById" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"></include>
from smbms_provider where id = #{id};
</select>
Provider SelectProviderById(Long id);
public Provider SelectProviderById(Long id) {
return providerMapper.SelectProviderById(id);
}
3、控制器层
@GetMapping("/providermodify")
public String goprovidermodify(){
return "providermodify";
}
@ModelAttribute
public void ModelAttributeProvider(Long id,String flag,Map<String,Object> map){
if("update".equals(flag)){
Provider provider = providerService.SelectProviderById(id);
map.put("updateProvider",provider);
}
}
二、数据展示和修改功能
1、视图层
<s:form id="providerForm" name="providerForm" method="post" action="${pageContext.request.contextPath }/provider/update" modelAttribute="updateProvider">
<s:hidden path="id"/>
<div>
<label for="proCode">供应商编码:</label>
<s:input path="proCode"/>
</div>
<div>
<label for="proName">供应商名称:</label>
<s:input path="proName"/>
<font color="red"></font>
</div>
<div>
<label for="proContact">联系人:</label>
<s:input path="proContact"/>
<font color="red"></font>
</div>
<div>
<label for="proPhone">联系电话:</label>
<s:input path="proPhone"/>
<font color="red"></font>
</div>
<div>
<label for="proAddress">联系地址:</label>
<s:input path="proAddress"/>
</div>
<div>
<label for="proFax">传真:</label>
<s:input path="proFax"/>
</div>
<div>
<label for="proDesc">描述:</label>
<s:textarea path="proDesc"/>
</div>
<div class="providerAddBtn">
<input type="submit" name="save" id="save" value="保存">
<input type="button" id="back" name="back" οnclick="javascript:window.history.back(-1);" value="返回"/>
</div>
</s:form>
2、持久层
ProviderMapper.class
int UpdateProvider(Provider provider);
ProviderMapper.xml
<update id="UpdateProvider" parameterType="provider">
update smbms_provider
<set>
<if test="proCode!=null">
proCode = #{proCode},
</if>
<if test="proName!=null">
proName = #{proName},
</if>
<if test="proDesc!=null">
proDesc = #{proDesc},
</if>
<if test="proContact!=null">
proContact = #{proContact},
</if>
<if test="proPhone!=null">
proPhone = #{proPhone},
</if>
<if test="proAddress!=null">
proAddress = #{proAddress},
</if>
<if test="proFax!=null">
proFax = #{proFax},
</if>
<if test="createdBy!=null">
createdBy = #{createdBy},
</if>
<if test="creationDate!=null">
creationDate = #{creationDate},
</if>
<if test="modifyDate!=null">
modifyDate = #{modifyDate},
</if>
<if test="modifyBy!=null">
modifyBy = #{modifyBy},
</if>
</set>
where id = #{id};
</update>
ProviderService.class
int UpdateProvider(Provider provider);
ProviderServiceImpl.class
public int UpdateProvider(Provider provider) {
return providerMapper.UpdateProvider(provider);
}
3、控制器层
@RequestMapping("/update")
public String updateProvider(Provider provider,Map<String,Object> map){
int i =0;
provider.setCreationDate(new Date());
User user = (User) session.getAttribute("user");
provider.setCreatedBy(user.getId());
i = providerService.UpdateProvider(provider);
if (i < 1) {
map.put("updateProvider",provider);
return "redirect:providermodify";
}
return "redirect:providerlist";
}
十九、实现供应商管理的删除功能
1、视图层
<a class="deleteProvider" href="javascript:if(confirm('您真的要删除吗?')){location.href='${pageContext.request.contextPath }/provider/providerdel?id=${pr.id}'}"><img src="${pageContext.request.contextPath }/images/schu.png" alt="删除" title="删除"/></a>
2、持久化层
ProviderMapper.class
int DeleteProviderById(@Param("id") Long id);
ProviderMapper.xml
<delete id="DeleteProviderById" parameterType="java.lang.Long">
delete from smbms_provider where id = #{id};
</delete>
ProviderService.class
int DeleteProviderById(Long id);
ProviderServiceImpl.class
public int DeleteProviderById(Long id) {
return providerMapper.DeleteProviderById(id);
}
3、控制器层
@RequestMapping("/providerdel")
public String deleteProviderById(Long id){
providerService.DeleteProviderById(id);
return "redirect:providerlist";
}
二十、实现订单管理的检索功能
1、视图层
跳转
<li ><a href="${pageContext.request.contextPath}/bill/billlist">订单管理</a></li>
检索条件
<form method="get" action="${pageContext.request.contextPath }/bill/billlist">
<span>商品名称:</span>
<input name="productname" type="text" value="${productname}">
<span>供应商:</span>
<select name="proid">
<option value="">--请选择--</option>
<c:forEach items="${providerIdNames}" var="pronames">
<option value="${pronames.id}" <c:if test="${proId==pronames.id}">selected</c:if>>${pronames.proName}</option>
</c:forEach>
</select>
<span>是否付款:</span>
<select name="ispayment">
<option value="">--请选择--</option>
<option value="1" <c:if test="${ispayment==1}">selected</c:if>>未付款</option>
<option value="2" <c:if test="${ispayment==2}">selected</c:if>>已付款</option>
</select>
<input value="查 询" type="submit" id="searchbutton">
<a href="${pageContext.request.contextPath }/bill/billadd">添加订单</a>
</form>
数据展示
<c:forEach items="${pageInfo.list}" var="bill">
<tr>
<td>
<span>${bill.billCode} </span>
</td>
<td>
<span>${bill.proName}</span>
</td>
<td>
<span>${bill.productName}</span>
</td>
<td>
<span>${bill.productUnit}</span>
</td>
<td>
<span>${bill.totalPrice/bill.productCount}¥</span>
</td>
<td>
<span>${bill.productCount}</span>
</td>
<td>
<span>${bill.totalPrice}¥</span>
</td>
<td>
<span>${bill.isPayment==1?"未付款":"已付款"}</span>
</td>
<td>
<span><f:formatDate value="${bill.creationDate}" pattern="yyyy-MM-dd"/></span>
</td>
<td>
<span><a class="viewBill" href="${pageContext.request.contextPath }/bill/billview?id=${bill.id}&flag=update"><img src="${pageContext.request.contextPath }/images/read.png" alt="查看" title="查看"/></a></span>
<span><a class="modifyBill" href="${pageContext.request.contextPath }/bill/billmodify?id=${bill.id}&flag=update"><img src="${pageContext.request.contextPath }/images/xiugai.png" alt="修改" title="修改"/></a></span>
<span><a class="deleteBill" href="${pageContext.request.contextPath }/bill/billdel?id=${bill.id}"><img src="${pageContext.request.contextPath }/images/schu.png" alt="删除" title="删除"/></a></span>
</td>
</tr>
</c:forEach>
翻页
<ul class="page-num-ul clearfix">
<li>共${pageInfo.total}条记录 ${pageInfo.pageNum}/${pageInfo.pages}页</li>
<a href="${pageContext.request.contextPath }/bill/billlist?n=${pageInfo.firstPage}&productname=${productname}&proid=${proId}&ispayment=${ispayment}">首页</a>
<a href="${pageContext.request.contextPath }/bill/billlist?n=${pageInfo.prePage<1?1:pageInfo.prePage}&productname=${productname}&proid=${proId}&ispayment=${ispayment}">上一页</a>
<c:forEach items="${pageInfo.navigatepageNums}" var="num">
<a href="${pageContext.request.contextPath }/bill/billlist?n=${num}&productname=${productname}&proid=${proId}&ispayment=${ispayment}">${num}</a>
</c:forEach>
<a href="${pageContext.request.contextPath }/bill/billlist?n=${pageInfo.nextPage<1?pageInfo.pages:pageInfo.nextPage}&productname=${productname}&proid=${proId}&ispayment=${ispayment}">下一页</a>
<a href="${pageContext.request.contextPath }/bill/billlist?n=${pageInfo.lastPage}&productname=${productname}&proid=${proId}&ispayment=${ispayment}">最后一页</a>
</ul>
2、持久层
ProviderMapper.class
查询下拉列表的内容
@Select("select id,proName from smbms_provider")
List<Provider> SelectIdAndName();
建一个用于页面显示的POJO类
@Data
public class BillPro extends Bill {
private String proName;
}
BillMapper.class
public interface BillMapper {
List<BillPro> SelectBillPageList(@Param("productname") String productname,@Param("proId") Long proId, @Param("ispayment") Integer ispayment);
}
BillMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dong.dao.BillMapper">
<resultMap id="PageList" type="billPro">
<id column="id" property="id"/>
<result column="billCode" property="billCode"/>
<result column="productName" property="productName" />
<result column="productDesc" property="productDesc" />
<result column="productUnit" property="productUnit" />
<result column="productCount" property="productCount" />
<result column="totalPrice" property="totalPrice" />
<result column="isPayment" property="isPayment" />
<result column="createdBy" property="createdBy" />
<result column="creationDate" property="creationDate" />
<result column="modifyBy" property="modifyBy" />
<result column="modifyDate" property="modifyDate" />
<result column="providerId" property="providerId"/>
<result column="proName" property="proName" />
</resultMap>
<sql id="Base_Column_List" >
id, billCode, productName, productDesc, productUnit, productCount, totalPrice, isPayment,
createdBy, creationDate, modifyBy, modifyDate, providerId
</sql>
<select id="SelectBillPageList" resultMap="PageList">
select b.*,p.proName from smbms_bill b,smbms_provider p where b.providerId = p.id
<if test="productname!=''">
and b.productName like concat('%',#{productname},'%')
</if>
<if test="proId!=null">
and b.providerId=#{proId}
</if>
<if test="ispayment!=null">
and b.isPayment = #{ispayment}
</if>
</select>
</mapper>
BillService.class
public interface BillService {
List<Provider> SelectIdAndName();
PageInfo<BillPro> SelectBillPageList(String productname, Long proId, Integer ispayment, Integer n, Integer pageSize);
}
BillServiceImpl.class
@Service
@Transactional
public class BillServiceImpl implements BillService {
@Autowired
private BillMapper billMapper;
@Autowired
private ProviderMapper providerMapper;
public List<Provider> SelectIdAndName() {
return providerMapper.SelectIdAndName();
}
public PageInfo<BillPro> SelectBillPageList(String productname, Long proId, Integer ispayment, Integer n, Integer pageSize) {
PageHelper.startPage(n,pageSize);
List<BillPro> billPros = billMapper.SelectBillPageList(productname, proId, ispayment);
PageInfo<BillPro> pageInfo = new PageInfo<BillPro>(billPros);
return pageInfo;
}
}
3、控制器层
@Controller
@RequestMapping("/bill")
public class BillController {
@Autowired
private BillService billService;
@Autowired
private HttpSession session;
@GetMapping("/billlist")
public String goBillList(@RequestParam(value = "productname", defaultValue = "") String productname,
@RequestParam(value = "proid", defaultValue = "") Long proId,
@RequestParam(value = "ispayment", defaultValue = "") Integer ispayment,
@RequestParam(value = "n", defaultValue = "1") Integer n,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
Map<String, Object> map) {
List<Provider> providers = billService.SelectIdAndName();
PageInfo<BillPro> pageInfo = billService.SelectBillPageList(productname, proId, ispayment, n, pageSize);
map.put("pageInfo",pageInfo);
map.put("providerIdNames", providers);
map.put("productname",productname);
map.put("proId",proId);
map.put("ispayment",ispayment);
return "billlist";
}
}
二十一、实现订单管理的添加功能
1、视图层
跳转
<a href="${pageContext.request.contextPath }/bill/billadd">添加订单</a>
添加
<form id="billForm" name="billForm" method="post" action="${pageContext.request.contextPath}/bill/addbill">
<div class="">
<label for="billCode">订单编码:</label>
<input type="text" name="billCode" class="text" id="billCode" value="">
<!-- 放置提示信息 -->
<font color="red"></font>
</div>
<div>
<label for="productName">商品名称:</label>
<input type="text" name="productName" id="productName" value="">
<font color="red"></font>
</div>
<div>
<label for="productUnit">商品单位:</label>
<input type="text" name="productUnit" id="productUnit" value="">
<font color="red"></font>
</div>
<div>
<label for="productCount">商品数量:</label>
<input type="text" name="productCount" id="productCount" value="">
<font color="red"></font>
</div>
<div>
<label for="totalPrice">总金额:</label>
<input type="text" name="totalPrice" id="totalPrice" value="">
<font color="red"></font>
</div>
<div>
<label >供应商:</label>
<select name="providerId" id="providerId">
<cl:forEach items="${addproviders}" var="pro">
<option value="${pro.id}">${pro.proName}</option>
</cl:forEach>
</select>
<font color="red"></font>
</div>
<div>
<label >是否付款:</label>
<input type="radio" name="isPayment" value="1" checked="checked">未付款
<input type="radio" name="isPayment" value="2" >已付款
</div>
<div class="providerAddBtn">
<input type="submit" name="add" id="add" value="保存">
<input type="button" id="back" name="back" value="返回" >
</div>
</form>
2、持久化层
int AddBill(Bill bill);
<insert id="AddBill" parameterType="bill">
insert into smbms_bill
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="billCode!=null">
billCode,
</if>
<if test="productName!=null">
productName,
</if>
<if test="productDesc!=null">
productDesc,
</if>
<if test="productUnit!=null">
productUnit,
</if>
<if test="productCount!=null">
productCount,
</if>
<if test="totalPrice!=null">
totalPrice,
</if>
<if test="isPayment!=null">
isPayment,
</if>
<if test="createdBy!=null">
createdBy,
</if>
<if test="creationDate!=null">
creationDate,
</if>
<if test="modifyBy!=null">
modifyBy,
</if>
<if test="modifyDate!=null">
modifyDate,
</if>
<if test="providerId!=null">
providerId,
</if>
</trim>
<trim prefix="values(" suffix=")" suffixOverrides=",">
<if test="billCode!=null">
#{billCode},
</if>
<if test="productName!=null">
#{productName},
</if>
<if test="productDesc!=null">
#{productDesc},
</if>
<if test="productUnit!=null">
#{productUnit},
</if>
<if test="productCount!=null">
#{productCount},
</if>
<if test="totalPrice!=null">
#{totalPrice},
</if>
<if test="isPayment!=null">
#{isPayment},
</if>
<if test="createdBy!=null">
#{createdBy},
</if>
<if test="creationDate!=null">
#{creationDate},
</if>
<if test="modifyBy!=null">
modifyBy=#{modifyBy},
</if>
<if test="modifyDate!=null">
#{modifyDate},
</if>
<if test="providerId!=null">
#{providerId},
</if>
</trim>
</insert>
int AddBill(Bill bill);
public int AddBill(Bill bill) {
return billMapper.AddBill(bill);
}
3、控制器层
@RequestMapping("/billadd")
public String gobilladd(Map<String,Object> map){
List<Provider> providers = billService.SelectIdAndName();
map.put("addproviders",providers);
return "billadd";
}
@PostMapping("/addbill")
public String addBill(Bill bill,Map<String,Object> map){
int i =0;
bill.setCreationDate(new Date());
User user = (User) session.getAttribute("user");
if(user!=null){
bill.setCreatedBy(user.getId());
}
System.out.println(bill);
i = billService.AddBill(bill);
if(i<1){
return "redirect:billadd";
}
return "redirect:billlist";
}
二十二、实现订单管理的详细信息
1、视图层
<a class="viewBill" href="${pageContext.request.contextPath }/bill/billview?id=${bill.id}"><img src="${pageContext.request.contextPath }/images/read.png" alt="查看" title="查看"/></a>
<input type="hidden" id="id" value="${billview.id}" />
<p><strong>订单编号:</strong><span>${billview.billCode}</span></p>
<p><strong>商品名称:</strong><span>${billview.productName}</span></p>
<p><strong>商品单位:</strong><span>${billview.productUnit}</span></p>
<p><strong>商品数量:</strong><span>${billview.productCount}</span></p>
<p><strong>总金额:</strong><span>${billview.totalPrice}</span></p>
<p><strong>供应商:</strong><span>${billview.proName}</span></p>
<p><strong>是否付款:</strong><span>${billview.isPayment==1?"未付款":"已付款"}</span></p>
<div class="billAddBtn">
<input type="button" id="back" name="back" οnclick="javascript:window.history.back(-1);" value="返回"/>
</div>
2、持久层
BillPro SelectBillById(@Param("id") Long id);
<select id="SelectBillById" parameterType="java.lang.Long" resultType="billPro">
select b.*,p.proName from smbms_bill b,smbms_provider p where b.providerId = p.id and b.id = #{id};
</select>
BillPro SelectBillById(Long id);
public BillPro SelectBillById(Long id) {
return billMapper.SelectBillById(id);
}
3、控制器
@GetMapping("/billview")
public String billview(@RequestParam("id") Long id,Map<String,Object> map){
BillPro billPro = billService.SelectBillById(id);
map.put("billview",billPro);
return "billview";
}
二十三、实现订单管理的修改功能
一、跳转到修改界面
1、视图层
<a class="modifyBill" href="${pageContext.request.contextPath }/bill/billmodify?id=${bill.id}&flag=update"><img src="${pageContext.request.contextPath }/images/xiugai.png" alt="修改" title="修改"/></a>
2、持久层
这里直接使用的二十二中的持久层
3、控制器层
@GetMapping("/billmodify")
public String gobillmodify(){
return "billmodify";
}
@ModelAttribute
public void ModeAttributeBill(Long id,String flag,Map<String,Object> map){
if("update".equals(flag)){
BillPro billPro = billService.SelectBillById(id);
List<Provider> providers = billService.SelectIdAndName();
map.put("updatebill",billPro);
map.put("proids",providers);
}
}
二、修改功能
1、视图层
<s:form id="billForm" name="billForm" method="post" action="${pageContext.request.contextPath }/bill/update" modelAttribute="updatebill">
<s:hidden path="id"/>
<div>
<label for="billCode">订单编码:</label>
<s:input path="billCode"/>
</div>
<div>
<label for="productName">商品名称:</label>
<s:input path="productName"/>
<font color="red"></font>
</div>
<div>
<label for="productUnit">商品单位:</label>
<s:input path="productUnit"/>
<font color="red"></font>
</div>
<div>
<label for="productCount">商品数量:</label>
<s:input path="productCount"/>
<font color="red"></font>
</div>
<div>
<label for="totalPrice">总金额:</label>
<s:input path="totalPrice"/>
<font color="red"></font>
</div>
<div>
<label for="providerId">供应商:</label>
<s:select path="providerId" items="${proids}" itemValue="id" itemLabel="proName">
</s:select>
<font color="red"></font>
</div>
<div>
<label >是否付款:</label>
<s:radiobutton path="isPayment" value="1"/>未付款
<s:radiobutton path="isPayment" value="2"/>已付款
</div>
<div class="providerAddBtn">
<input type="submit" name="save" id="save" value="保存">
<input type="button" id="back" name="back" οnclick="javascript:window.history.back(-1);" value="返回"/>
</div>
</s:form>
2、持久层
int UpdateBill(Bill bill);
<update id="UpdateBill" parameterType="bill">
update smbms_bill
<set>
<if test="billCode!=null">
billCode=#{billCode},
</if>
<if test="productName!=null">
productName= #{productName},
</if>
<if test="productDesc!=null">
productDesc= #{productDesc},
</if>
<if test="productUnit!=null">
productUnit= #{productUnit},
</if>
<if test="productCount!=null">
productCount=#{productCount},
</if>
<if test="totalPrice!=null">
totalPrice= #{totalPrice},
</if>
<if test="isPayment!=null">
isPayment= #{isPayment},
</if>
<if test="createdBy!=null">
createdBy= #{createdBy},
</if>
<if test="creationDate!=null">
creationDate= #{creationDate},
</if>
<if test="modifyBy!=null">
modifyBy=#{modifyBy},
</if>
<if test="modifyDate!=null">
modifyDate=#{modifyDate},
</if>
<if test="providerId!=null">
providerId=#{providerId},
</if>
</set>
where id = #{id};
</update>
int UpdateBill(Bill bill);
public int UpdateBill(Bill bill) {
return billMapper.UpdateBill(bill);
}
3、控制器层
@PostMapping("/update")
public String update(Bill bill,Map<String,Object> map){
int i = 0;
bill.setModifyDate(new Date());
User user = (User) session.getAttribute("user");
if(user!=null){
bill.setModifyBy(user.getId());
}
i = billService.UpdateBill(bill);
if (i<1){
List<Provider> providers = billService.SelectIdAndName();
map.put("proids",providers);
map.put("updatebill",bill);
return "redirect:billmodify";
}
return "redirect:billlist";
}
二十四、实现订单管理的删除功能
1、视图层
<a class="deleteBill" href="javascript:if(confirm('您真的要删除吗?')){location.href='${pageContext.request.contextPath }/bill/billdel?id=${bill.id}'}"><img src="${pageContext.request.contextPath }/images/schu.png" alt="删除" title="删除"/></a>
2、持久层
int DeleteBill(@Param("id") Long id);
<delete id="DeleteBill" parameterType="java.lang.Long">
delete from smbms_bill where id = #{id};
</delete>
int DeleteBill(Long id);
public int DeleteBill(Long id) {
return billMapper.DeleteBill(id);
}
3、控制器层
@GetMapping("/billdel")
public String billdel(@RequestParam("id") Long id){
billService.DeleteBill(id);
return "redirect:billlist";
}