• 新版idea创建springMVC项目


    新版idea创建springMVC项目



    1.创建项目

    new一个project

    进行下一步

    继续下一步,设置项目名,存放位置,项目所属公司

    2. 使用maven导入需要的包

    查看maven配置,及使用本地库

    导包

    导入spring框架所需的包

    首先在properties中加入spring.version

    然后导入依赖

    <!--spring核心包-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-expression</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>3.2.13.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>3.2.13.RELEASE</version>
            </dependency>
    

    导入mybaits及数据库所需包

    导入通用包

    导入alibaba及log4j包

    最终的pom.xml文件

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.example</groupId>
        <artifactId>demo1</artifactId>
        <version>1.0-SNAPSHOT</version>
        <name>demo1</name>
        <packaging>war</packaging>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <maven.compiler.target>1.8</maven.compiler.target>
            <maven.compiler.source>1.8</maven.compiler.source>
            <junit.version>5.6.2</junit.version>
            <spring.version>4.3.6.RELEASE</spring.version>
        </properties>
    
        <dependencies>
            <!--javax包-->
            <dependency>
                <groupId>javax</groupId>
                <artifactId>javaee-web-api</artifactId>
                <version>8.0.1</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.mvc</groupId>
                <artifactId>javax.mvc-api</artifactId>
                <version>1.0.0</version>
            </dependency>
            <!--添加的javax包-->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>4.0.1</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.annotation</groupId>
                <artifactId>jsr250-api</artifactId>
                <version>1.0</version>
            </dependency>
            <dependency>
                <groupId>javax.validation</groupId>
                <artifactId>validation-api</artifactId>
                <version>1.1.0.Final</version>
            </dependency>
    
            <!--junit包-->
            <dependency>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-api</artifactId>
                <version>${junit.version}</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-engine</artifactId>
                <version>${junit.version}</version>
                <scope>test</scope>
            </dependency>
            <!--spring核心包-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-expression</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>3.2.13.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>3.2.13.RELEASE</version>
            </dependency>
            <!-- 数据库 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.31</version>
            </dependency>
            <dependency>
                <groupId>com.mchange</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.5.2</version>
            </dependency>
    
            <!--mybatis-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.6</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.3.2</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
            </dependency>
            <!-- 通用包-->
            <dependency>
                <groupId>commons-dbcp</groupId>
                <artifactId>commons-dbcp</artifactId>
                <version>1.4</version>
            </dependency>
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.2.2</version>
            </dependency>
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.4</version>
            </dependency>
            <dependency>
                <groupId>commons-lang</groupId>
                <artifactId>commons-lang</artifactId>
                <version>2.6</version>
            </dependency>
            <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>1.2</version>
            </dependency>
            <dependency>
                <groupId>commons-pool</groupId>
                <artifactId>commons-pool</artifactId>
                <version>1.6</version>
            </dependency>
            <!-- 其他 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.47</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-validator</artifactId>
                <version>5.4.1.Final</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.logging</groupId>
                <artifactId>jboss-logging</artifactId>
                <version>3.1.0.CR2</version>
            </dependency>
            <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>29.0-jre</version>
           </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.3.0</version>
                </plugin>
            </plugins>
        </build>
    </project>
    

    3.配置tomcat

    添加tomcat

    配置tomacat,主要是tomcat版本,端口,默认网址

    4.完善项目结构

    在java中添加controller,services,dao,entity,interceptor四个package。

    在entity中存放实体类,在controller中处理页面请求request与返回给页面信息,dao层调用处理数据库,services存放调用的各种方法,interceptor中保存过滤器相关的类。

    完善webapp

    在webapp下添加static文件夹,用来存放js等相关文件。

    在webapp下进行index.jsp,作为初始界面。

    <%--
      Created by IntelliJ IDEA.
      User: 19781
      Date: 2020/11/15
      Time: 13:21
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    初始界面index.jsp ,欢迎
    </body>
    </html>
    
    

    在WEB-INF目录下添加jsp文件夹,并创建login.jsp

    4.配置springMVC并测试

    编写web.xml,配置springMVC-servlet,log4j和applicatinoContext-mybaits.xml

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
    
        <display-name>springMVC</display-name>
    
        <!--初始界面-->
        <welcome-file-list>
            <welcome-file>/index.jsp</welcome-file>
        </welcome-file-list>
    
        <!-- 1.contextConfigLocation-mybaits参数用来指定SpringMybaits的配置文件 -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext-*.xml</param-value>
        </context-param>
        <!--2.配置Spring官方提供的监听器-->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
    
        <!--3.前端控制器:拦截所有的请求,进行2次分配-->
        <servlet>
            <servlet-name>spring</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springMVC-servlet.xml</param-value>
            </init-param>
        <!-- 优先加载-->
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>spring</servlet-name>
           <!--所有请求都被拦截-->
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
        <!--4.过滤器:处理请求中出现的中文乱码-->
        <filter>
            <filter-name>encodingFilter</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>
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>encodingFilter</filter-name>
            <!-- /*  所有请求-->
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        <!-- 静态资源 -->
        <servlet-mapping>
            <servlet-name>default</servlet-name>
            <url-pattern>*.css</url-pattern>
            <url-pattern>*.js</url-pattern>
            <url-pattern>*.gif</url-pattern>
            <url-pattern>*.png</url-pattern>
            <url-pattern>*.jpg</url-pattern>
            <url-pattern>*.jpeg</url-pattern>
            <url-pattern>*.swf</url-pattern>
            <url-pattern>*.mp4</url-pattern>
        </servlet-mapping>
    
        <!--5.配置log4j-->
        <context-param>
            <param-name>log4jConfigLocation</param-name>
            <param-value>classpath:log4j.properties</param-value>
        </context-param>
        <listener>
            <listener-class>
                org.springframework.web.util.Log4jConfigListener
            </listener-class>
        </listener>
    
    </web-app>
    

    springMVC-servlet.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:mvc="http://www.springframework.org/schema/mvc"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:context="http://www.springframework.org/schema/context"
           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/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <!--1.扫描Controller,并将其生命周期纳入Spring管理-->
        <context:component-scan base-package="com.test.controller"/>
    
    
        <!--2. 配置 message-converters -->
        <mvc:annotation-driven>
            <mvc:message-converters>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
                <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>
                            <value>application/json</value>
                        </list>
                    </property>
                    <property name="features">
                        <list>
                            <!--   Date的日期转换器 -->
                            <value>WriteDateUseDateFormat</value>
                        </list>
                    </property>
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>
    
    
    
        <!-- 3.配置多视图解析器ContentNegotiatingViewResolver:使用了不同的请求方式去请求同一个资源,返回各自的形式 -->
        <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
            <property name="favorParameter" value="true"/>
            <property name="defaultContentType" value="text/html"/>
            <property name="mediaTypes">
                <map>
                    <entry key="html" value="text/html;charset=UTF-8"/>
                    <entry key="json" value="application/json;charset=UTF-8"/>
                    <entry key="xml" value="application/xml;charset=UTF-8"/>
                </map>
            </property>
            <!-- InternalResourceViewResolver是jsp的视图解析器,在无法匹配到html、json、xml的情况下,会返回jsp的视图-->
            <property name="viewResolvers">
                <list>
                    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
                        <property name="prefix" value="/WEB-INF/jsp/"/>
                        <property name="suffix" value=".jsp"/>
                    </bean>
                </list>
            </property>
        </bean>
    
        <!--4.如何引入静态资源文件-->
        <mvc:resources location="/statics/" mapping="/statics/**"/>
    
        <!--5.拦截器 interceptors-->
    
    
        <!-- 6.配置MultipartResolver,用于上传文件,使用spring的CommonsMultipartResolver -->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="maxUploadSize" value="5000000"/>
            <property name="defaultEncoding" value="UTF-8"/>
        </bean>
    
    </beans>
    

    applicationContext-mybaits.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:aop="http://www.springframework.org/schema/aop"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="
                http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd">
    
    </beans>
    

    log4j

    log4j.rootLogger=debug,CONSOLE,file
    #log4j.rootLogger=ERROR,ROLLING_FILE
    
    log4j.logger.com.test=debug
    log4j.logger.org.apache.ibatis=debug
    log4j.logger.org.mybatis.spring=debug
    log4j.logger.java.sql.Connection=debug
    log4j.logger.java.sql.Statement=debug
    log4j.logger.java.sql.PreparedStatement=debug
    log4j.logger.java.sql.ResultSet=debug
    
    ######################################################################################
    # Console Appender  u65e5u5fd7u5728u63a7u5236u8f93u51fau914du7f6e
    ######################################################################################
    log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
    log4j.appender.Threshold=debug
    log4j.appender.CONSOLE.DatePattern=yyyy-MM-dd
    log4j.appender.CONSOLE.Target=System.out
    log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
    log4j.appender.CONSOLE.layout.ConversionPattern= - (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
    
    
    
    ######################################################################################
    # Rolling File  u6587u4ef6u5927u5c0fu5230u8fbeu6307u5b9au5c3au5bf8u7684u65f6u5019u4ea7u751fu4e00u4e2au65b0u7684u6587u4ef6
    ######################################################################################
    #log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender
    #log4j.appender.ROLLING_FILE.Threshold=INFO
    #log4j.appender.ROLLING_FILE.File=${baojia.root}/logs/log.log
    #log4j.appender.ROLLING_FILE.Append=true
    #log4j.appender.ROLLING_FILE.MaxFileSize=5000KB
    #log4j.appender.ROLLING_FILE.MaxBackupIndex=100
    #log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout
    #log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
    
    ######################################################################################
    # DailyRolling File  u6bcfu5929u4ea7u751fu4e00u4e2au65e5u5fd7u6587u4ef6uff0cu6587u4ef6u540du683cu5f0f:log2009-09-11
    ######################################################################################
    log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.file.DatePattern=yyyy-MM-dd
    log4j.appender.file.File=${SMBMS_C12_10.root}/logs/log.log
    log4j.appender.file.Append=true
    log4j.appender.file.Threshold=debug
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern= - (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
    
    #DWR u65e5u5fd7
    #log4j.logger.org.directwebremoting = ERROR
    
    #u663eu793aHibernateu5360u4f4du7b26u7ed1u5b9au503cu53cau8fd4u56deu503c
    #log4j.logger.org.hibernate.type=DEBUG,CONSOLE
    
    #log4j.logger.org.springframework.transaction=DEBUG
    #log4j.logger.org.hibernate=DEBUG
    #log4j.logger.org.acegisecurity=DEBUG
    #log4j.logger.org.apache.myfaces=TRACE
    #log4j.logger.org.quartz=DEBUG
    
    #log4j.logger.com.opensymphony=INFO
    #log4j.logger.org.apache.struts2=DEBUG
    log4j.logger.com.opensymphony.xwork2=debug
    
    

    当前文件结构

    添加对应的javeBean

    在springMVC-servlet中配置controller

    在applicationContext-mybaits中添加services层和dao层

    测试

    启动tomcat。结果在浏览器中显示index.jsp界面

    在login.jsp中添加登录表格

    <section class="loginCont" style="text-align: center">
        <form class="loginForm" action="${pageContext.request.contextPath }/dologin"  name="actionForm" id="actionForm"  method="post" >
            <div class="info">${error}</div>
            <div class="inputbox">
                <%--@declare id="user"--%><label for="user">用户名:</label>
                <input type="text" class="input-text" id="userCode" name="userCode" placeholder="请输入用户名" required/>
            </div>
            <div class="inputbox">
                <%--@declare id="mima"--%><label for="mima">密码:</label>
                <input type="password" id="userPassword" name="userPassword" placeholder="请输入密码" required/>
            </div>
            <div class="subBtn">
                <input type="submit" value="登录"/>
                <input type="reset" value="重置"/>
            </div>
        </form>
    </section>
    

    在controller层添加LoginController类

    package com.test.controller;
    
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /**
     *
     */
    @Controller
    public class LoginController {
    
    
        @RequestMapping("/test")
        public String welcome() {
            return "login";
        }
    }
    
    

    在地址栏中输入http://localhost:8080/test

    此时SpringMVC结构

    5.配置文件Mybaits

    新建database.properties中放置数据库连接内容

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    user=root
    password=root
    minIdle=45
    maxIdle=50
    initialSize=5
    maxActive=100
    maxWait=100
    removeAbandonedTimeout=180
    removeAbandoned=true
    

    在applicationContext-mybaits.xml中配置数据库连接,整合mybaits与springMVC,配置事务管理

    <?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:aop="http://www.springframework.org/schema/aop"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="
                http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:component-scan base-package="com.test.service"/>
        <context:component-scan base-package="com.test.dao"/>
    
        <!-- 读取数据库配置文件 -->
        <context:property-placeholder location="classpath:database.properties"/>
    
        <!-- JNDI获取数据源(使用dbcp连接池) -->
        <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 name="maxActive" value="${maxActive}"/>
            <property name="maxIdle" value="${maxIdle}"/>
            <property name="minIdle" value="${minIdle}"/>
            <property name="maxWait" value="${maxWait}"/>
            <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}"/>
            <property name="removeAbandoned" value="${removeAbandoned}"/>
            <!-- sql 心跳 -->
            <property name= "testWhileIdle" value="true"/>
            <property name= "testOnBorrow" value="false"/>
            <property name= "testOnReturn" value="false"/>
            <property name= "validationQuery" value="select 1"/>
            <property name= "timeBetweenEvictionRunsMillis" value="60000"/>
            <property name= "numTestsPerEvictionRun" value="${maxActive}"/>
        </bean>
    
        <!-- 配置mybitas SqlSessionFactoryBean-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
    
    
        <!--JDBC事务管理 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        </bean>
    
        <!--使用spring的配置自动完成创建代理织入切面的工作-->
        <aop:aspectj-autoproxy/>
        <!-- <aop:aspectj-autoproxy/>有一个proxy-target-class属性,默认为false,表示使用jdk动态代理织入增强,
        当配为<aop:aspectj-autoproxy poxy-target-class="true"/>时,表示使用CGLib动态代理技术织入增强-->
    
        <aop:config  proxy-target-class="true">
            <!--定义切点   exeuction()方法匹配模式串,(* *com.test.service..*(..))表示services类中的所有方法 -->
            <aop:pointcut expression="execution(* *com.test.service..*(..))" id="transService"/>
            <aop:advisor pointcut-ref="transService" advice-ref="txAdvice" />
        </aop:config>
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="test*"  propagation="REQUIRED" rollback-for="Exception"  />
            </tx:attributes>
        </tx:advice>
        <!-- AOP 事务处理 结束 -->
    
    
    
    </beans>
    

    mybaits-config.xml中配置mybaits相关

    <?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>
            <!-- changes from the defaults -->
            <setting name="lazyLoadingEnabled" value="false" />
        </settings>
        <typeAliases>
            <!--这里给实体类取别名,方便在mapper配置文件中使用-->
            <package name=""/>
        </typeAliases>
    
    </configuration>
    

    注意1 jdbc-mysql6.0以上的版本必须配置serverTimezone参数

    代码编写示例,登录功能

    功能描述

    在页面login.jsp填写用户名和密码信息,controller层根据路径调用方法,在数据库查询用户,如果存在的话将用户信息存放在session中,否则返回错误信息。

    Session可以作为独立的信息单独存放,可以建立Constants类来存放信息。

    1.jsp页面 login.jsp ,frame.jsp

    <%--
      Created by IntelliJ IDEA.
      User: 19781
      Date: 2020/11/15
      Time: 13:21
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Login</title>
    </head>
    <body>
        login.jsp
    <section class="loginCont"  style="text-align: center">
        <form class="loginForm" action="${pageContext.request.contextPath }/doLogin"  name="actionForm" id="actionForm"  method="post" >
            <div class="info">${error}</div>
            <div class="inputbox">
                <%--@declare id="user"--%><label for="user">用户名:</label>
                <input type="text" class="input-text" id="userCode" name="userCode" placeholder="请输入用户名" required/>
            </div>
            <div class="inputbox">
                <%--@declare id="mima"--%><label for="mima">密码:</label>
                <input type="password" id="userPassword" name="userPassword" placeholder="请输入密码" required/>
            </div>
            <div class="subBtn">
                <input type="submit" value="登录"/>
                <input type="reset" value="重置"/>
            </div>
        </form>
    </section>
    
    </body>
    </html>
    
    

    frame.jsp

    <%--
      Created by IntelliJ IDEA.
      User: 19781
      Date: 2020/11/16
      Time: 10:55
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        frame.jsp
    登录成功 ,欢迎${userSession.userName},${userSession. userCode}
    </body>
    </html>
    
    

    2.设计数据库建立用户信息表格

    创建表

    CREATE TABLE `test_user` (
      `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
      `userCode` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户编码',
      `userName` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户名称',
      `userPassword` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户密码',
      `gender` INT(10) DEFAULT NULL COMMENT '性别(1:女、 2:男)',
      `birthday` DATE DEFAULT NULL COMMENT '出生日期',
      `phone` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '手机',
      `address` VARCHAR(30) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '地址',
      PRIMARY KEY (`id`)
    ) ENGINE=INNODB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    
    insert  into `test_user`
    (`id`,`userCode`,`userName`,`userPassword`,`gender`,`birthday`,`phone`,`address`) 
    values 
    (1,'admin','系统管理员','1234567',1,'1983-10-10','13688889999','北京市海淀区成府路207号'),
    (2,'liming','李明','0000000',2,'1983-12-10','13688884457','北京市东城区前门东大街9号'),
    (5,'hanlubiao','韩路彪','0000000',2,'1984-06-05','18567542321','北京市朝阳区北辰中心12号'),
    (6,'zhanghua','张华','0000000',1,'1983-06-15','13544561111','北京市海淀区学院路61号'),
    (7,'wangyang','王洋','0000000',2,'1982-12-31','13444561124','北京市海淀区西二旗辉煌国际16层'),
    (8,'zhaoyan','赵燕','0000000',1,'1986-03-07','18098764545','北京市海淀区回龙观小区10号楼'),
    (10,'sunlei','孙磊','0000000',2,'1981-01-04','13387676765','北京市朝阳区管庄新月小区12楼'),
    (11,'sunxing','孙兴','0000000',2,'1978-03-12','13367890900','北京市朝阳区建国门南大街10号'),
    (12,'zhangchen','张晨','0000000',1,'1986-03-28','18098765434','朝阳区管庄路口北柏林爱乐三期13号楼'),
    (13,'dengchao','邓超','0000000',2,'1981-11-04','13689674534','北京市海淀区北航家属院10号楼'),
    (14,'yangguo','杨过','0000000',2,'1980-01-01','13388886623','北京市朝阳区北苑家园茉莉园20号楼'),
    (15,'zhaomin','赵敏','0000000',1,'1987-12-04','18099897657','北京市昌平区天通苑3区12号楼');
    

    3.根据表在entity中建立实体类User

    根据数据库中的表产生,使用Setter和Getter产生set和get方法

    package com.test.entity;
    
    import com.alibaba.fastjson.annotation.JSONField;
    import org.hibernate.validator.constraints.Length;
    import org.hibernate.validator.constraints.NotEmpty;
    
    import javax.validation.constraints.NotNull;
    import javax.validation.constraints.Past;
    import java.util.Date;
    
    public class User {
        private Integer id; //id
    
        @NotEmpty(message="用户编码不能为空")
        private String userCode; //用户编码
    
        @NotEmpty(message="用户名称不能为空")
        private String userName; //用户名称
    
        @NotNull(message="密码不能为空")
        @Length(min=6,max=10,message="用户密码长度为6-10")
        private String userPassword; //用户密码
    
        private Integer gender;  //性别
    
        @Past(message="必须是一个过去的时间")
        //@DateTimeFormat(pattern="yyyy-MM-dd")
        @JSONField(format="yyyy-MM-dd")
        private Date birthday;  //出生日期
        private String phone;   //电话
        private String address; //地址
        
    }
    
    

    4 新建Constants类存放session信息

    package com.test.tools;
    
    public class Constants {
        public  static final String USER_SESSION = "userSession";
        public final static String SYS_MESSAGE = "message";
    
    }
    
    

    5 编写Controller层

    需要注意,要把controller层在springMVC-servlet中注册为javaBean

    package com.test.controller;
    
    
    import com.test.entity.User;
    import com.test.service.user.UserService;
    import com.test.tools.Constants;
    import org.apache.log4j.Logger;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    
    /**
     *
     */
    @Controller
    public class LoginController {
    
        //log4j
        private  static  final Logger logger= Logger.getLogger(LoginController.class);
    
        //service层
        @Autowired
        private UserService userService;
    
        @RequestMapping("/test")
        public String welcome() {
            return "login";
        }
    
        //提交登陆表单,实现登陆功能
        @RequestMapping(value = "/doLogin")
        public String doLogin(@RequestParam(value = "userCode") String userCode,
                              @RequestParam(value = "userPassword") String password,
                              HttpSession session,
                              HttpServletRequest request){
            logger.debug("enter LoginController =====>doLogin method");
            //和数据库中的用户信息进行校验
            User loginUser = this.userService.login(userCode, password);
            if(loginUser !=null){//说明用户存在
                //使用session容器,把该用户放进去
                session.setAttribute(Constants.USER_SESSION,loginUser);
                //页面的跳转
                return "redirect:/frame";
            }else {//用户不存在
                //使用request容器,返回一个提示信息
                request.setAttribute("error","用户名或者密码错误");
                //页面的跳转
                return "login";
            }
    
        }
    
        @RequestMapping("/frame")
        public String frame(){
            return "frame";
        }
    
    }
    

    6 编写Services层

    注意要在applicationContext-mybaits.xml中注册为javaBean

    目录结构

    UserService接口

    package com.test.service.user;
    
    import com.test.entity.User;
    
    public interface UserService {
        User login(String userCode, String password);
    }
    
    

    UserServiceImpl实现

    package com.test.service.user;
    
    
    import com.test.controller.LoginController;
    import com.test.dao.user.UserMapper;
    import com.test.entity.User;
    import org.apache.log4j.Logger;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class UserServiceImpl  implements UserService{
    
        //log4j
        private  static  final Logger logger1= Logger.getLogger(UserServiceImpl.class);
    
        @Autowired
        private UserMapper userMapper;
    
    
        //登陆
        @Override
        public User login(String userCode, String password) {
    
            logger1.debug("enter UserServiceImpl  =====>login method  param: userCode="+userCode
                    +" password= "+password);
            User user = userMapper.getUserByUserCode(userCode);
            logger1.debug("enter UserServiceImpl  =====>login method  " +
                    "return: user=:user.id"+user.getId()+
                    "  user.userCode="+user.getUserCode()+
                    " user.userName="+user.getUserName());
    
            if(user!=null && !user.getUserPassword().equals(password)){
                //当用户存在,但是密码不一致,赋值为null
                user=null;
            }
            return user;
        }
    }
    
    
    

    7.编写dao层

    目录结构

    首先在applicationContext-mybaits.xml中将dao层的mapper注册为javaBean,放在最后即可。

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.test.dao" />
        </bean>
    

    UserMapper接口

    package com.test.dao.user;
    
    
    import com.test.entity.User;
    import org.apache.ibatis.annotations.Param;
    
    public interface UserMapper {
    
        //根据用户名获得用户
        public User getUserByUserCode(@Param("userCode") String userCode);
    
    }
    
    

    UserMapper.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.test.dao.user.UserMapper">
    
        <!--根据用户名获得用户-->
        <select id="getUserByUserCode" parameterType="string" resultType="User">
            select * from test_user
            <where>
                <if test="userCode!=null and userCode!=''">
                    userCode=#{userCode}
                </if>
            </where>
        </select>
    
    </mapper>
    

    注意2 在pom的build中添加resource资源,否则会找不到mapper

     <!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 -->
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
            </resources>
    

    效果

    初始界面 index.jsp

    在地址栏输入localhost:8080/test 进入登录界面login.jsp

    登录成功

    登录失败

  • 相关阅读:
    FCKEditor装入模板方法
    医道再解开阖枢
    测试一下 Last
    [技术架构] 大型互联网站解决高并发的常见策略
    swfupload实现图片及缩略图上传
    解决“在证书存储区中找不到清单签名证书”
    asp.net EnableViewState禁用与注意事项
    jQuery创建水平和垂直居中的div窗口
    甩掉ashx/asmx,使用jQuery.ajaxWebService请求WebMethod,Ajax处理更加简练
    type="button" ,"submit" 的区别(转)
  • 原文地址:https://www.cnblogs.com/zuti666/p/13987082.html
Copyright © 2020-2023  润新知