简易SSM+Layui 查询信息项目

      入职的第一个星期,领导安排做了一个测试新人项目,框架要求用SpringMVC,数据库使用Oracle,页面没有要求,所以我就选用了我比较熟悉的Layui,小伙伴可以把该项目当成简易的SSM项目框架使用,不需要使用时不需要再次搭建。

spring-mybatis配置

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
                        http://www.springframework.org/schema/aop
                        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
    <!-- 自动扫描 -->
    <context:component-scan base-package="com.cn.ssm"/>


    <!-- 引入连接数据库参数的配置文件 -->
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"/>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${password}"/>
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:*com/cn/ssm/mapping/*.xml"></property>
    </bean>

    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.cn.ssm.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 拦截器方式配置事物 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="append*" propagation="REQUIRED"/>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="modify*" propagation="REQUIRED"/>
            <tx:method name="edit*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="remove*" propagation="REQUIRED"/>
            <tx:method name="confirm*" propagation="REQUIRED"/>
            <tx:method name="start*" propagation="REQUIRED"/>
            <tx:method name="sendMes" propagation="REQUIRED"/>
            <tx:method name="read*" propagation="REQUIRED"/>
            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="find*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="load*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="search*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="datagrid*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="select*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

<!--    <aop:config>-->
<!--        <aop:pointcut id="mainPointcut" expression="execution(* com.cn.ssm.service.*(..))"/>-->
<!--        <aop:advisor pointcut-ref="mainPointcut" advice-ref="transactionAdvice" order="2"/>-->
<!--    </aop:config>-->
</beans>  

springMvc配置

<?xml version="1.0" encoding="UTF-8"?>
<!-- ~ Copyright (c) 2009-2013 NancyNing All rights reserved. ~ @(#) 
	spring-mvc.xml 2013-05-20 10:09 -->

<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    					http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
     <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->  
    <context:component-scan base-package="com.cn.ssm.controller" />  
    <mvc:annotation-driven />
    <mvc:default-servlet-handler/>
    <!--避免IE执行AJAX时,返回JSON出现下载文件 -->  
    <bean id="mappingJacksonHttpMessageConverter"  
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
        <property name="supportedMediaTypes">  
            <list>  
                <value>text/html;charset=UTF-8</value>  
            </list>  
        </property>  
    </bean>  
    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->  
    <bean  
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
        <property name="messageConverters">  
            <list>  
                <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->  
            </list>  
        </property>  
    </bean>  
    <!-- 定义跳转的文件的前后缀 ,视图模式配置-->  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->  
        <property name="prefix" value="/WEB-INF/jsp/" />  
        <property name="suffix" value=".jsp" />  
    </bean>  
      
    <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->  
    <bean id="multipartResolver"    
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
        <!-- 默认编码 -->  
        <property name="defaultEncoding" value="utf-8" />    
        <!-- 文件大小最大值 -->  
        <property name="maxUploadSize" value="10485760000" />    
        <!-- 内存中的最大值 -->  
        <property name="maxInMemorySize" value="40960" />    
    </bean>
    <mvc:interceptors>
        <!--登录拦截器-->
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/login"/>
            <mvc:exclude-mapping path="/js/**"/>
            <mvc:exclude-mapping path="/layui/**"/>
            <mvc:exclude-mapping path="/css/**"/>
            <bean class="com.cn.ssm.common.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

log4j 配置

### 设置###
log4j.rootLogger = debug,stdout,D,E

### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 输出DEBUG 级别以上的日志到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 输出ERROR 级别以上的日志到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

登录页面jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>登录页面</title>
    <link rel="stylesheet" href="css/login.css" media="all">
    <link rel="stylesheet" href="css/layui.css">
</head>
<body style="margin: 0px;
	padding: 0px;
	background-color: #005cb1;
	width: 100%;
	height: 100%;
	text-align: center;">
<form id="userForm" class="layui-form" method="post">
    <div>
        <div id="card">
            <div id="top" style="text-align: center;
	font-family: 'Microsoft Tai Le Bold', 'Microsoft Tai Le Regular',
		'Microsoft Tai Le';
	font-weight: bold;
	font-style: normal;
	font-size: 20px;
	height: 50px;
	color: white;">查询登录
            </div>
            <div>
                <div>
                    <input id="username" name="username" type="text" placeholder="账号" autocomplete="off" style="background-color: white;
	border-radius: 10px;
	width: 390px;
	height: 40px;
	margin-top: 65px;
	text-indent: 15px;"/>
                </div>
            </div>
            <div>
                <div>
                    <input id="password" type="password" name="password" placeholder="密码" autocomplete="off" style="	background-color: white;
	border-radius: 10px;
	width: 390px;
	height: 40px;
	margin-top: 25px;
	text-indent: 15px;"/>
                </div>
            </div>
            <div>
                <div style="color: #FCC800;width: 390px;margin: auto;">
                    <button id="login" type="button" style="margin-top: 25px;background-color: #005cb1" lay-submit
                            lay-filter="login"
                            class="layui-btn layui-btn-fluid">登录
                    </button>
                </div>
            </div>
            <div>
                <div class="layui-col-xs-12" style="margin-top: 50px; color: white;">Project one test</div>
            </div>
        </div>
    </div>
</form>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="layui/layui.all.js" charset="utf-8"></script>
<script type="text/javascript" src="layui/lay/modules/layer.js" ></script>
<script type="text/javascript" src="js/login.js" charset="utf-8"></script>
</body>
</html>

需要layui的资源文件直接去layui官网下载即可。

登录页面js


layui.use('form', function() {
    var form = layui.form;
    var layer = layui.layer;
    form.on('submit(login)', function(data){
        $.ajax({
            url: '/login',
            type : 'POST',
            data: {
                'username': data.field.username,
                'password': data.field.password
            },
            dataType: 'json',
            success: function (res) {
                if (res.msg != '' && res.msg != null) {
                    layer.msg(res.msg);
                    return false;
                }
                $(location).prop('href','/index')
            },
            error: function (res) {
                layer.msg("登录失败");
                return false;
            }
        });
    });
})

$(document).keyup(function(e){
    if (e.keyCode == 13) {
        if ($('username').val() != '' && $('password').val() != '') {
            $('#login')[0].click();
        }
    }

});

登录后台

package com.cn.ssm.controller;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private UsersService usersService;
    @Autowired
    private IDCardService idCardService;
    /**
     * 用户登录
     *
     * @param user
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result login(Users user, Model model, HttpSession session) {
        Result<Object> result = new Result();
        //获取用户名和密码
        String username = user.getUsername();
        String password = user.getPassword();
        //些处横板从数据库中获取对用户名和密码后进行判断
        Users userInfo = usersService.selectByName(username);
        if (userInfo == null) {
            result.setCode("1");
            result.setMsg("用户名或密码错误");
            return result;
        }else {
            String pwd = userInfo.getPassword();
            if (pwd.equals(password)) {
                session.setAttribute("USER_SESSION", userInfo);
                return result;
            } else {
                result.setCode("1");
                result.setMsg("用户名或密码错误");
                return result;
            }
        }
    }
}

Result是我自己封装的一个类,主要用于返回信息,状态和数据

Result类代码

package com.cn.ssm.domain;

public class Result<T> {

        private String code = "0";

        private String msg;

        private T result;

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        public T getResult() {
            return result;
        }

        public void setResult(T result) {
            this.result = result;
        }
    }

之后便是调用service里面selsctByName(),在写一些简单的sql即可。

登录页面和主页面样式一样,用到layui的主要包含数据表格,以下是代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>信息详情</title>
    <link rel="stylesheet" href="../../css/login.css" media="all">
    <link rel="stylesheet" href="../../css/layui.css">
</head>
<body >
<span>身份证信息</span>
<table class="layui-hide" id="one"></table><br><br>
<span>登记信息</span>
<table class="layui-hide" id="two"></table><br><br>
<span>完成情况信息</span>
<table class="layui-hide" id="three"></table>
<input type="hidden" id="ID" value="${info.ID}">
<input type="hidden" id="type" value="${info.type}">


<script type="text/javascript" src="../../js/jquery.min.js"></script>
<script type="text/javascript" src="../../layui/layui.all.js" charset="utf-8"></script>
<script type="text/javascript" src="../../layui/lay/modules/layer.js" ></script>
<script type="text/javascript" src="../../js/indexTable.js" charset="utf-8"></script>
<script type="text/javascript" src="../../js/dateFormat.js" charset="utf-8"></script>
</body>
</html>

相应JS代码:

$(function () {
    var id = $("#ID").val();
    var type = $("#type").val();

    var table = layui.table;
    var url = getRootPath() + "/station/StationInfo/searchList";
    var cols =
        layui.use('table', function () {
            var table = layui.table;
            table.render({
                elem: '#one'
                , url: '/searchList?ID=' + id
                , cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
                , cols: [[
                    {field: 'id', width: 200, title: '身份证号', sort: true},
                    {field: 'typeName', width: 200, title: '居住类型'}
                    , {field: 'startTime', width: 200, title: '开始时间', templet: '#startTime'}
                    , {field: 'endTime', width: 200, title: '截止时间', templet: '#endTime'}
                ]], page: true   //开启分页
                , limit: 10   //默认十条数据一页
                , limits: [10, 20, 30, 50]  //数据分页条
            });
            table.render({
                elem: '#two'
                , url: '/searchListTwo?ID=' + id + "&type=" + type
                , cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
                , cols: [[
                    {field: 'dzsffsbh', width: 200, title: '是否申请地址变更'},
                    {field: 'wyjjrq', width: 200, title: '网约取件时间', templet: '#wyjjrq'}
                    , {field: 'jjr_xm', width: 200, title: '取件人姓名'}
                    , {field: 'jjr_lxdh', width: 200, title: '取件联系电话'}
                    , {field: 'jjr_dz', width: 300, title: '取件地址'}

                    , {field: 'jjtscg', width: 200, title: '是否取件成功'}
                    , {field: 'jjsbyy', width: 200, title: '取件失败原因'}
                    , {field: 'jjsj', width: 200, title: '取件时间', templet: '#jjsj'}
                    , {field: 'jjdh', width: 200, title: '取件单号'}
                    , {field: 'sjr_xm', width: 200, title: '收件人姓名'}

                    , {field: 'sjr_lxdh', width: 200, title: '收件人联系电话'}
                    , {field: 'sjr_dz', width: 200, title: '收件地址'}
                    , {field: 'psrq', width: 200, title: '配送日期'}
                    , {field: 'psdh', width: 200, title: '配送单号'}
                    , {field: 'xgsj', width: 200, title: '修改日期', templet: '#xgsj'}
                ]],
                parseData: function (res) {
                    console.log(res);
                }
            });
            table.render({
                elem: '#three'
                , url: '/searchListThree?ID=' + id
                , cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
                , cols: [[
                    {field: 'yjmx_qzrq', width: 200, title: '签注时间', templet: '#yjmx_qzrq'},
                    {field: 'yjmx_sfps', width: 200, title: '是否配送'}
                    , {field: 'yjmx_pspc', width: 200, title: '配送批次'}
                    , {field: 'yjmx_qsrq', width: 200, title: '签收日期'}
                    , {field: 'yjmx_psdh', width: 200, title: '配送单号'}
                ]]
                , page: true   //开启分页
                , limit: 10   //默认十条数据一页
                , limits: [10, 20, 30, 50]  //数据分页条
            });
        });
});

需要注意的一点是lauyi需特定的返回数据格式才能在页面显示出来,这是后台的代码

   @RequestMapping("/searchList")
    @ResponseBody
    public Map<String,Object> searchListTwo(String ID,String type){
        Map<String,Object> resultMap = new HashMap<String, Object>();
        List<IDCard> list = new ArrayList<IDCard>();
        if ("2".equals(type)) {
            list = idCardService.selectByTypeOne(ID);
        } else {
            list = idCardService.selectByTypeTwo(ID);
        }
        for (int i = 0;i<list.size();i++){
            if ("1".equals(list.get(i).getDzsffsbh())){
                list.get(i).setDzsffsbh("已变更");
            }else{
                list.get(i).setDzsffsbh("未变更");
            }
            if ("1".equals(list.get(i).getJjtscg())){
                list.get(i).setJjtscg("已取件");
            }else{
                list.get(i).setJjtscg("未取件");
            }
        }
        resultMap.put("data",list);
        resultMap.put("code",0);
        resultMap.put("msg","");
        resultMap.put("count","1000");

        return resultMap;
    }

resultMap中data,code,msg,count便是layui规定的返回数据格式。

之上就是简易的SSM加layui后台项目,如果有小伙伴有什么问题可留言,也可以关注我公众号加我微信。


                                                                                        Java核心基础

                                                                                 ----------------------------------

                                                                                    (看那两撇小胡子)

                                                                                    

                                                                          基础 | 心得 | 经历 | 更重要的是开心嘛!

发布了15 篇原创文章 · 获赞 19 · 访问量 5万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览