<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.0.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>5.0.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.0.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>5.0.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.0.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.0.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjrtartifactId>
<version>1.9.1version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.1version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.6version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.16version>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-dbcp2artifactId>
<version>2.5.0version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.47version>
dependency>
<dependency>
<groupId>org.hibernate.validatorgroupId>
<artifactId>hibernate-validatorartifactId>
<version>6.1.5.Finalversion>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.3.3version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>taglibsgroupId>
<artifactId>standardartifactId>
<version>1.1.2version>
dependency>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>5.1.4version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.12version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
dependency>
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
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
<configuration>
<settings>
<setting name="cacheEnabled" value="true" />
<setting name="logImpl" value="LOG4J"/>
<setting name="autoMappingBehavior" value="FULL" />
<setting name="defaultStatementTimeout" value="25" />
<setting name="mapUnderscoreToCamelCase" value="true" />
settings>
<typeAliases>
<package name="com.dong.pojo"/>
typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">plugin>
plugins>
<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
<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>
<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:annotation-driven>
<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;
}
使用了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");
})
})
(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;
}
}
@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>
不需要与数据库进行交互,没有持久化层
退出
退出系统
在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";
}
密码修改
@RequestMapping("/pwdModify")
public String goPwdModify(){
return "pwdmodify";
}
当旧密码框失去焦点时判断旧密码是否正确
$(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
<mapper namespace="com.dong.dao.UserMapper">
<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>
<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("密码不一致!请重新输入!");
}
}
实现提交
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);
}
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>5.1.4version>
dependency>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">plugin>
plugins>
当前页
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;
页面数据显示,大部分都是user类中的,只多了一项roleName
@Data
public class UserRole extends User {
private String roleName;
}
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
<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>
<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();
}
/*
*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";
}
<%--使用EL表达式实现数据回显--%>
<%--Jstl对用户信息进行遍历显示--%>
${ur.userCode}
${ur.userName}
${ur.roleName }
${ur.gender==1?"男":"女" }
${ur.phone}
<%--这里翻页相关的,总记录条数,页数,上一页下一页等--%>
添加用户
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();
}
@RequestMapping("/useradd")
public String toUserAdd(Map<String,Object> map){
List<Role> roles = userService.getRoleNameAndId();
map.put("roles",roles);
return "useradd";
}
$(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")
}
}
)
})
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);
}
(简单做了一个数据回显,这里很难出现错误,因为数据库中的字段除了自增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";
}
用来跳转的链接
用来接受数据的前端
用户名称:${userRole.userName}
用户性别:${userRole.gender==1?'男':'女'}
出生日期:
用户电话:${userRole.phone}
用户地址:${userRole.address}
用户角色:${userRole.roleName}
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);
}
@GetMapping("/userview")
public String userview(Long id,Map<String,Object> map){
UserRole userRole = userService.SelectByUserId(id);
map.put("userRole",userRole);
return "userview";
}
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);
}
@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个时区
这里用到了Spring的标签实现的数据展示(对我来说时新知识)
这里链接一个博客简单了解https://blog.csdn.net/qq_38198467/article/details/90602361
男
女
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);
}
@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";
}
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);
}
@GetMapping("/userdel")
public String deleteUser(@RequestParam("id") Long id){
userService.deleteUserById(id);
return "forward:userlist";
}
(包括跳转和数据显示两部分)
跳转
供应商管理
数据检索条件
数据显示
${pr.proCode}
${pr.proName}
${pr.proContact}
${pr.proPhone}
${pr.proFax}
${pr.proAddress}
翻页系统
ProviderMapper.java
public interface ProviderMapper {
List<Provider> SelectProviderListPage(@Param("proContact") String proContact,@Param("proName") String proName);
}
ProviderMapper.xml
<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;
}
}
@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";
}
}
跳转
添加供应商
输入数据
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>
//页面跳转
@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";
}
跳转
数据显示
供应商编码:${viewprovider.proCode}
供应商名称:${viewprovider.proName}
联系人:${viewprovider.proContact}
联系电话:${viewprovider.proPhone}
传真:${viewprovider.proFax}
描述:${viewprovider.proDesc}
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);
}
@RequestMapping("/providerview")
public String providerview(Long id,Map<String,Object> map){
Provider provider = providerService.SelectProviderById(id);
map.put("viewprovider",provider);
return "providerview";
}
这里的持久化层直接使用了十七里的根据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);
}
@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);
}
}
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);
}
@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";
}
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);
}
@RequestMapping("/providerdel")
public String deleteProviderById(Long id){
providerService.DeleteProviderById(id);
return "redirect:providerlist";
}
跳转
订单管理
检索条件
数据展示
${bill.billCode}
${bill.proName}
${bill.productName}
${bill.productUnit}
${bill.totalPrice/bill.productCount}¥
${bill.productCount}
${bill.totalPrice}¥
${bill.isPayment==1?"未付款":"已付款"}
翻页
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
<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;
}
}
@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";
}
}
跳转
添加订单
添加
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);
}
@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";
}
订单编号:${billview.billCode}
商品名称:${billview.productName}
商品单位:${billview.productUnit}
商品数量:${billview.productCount}
总金额:${billview.totalPrice}
供应商:${billview.proName}
是否付款:${billview.isPayment==1?"未付款":"已付款"}
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);
}
@GetMapping("/billview")
public String billview(@RequestParam("id") Long id,Map<String,Object> map){
BillPro billPro = billService.SelectBillById(id);
map.put("billview",billPro);
return "billview";
}
这里直接使用的二十二中的持久层
@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);
}
}
未付款
已付款
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);
}
@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";
}
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);
}
@GetMapping("/billdel")
public String billdel(@RequestParam("id") Long id){
billService.DeleteBill(id);
return "redirect:billlist";
}