springmvc+mybatis 實現登陸、註冊、郵件激活等功能

原創做品, 轉載請註明來源👉https://www.cnblogs.com/sogeisetsu/p/12933370.html
css

8 一個真實的開發總結

8.1 網站地址

http://106.14.162.154:8086/html

8.2 代碼文件

https://github.com/sogeisetsu/springstudyy/tree/master/sptumvc-07java

sql建表

show databases ;
create database if not exists springstudy character set utf8;
use springstudy;
create table `User` (
                        `uid` int primary key ,
                        `username` varchar(20) not null ,
                        `password` varchar(20) not null ,
                        `status` char(1),
                        `code` varchar(50),
                        constraint check_status check ( status='Y'or 'N')
);
show tables ;
desc User;
alter table User modify uid int auto_increment;
alter table User modify uid int auto_increment;
alter table User modify username varchar(20) unique not null ;

alter table User add `date` DATETIME;
alter table User add `email` varchar(25);

表格結構

Field Type Null Key Default Extra
uid int(11) NO PRI NULL auto_increment
username varchar(20) NO UNI NULL
password varchar(20) NO NULL
status char(1) YES NULL
code varchar(50) YES NULL
date datetime YES NULL
email varchar(25) YES NULL

配置文件關係圖

導包

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">
<!--靜態資源的名字和controller的路徑名字相同,須要特殊配置讓其走tomcat默認的servlet-->
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/login.html</url-pattern>
    <url-pattern>/regist.html</url-pattern>
  </servlet-mapping>
<!--  配置spring的DispatcherServlet-->
  <servlet>
    <servlet-name>springmvc06</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:Beans.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc06</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
<!--配置字符編碼-->

  <filter>
    <filter-name>filterForCharSet</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>forceRequestEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>forceResponseEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>filterForCharSet</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

<!--  配置session存活時間-->
  <session-config>
    <session-timeout>40</session-timeout>
  </session-config>
<!--  配置初始頁面-->
  <welcome-file-list>
    <welcome-file>login.html</welcome-file>
  </welcome-file-list>

  <error-page>
    <error-code>404</error-code>
    <location>/error/sea-404page.html</location>
  </error-page>
  <error-page>
    <error-code>405</error-code>
    <location>/error/405.html</location>
  </error-page>
  <error-page>
    <error-code>500</error-code>
    <location>/error/500.html</location>
  </error-page>
</web-app>

springmvc 配置(springmvcconfig.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: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/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="org.suyuesheng.spring7"/>
    <!--        @Response亂碼問題解決-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" >
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/plain;charset=utf-8</value>
                            <value>text/html;charset=UTF-8</value>
                            <value>applicaiton/*;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

數據庫配置(mybatisBean.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://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/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
    <context:component-scan base-package="org.suyuesheng.spring7"/>
    <context:annotation-config/>
    <import resource="springmvcconfig.xml"/>
<!--    引入配置文件-->
    <context:property-placeholder location="classpath:druid.properties"/>
<!--    datasource-->
<!--    鏈接池 druid-->
    <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.name}"/>
        <property name="password" value="${jdbc.password}"/>

        <property name="initialSize" value="${jdbc.initialSize}"/>
        <property name="minIdle" value="${jdbc.minIdle}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>

        <property name="maxWait" value="${jdbc.maxWait}"/>

        <property name="timeBetweenEvictionRunsMillis" value="${jbbc.timeBetweenEvictionRunsMillis}"/>
        <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/>

        <property name="validationQuery" value="${jdbc.validationQuery}"/>
        <property name="testWhileIdle" value="true"/>
    </bean>
<!--    sqlsessionFactory-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatisConfig.xml"/>
        <property name="mapperLocations" value="classpath:org/suyuesheng/spring7/mapper/*.xml"/>
    </bean>
<!--sqlsession-->
<!--    MapperScannerConfigurer會自動代理,其實不用配置-->
<!--    <bean class="org.mybatis.spring.SqlSessionTemplate" id="sqlSessionTemplate" scope="prototype">-->
<!--        <constructor-arg index="0" ref="sqlSessionFactory"/>-->
<!--    </bean>-->

    <!--    自動代理mapper接口-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="org.suyuesheng.spring7.mapper"/>
    </bean>

    <bean class="org.suyuesheng.spring7.services.UserService" id="userservice">
        <property name="userMapper" ref="userMapper"/>
    </bean>

<!--    配置事務管理器-->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>



    <tx:advice transaction-manager="transactionManager" id="interceptor">
        <tx:attributes >
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <aop:config proxy-target-class="true">
        <aop:pointcut id="tx" expression="execution(* org.suyuesheng.spring7.services.*.*(..))"/>
        <aop:advisor advice-ref="interceptor" pointcut-ref="tx"/>
    </aop:config>
</beans>

druid鏈接池配置 (druid.properties)

jdbc.url=jdbc:mysql://106.14.162.154:3306/springstudy?characterEncoding=utf-8&useUnicode=true
jdbc.name=root
jdbc.password=密碼是常規密碼
jdbc.initialSize=5
jdbc.minIdle=5
jdbc.maxActive=10
jdbc.maxWait=10000
#配置間隔多久啓動一次DestroyThread,對鏈接池內的鏈接才進行一次檢測,單位是毫秒
#檢測時:1.若是鏈接空閒而且超過minIdle之外的鏈接,若是空閒時間超過minEvictableIdleTimeMillis設置的值則直接物理關閉。
#     2.在minIdle之內的不處理。
jbbc.timeBetweenEvictionRunsMillis=600000
#配置一個鏈接在池中最大空閒時間,單位是毫秒
jdbc.minEvictableIdleTimeMillis=300000
#用來檢測鏈接是否有效的sql,要求是一個查詢語句,經常使用select 'x'。若是validationQuery爲null,testOnBorrow、testOnReturn、testWhileIdle都不會起做用。
#mysql select 1
#oracle select 1 from dual
jdbc.validationQuery=select 1
#建議配置爲true,不影響性能,而且保證安全性。申請鏈接的時候檢測,若是空閒時間大於timeBetweenEvictionRunsMillis,執行validationQuery檢測鏈接是否有效。
jdbc.testWhileIdle=true

數據庫配置 (mybatisConfig.xml)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <setting name="logImpl" value="LOG4J"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="cacheEnabled" value="true"/>
    </settings>
    <typeAliases>
        <package name="org.suyuesheng.spring7.pojo"/>
    </typeAliases>
</configuration>

Beans.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: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/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="org.suyuesheng.spring7"/>
    <import resource="mybatisBean.xml"/>
    <import resource="springmvcconfig.xml"/>
    <bean class="org.suyuesheng.spring7.pojo.User" id="user"/>
<!--    配置攔截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/"/>
            <mvc:mapping path="/**"/>
            <mvc:mapping path="/**/*.html"/>
            <mvc:mapping path="/index.html"/>
            <mvc:exclude-mapping path="/login*"/>
            <mvc:exclude-mapping path="/regist*"/>
            <mvc:exclude-mapping path="/**/*.js"/>
            <mvc:exclude-mapping path="/**/*.css"/>
            <mvc:exclude-mapping path="/bootstrap-3.3.7-dist/**"/>
            <mvc:exclude-mapping path="/img/**"/>
            <mvc:exclude-mapping path="/active"/>
            <bean class="org.suyuesheng.spring7.interceptor.Logininterceptor" id="logininterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

8.3 開發過程當中遇到的問題

druid配置相關資料

https://my.oschina.net/xzfx/blog/478482mysql

https://www.jianshu.com/p/e75d73129f51git

https://blog.csdn.net/sjtu_chenchen/article/details/77618967github

MapperScannerConfigurer配置

http://www.javashuo.com/article/p-yugsmipu-p.htmlweb

aop中的propagation的7種配置的意思

https://my.oschina.net/wangyongzhi/blog/631200spring

下面是Spring中Propagation類的事務屬性詳解:
REQUIRED:支持當前事務,若是當前沒有事務,就新建一個事務。這是最多見的選擇。
SUPPORTS:支持當前事務,若是當前沒有事務,就以非事務方式執行。
MANDATORY:支持當前事務,若是當前沒有事務,就拋出異常。
REQUIRES_NEW:新建事務,若是當前存在事務,把當前事務掛起。
NOT_SUPPORTED:以非事務方式執行操做,若是當前存在事務,就把當前事務掛起。
NEVER:以非事務方式執行,若是當前存在事務,則拋出異常。
NESTED:支持當前事務,若是當前事務存在,則執行一個嵌套事務,若是當前沒有事務,就新建一個事務。sql

spring mvc路徑匹配原則

靜態資源和controller重名

靜態資源的名字和controller的路徑名字相同,須要特殊配置讓其走tomcat默認的servlet數據庫

好比說有個靜態資源叫hello.html 有個controller的路徑是/hello。那麼訪問localhost/hello.html的時候會自動跳轉到localhost/hello。爲了不這種現像,須要在web.xml裏面定義👇

<!--靜態資源的名字和controller的路徑名字相同,須要特殊配置讓其走tomcat默認的servlet-->
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/login.html</url-pattern>
    <url-pattern>/regist.html</url-pattern>
  </servlet-mapping>

mvc:interceptors攔截器的用法

mvc:interceptors攔截器的用法

阿里雲服務器25端口的問題

Could not connect to SMTP host: smtp.163.com, port: 25,阿里雲服務器封禁了25,解決辦法是使用465端口👇

package org.suyuesheng.spring7.util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 發郵件工具類
 */
public final class MailUtils {
    private static final String USER = "sys088519@163.com"; // 發件人稱號,同郵箱地址
    private static final String PASSWORD = "受權碼"; // 若是是qq郵箱可使戶端受權碼,或者登陸密碼

    /**
     *
     * @param to 收件人郵箱
     * @param text 郵件正文
     * @param title 標題
     */
    /* 發送驗證信息的郵件 */
    public static boolean sendMail(String to, String text, String title){
        try {
            final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            final Properties props = new Properties();
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", "smtp.163.com");
            props.setProperty("mail.smtp.port", "465");
            props.setProperty("mail.smtp.socketFactory.port", "465");
            // 發件人的帳號
            props.put("mail.user", USER);
            //發件人的密碼
            props.put("mail.password", PASSWORD);

            // 構建受權信息,用於進行SMTP進行身份驗證
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用戶名、密碼
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用環境屬性和受權信息,建立郵件會話
            Session mailSession = Session.getInstance(props, authenticator);

            // 建立郵件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 設置發件人
            String username = props.getProperty("mail.user");
            /**
             * 發件人地址:sys088519@163.com
             * 發件人姓名:節能減排小組
             */
            InternetAddress form = new InternetAddress(username, "節能減排小組");
            message.setFrom(form);
            // 設置收件人
            InternetAddress toAddress = new InternetAddress(to);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            // 設置郵件標題
            message.setSubject(title);

            // 設置郵件的內容體
            message.setContent(text, "text/html;charset=UTF-8");
            // 發送郵件
            Transport.send(message);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) throws Exception { // 作測試用
        MailUtils.sendMail("1446942825@qq.com","<h1>測試郵件,無須回覆</h1><hr><p>這是一封測試郵件</p>","測試");
        System.out.println("發送成功");
    }



}

使用465端口還有一個證書的問題👉[javax.net.ssl.SSLException](http://javax.net.ssl.sslexception/): java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty解決辦法是👉https://blog.csdn.net/yu849893679/article/details/86081562

tomcat的項目,不一樣端口訪問的問題

https://blog.csdn.net/gang_strong/article/details/29415301

相關文章
相關標籤/搜索