这里写目录标题
一级目录
二级目录
三级目录
一功能简介和项目最终成型效果预览:
1滑块代替验证码来控制登录注册验证
2全局拦截器:`①没有进去登录页面之前无法访问其他所有的页面(设置登录页面为主页)`,`②没有成功登录之前无法进入index页面(设置进入index页面的权限)`
①
首先访问注册页面,被拦截器拦截,然后返回登录页面.
返回login页面
在返回login页面之后,再次点击免费注册进入注册页面就不会再被拦截器拦截
②
首先进入login页面之后,再访问index页面,因为还没有登录,依然会访问失败,返回login页面
输入登录账号,并解锁登录成功,才能进入index主页面.
)
3 ①注册时验证账号是否重复注册, ,,②登录时验证账户密码是否正确以及账号状态是否被激活.
①
②
4全局异常处理器:系统发生异常时,分辨是系统内置异常或者是未知异常,并进入相应异常页面
5 前端表单格式控制验证
二项目架构
三用户sql建表
CREATE TABLE `account` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`account` varchar(255) NOT NULL DEFAULT '游客',
`password` varchar(255) DEFAULT NULL,
`enterprise` varchar(255) DEFAULT '游客',
`phone` varchar(255) DEFAULT NULL,
`mail` varchar(255) DEFAULT NULL,
`status` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
四 pom环境
<?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>org.example</groupId>
<artifactId>ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- spring4.3.2 -->
<!-- spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!-- spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!-- spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!--使用AspectJ方式注解需要相应的包 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>
<!--使用AspectJ方式注解需要相应的包 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>
<!-- mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!--数据源druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.3</version>
</dependency>
<!--mybitis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--spring事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!--springJDBC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!--mybitis-spring插件包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- 配置jsp -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
<!-- spring web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!-- spring webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!--data-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
<build>
<!-- 配置tomcat插件,web端 -->
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<!-- 配置项目的请求路径 -->
<path>/mvc</path>
<!-- 配置服务器端口号 -->
<port>9091</port>
</configuration>
</plugin>
<!-- mybatis-generator反向工程 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<!-- 在控制台打印执行日志 -->
<verbose>true</verbose>
<!-- 重复生成时会覆盖之前的文件-->
<overwrite>true</overwrite>
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
五 配置文件
mapper/AccountMapper.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="baobaobaobao.dao.AccountMapper">
<resultMap id="BaseResultMap" type="baobaobaobao.entity.Account">
<id column="Id" jdbcType="INTEGER" property="id" />
<result column="account" jdbcType="VARCHAR" property="account" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="enterprise" jdbcType="VARCHAR" property="enterprise" />
<result column="phone" jdbcType="VARCHAR" property="phone" />
<result column="mail" jdbcType="VARCHAR" property="mail" />
<result column="status" jdbcType="INTEGER" property="status" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
Id, account, password, enterprise, phone, mail,status
</sql>
<select id="selectByExample" parameterType="baobaobaobao.entity.AccountExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from account
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from account
where Id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from account
where Id = #{id,jdbcType=INTEGER}
</delete>
<delete id="deleteByExample" parameterType="baobaobaobao.entity.AccountExample">
delete from account
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="baobaobaobao.entity.Account">
insert into account (Id, account, password,
enterprise, phone, mail,status
)
values (#{id,jdbcType=INTEGER}, #{account,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{enterprise,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, #{mail,jdbcType=VARCHAR},#{status,jdbcType=INTEGER}
)
</insert>
<insert id="insertSelective" parameterType="baobaobaobao.entity.Account">
insert into account
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
Id,
</if>
<if test="account != null">
account,
</if>
<if test="password != null">
password,
</if>
<if test="enterprise != null">
enterprise,
</if>
<if test="phone != null">
phone,
</if>
<if test="mail != null">
mail,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="account != null">
#{account,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="enterprise != null">
#{enterprise,jdbcType=VARCHAR},
</if>
<if test="phone != null">
#{phone,jdbcType=VARCHAR},
</if>
<if test="mail != null">
#{mail,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="baobaobaobao.entity.AccountExample" resultType="java.lang.Long">
select count(*) from account
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update account
<set>
<if test="record.id != null">
Id = #{record.id,jdbcType=INTEGER},
</if>
<if test="record.account != null">
account = #{record.account,jdbcType=VARCHAR},
</if>
<if test="record.password != null">
password = #{record.password,jdbcType=VARCHAR},
</if>
<if test="record.enterprise != null">
enterprise = #{record.enterprise,jdbcType=VARCHAR},
</if>
<if test="record.phone != null">
phone = #{record.phone,jdbcType=VARCHAR},
</if>
<if test="record.mail != null">
mail = #{record.mail,jdbcType=VARCHAR},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update account
set Id = #{record.id,jdbcType=INTEGER},
account = #{record.account,jdbcType=VARCHAR},
password = #{record.password,jdbcType=VARCHAR},
enterprise = #{record.enterprise,jdbcType=VARCHAR},
phone = #{record.phone,jdbcType=VARCHAR},
mail = #{record.mail,jdbcType=VARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="baobaobaobao.entity.Account">
update account
<set>
<if test="account != null">
account = #{account,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="enterprise != null">
enterprise = #{enterprise,jdbcType=VARCHAR},
</if>
<if test="phone != null">
phone = #{phone,jdbcType=VARCHAR},
</if>
<if test="mail != null">
mail = #{mail,jdbcType=VARCHAR},
</if>
</set>
where Id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="baobaobaobao.entity.Account">
update account
set account = #{account,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
enterprise = #{enterprise,jdbcType=VARCHAR},
phone = #{phone,jdbcType=VARCHAR},
mail = #{mail,jdbcType=VARCHAR}
where Id = #{id,jdbcType=INTEGER}
</update>
</mapper>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.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">
<!--bean管理-->
<!--加载数据库连接属性文件-->
<context:property-placeholder location="classpath:dbConfig.properties"></context:property-placeholder>
<!--启用classpath-->
<context:component-scan base-package="baobaobaobao.service"></context:component-scan>
<!--启用事务注解-->
<tx:annotation-driven transaction-manager="txManager"></tx:annotation-driven>
<!-- 事务管理器 -->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置SqlSessionFactoryBean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatisConfig.xml"></property>
<property name="mapperLocations" value="classpath:mapper/AccountMapper.xml"></property>
</bean>
<!--因为接口无法直接被NEW出来,所以需要借用插件来扫描管理接口-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="baobaobaobao.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- 创建数据源 init-method/destroy-method -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<!-- 配置数据库连接基本信息 -->
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.name}"/>
<property name="password" value="${jdbc.password}"/>
<!-- ******配置数据库连接池相关信息******* -->
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="5"/>
<property name="minIdle" value="2"/>
<property name="maxActive" value="10"/>
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="10000"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000"/>
<property name="testWhileIdle" value="true"/>
<!-- 这里建议配置为TRUE,防止取到的连接不可用 -->
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="false"/>
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true"/>
<property name="maxPoolPreparedStatementPerConnectionSize"
value="20"/>
<!-- 这里配置提交方式,默认就是TRUE,可以不用配置 -->
<property name="defaultAutoCommit" value="true"/>
<!-- 验证连接有效与否的SQL,不同的数据配置不同 -->
<property name="validationQuery" value="select 1"/>
</bean>
</beans>
dbConfig.properties
jdbc.url=jdbc:mysql://ip:3306/数据库
jdbc.driver=com.mysql.jdbc.Driver
jdbc.name=用户名
jdbc.password=密码
generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://49.235.16.100:3306/baobaobaobao" userId="root"
password="shuang666">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成PO(实体类)类的位置 .\src为eclipse .\src\main\java 为idea 1-->
<javaModelGenerator targetPackage="baobaobaobao.entity"
targetProject=".\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置.\src为eclipse .\src\main\resourses 为idea 2-->
<sqlMapGenerator targetPackage="mapper"
targetProject=".\src\main\resources">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 .\src为eclipse .\src\main\java 为idea3-->
<javaClientGenerator type="XMLMAPPER"
targetPackage="baobaobaobao.dao"
targetProject=".\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<table schema="" tableName="account"></table>
</context>
</generatorConfiguration>
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>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="reasonable" value="true"/>
</plugin>
</plugins>
</configuration>
springmvc.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:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop.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">
<!--启用mvc注解,会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--启用注解扫描-->
<context:component-scan base-package="baobaobaobao.controller"></context:component-scan>
<!--配置静态资源的请求映射,一个*代表任意字符,**代表多级目录-->
<mvc:resources mapping="/img/**" location="/img/" > </mvc:resources>
<mvc:resources mapping="/image/**" location="/img/" > </mvc:resources>
<mvc:resources mapping="/js/**" location="/js/" ></mvc:resources>
<mvc:resources mapping="/layui/**" location="/layui/"></mvc:resources>
<mvc:resources mapping="/css/**" location="/css/"></mvc:resources>
<!--配置项目的全局异常-->
<bean class="baobaobaobao.exception.CustomExceptionResolver"></bean>
<!-- 配置拦截器(多个) -->
<mvc:interceptors>
<!-- 配置1个拦截器 -->
<mvc:interceptor>
<!-- 拦截路径 -->
<mvc:mapping path="/**/*" />
<!-- 排除拦截 -->
<mvc:exclude-mapping path="/**/*.js"/>
<mvc:exclude-mapping path="/**/*.css"/>
<mvc:exclude-mapping path="/**/*.png"/>
<mvc:exclude-mapping path="/**/*.jpeg"/>
<mvc:exclude-mapping path="/**/*.jpg"/>
<mvc:exclude-mapping path="/**/*.ico"/>
<mvc:exclude-mapping path="/**/*.woff"/>
<mvc:exclude-mapping path="/**/*.woff2"/>
<mvc:exclude-mapping path="/**/font/*"/>
<bean class="baobaobaobao.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
<!-- 配置2个拦截器 -->
<mvc:interceptor>
<!-- 拦截路径 -->
<mvc:mapping path="/" />
<!-- 排除拦截 -->
<mvc:exclude-mapping path="/"/>
<bean class="baobaobaobao.interceptor.XInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!-- <!– HandlerMapping映射处理器 –>
<!–Spring3.1开始的注解HandlerMapping –>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
<!– HandlerAdapter处理适配器 –>
<!–Spring3.1开始的注解HandlerAdapter–>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>-->
<!-- ViewResolver 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀,后缀指定跳转的位置,/代表项目根路径-->
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
六 项目后台架构
实体层
package baobaobaobao.entity;
public class Account {
private Integer id;
private String account;
private String password;
private String enterprise;
private String phone;
private String mail;
private int status;
public Account() {
}
public Account(Integer id, String account, String password, String enterprise, String phone, String mail, int status) {
this.id = id;
this.account = account;
this.password = password;
this.enterprise = enterprise;
this.phone = phone;
this.mail = mail;
this.status = status;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account == null ? null : account.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getEnterprise() {
return enterprise;
}
public void setEnterprise(String enterprise) {
this.enterprise = enterprise == null ? null : enterprise.trim();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail == null ? null : mail.trim();
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", account='" + account + '\'' +
", password='" + password + '\'' +
", enterprise='" + enterprise + '\'' +
", phone='" + phone + '\'' +
", mail='" + mail + '\'' +
", status=" + status +
'}';
}
}
package baobaobaobao.entity;
import java.util.ArrayList;
import java.util.List;
public class AccountExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public AccountExample() {
oredCriteria = new ArrayList<>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("Id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("Id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("Id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("Id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("Id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("Id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("Id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("Id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("Id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("Id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("Id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("Id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andAccountIsNull() {
addCriterion("account is null");
return (Criteria) this;
}
public Criteria andAccountIsNotNull() {
addCriterion("account is not null");
return (Criteria) this;
}
public Criteria andAccountEqualTo(String value) {
addCriterion("account =", value, "account");
return (Criteria) this;
}
public Criteria andAccountNotEqualTo(String value) {
addCriterion("account <>", value, "account");
return (Criteria) this;
}
public Criteria andAccountGreaterThan(String value) {
addCriterion("account >", value, "account");
return (Criteria) this;
}
public Criteria andAccountGreaterThanOrEqualTo(String value) {
addCriterion("account >=", value, "account");
return (Criteria) this;
}
public Criteria andAccountLessThan(String value) {
addCriterion("account <", value, "account");
return (Criteria) this;
}
public Criteria andAccountLessThanOrEqualTo(String value) {
addCriterion("account <=", value, "account");
return (Criteria) this;
}
public Criteria andAccountLike(String value) {
addCriterion("account like", value, "account");
return (Criteria) this;
}
public Criteria andAccountNotLike(String value) {
addCriterion("account not like", value, "account");
return (Criteria) this;
}
public Criteria andAccountIn(List<String> values) {
addCriterion("account in", values, "account");
return (Criteria) this;
}
public Criteria andAccountNotIn(List<String> values) {
addCriterion("account not in", values, "account");
return (Criteria) this;
}
public Criteria andAccountBetween(String value1, String value2) {
addCriterion("account between", value1, value2, "account");
return (Criteria) this;
}
public Criteria andAccountNotBetween(String value1, String value2) {
addCriterion("account not between", value1, value2, "account");
return (Criteria) this;
}
public Criteria andPasswordIsNull() {
addCriterion("password is null");
return (Criteria) this;
}
public Criteria andPasswordIsNotNull() {
addCriterion("password is not null");
return (Criteria) this;
}
public Criteria andPasswordEqualTo(String value) {
addCriterion("password =", value, "password");
return (Criteria) this;
}
public Criteria andPasswordNotEqualTo(String value) {
addCriterion("password <>", value, "password");
return (Criteria) this;
}
public Criteria andPasswordGreaterThan(String value) {
addCriterion("password >", value, "password");
return (Criteria) this;
}
public Criteria andPasswordGreaterThanOrEqualTo(String value) {
addCriterion("password >=", value, "password");
return (Criteria) this;
}
public Criteria andPasswordLessThan(String value) {
addCriterion("password <", value, "password");
return (Criteria) this;
}
public Criteria andPasswordLessThanOrEqualTo(String value) {
addCriterion("password <=", value, "password");
return (Criteria) this;
}
public Criteria andPasswordLike(String value) {
addCriterion("password like", value, "password");
return (Criteria) this;
}
public Criteria andPasswordNotLike(String value) {
addCriterion("password not like", value, "password");
return (Criteria) this;
}
public Criteria andPasswordIn(List<String> values) {
addCriterion("password in", values, "password");
return (Criteria) this;
}
public Criteria andPasswordNotIn(List<String> values) {
addCriterion("password not in", values, "password");
return (Criteria) this;
}
public Criteria andPasswordBetween(String value1, String value2) {
addCriterion("password between", value1, value2, "password");
return (Criteria) this;
}
public Criteria andPasswordNotBetween(String value1, String value2) {
addCriterion("password not between", value1, value2, "password");
return (Criteria) this;
}
public Criteria andEnterpriseIsNull() {
addCriterion("enterprise is null");
return (Criteria) this;
}
public Criteria andEnterpriseIsNotNull() {
addCriterion("enterprise is not null");
return (Criteria) this;
}
public Criteria andEnterpriseEqualTo(String value) {
addCriterion("enterprise =", value, "enterprise");
return (Criteria) this;
}
public Criteria andEnterpriseNotEqualTo(String value) {
addCriterion("enterprise <>", value, "enterprise");
return (Criteria) this;
}
public Criteria andEnterpriseGreaterThan(String value) {
addCriterion("enterprise >", value, "enterprise");
return (Criteria) this;
}
public Criteria andEnterpriseGreaterThanOrEqualTo(String value) {
addCriterion("enterprise >=", value, "enterprise");
return (Criteria) this;
}
public Criteria andEnterpriseLessThan(String value) {
addCriterion("enterprise <", value, "enterprise");
return (Criteria) this;
}
public Criteria andEnterpriseLessThanOrEqualTo(String value) {
addCriterion("enterprise <=", value, "enterprise");
return (Criteria) this;
}
public Criteria andEnterpriseLike(String value) {
addCriterion("enterprise like", value, "enterprise");
return (Criteria) this;
}
public Criteria andEnterpriseNotLike(String value) {
addCriterion("enterprise not like", value, "enterprise");
return (Criteria) this;
}
public Criteria andEnterpriseIn(List<String> values) {
addCriterion("enterprise in", values, "enterprise");
return (Criteria) this;
}
public Criteria andEnterpriseNotIn(List<String> values) {
addCriterion("enterprise not in", values, "enterprise");
return (Criteria) this;
}
public Criteria andEnterpriseBetween(String value1, String value2) {
addCriterion("enterprise between", value1, value2, "enterprise");
return (Criteria) this;
}
public Criteria andEnterpriseNotBetween(String value1, String value2) {
addCriterion("enterprise not between", value1, value2, "enterprise");
return (Criteria) this;
}
public Criteria andPhoneIsNull() {
addCriterion("phone is null");
return (Criteria) this;
}
public Criteria andPhoneIsNotNull() {
addCriterion("phone is not null");
return (Criteria) this;
}
public Criteria andPhoneEqualTo(String value) {
addCriterion("phone =", value, "phone");
return (Criteria) this;
}
public Criteria andPhoneNotEqualTo(String value) {
addCriterion("phone <>", value, "phone");
return (Criteria) this;
}
public Criteria andPhoneGreaterThan(String value) {
addCriterion("phone >", value, "phone");
return (Criteria) this;
}
public Criteria andPhoneGreaterThanOrEqualTo(String value) {
addCriterion("phone >=", value, "phone");
return (Criteria) this;
}
public Criteria andPhoneLessThan(String value) {
addCriterion("phone <", value, "phone");
return (Criteria) this;
}
public Criteria andPhoneLessThanOrEqualTo(String value) {
addCriterion("phone <=", value, "phone");
return (Criteria) this;
}
public Criteria andPhoneLike(String value) {
addCriterion("phone like", value, "phone");
return (Criteria) this;
}
public Criteria andPhoneNotLike(String value) {
addCriterion("phone not like", value, "phone");
return (Criteria) this;
}
public Criteria andPhoneIn(List<String> values) {
addCriterion("phone in", values, "phone");
return (Criteria) this;
}
public Criteria andPhoneNotIn(List<String> values) {
addCriterion("phone not in", values, "phone");
return (Criteria) this;
}
public Criteria andPhoneBetween(String value1, String value2) {
addCriterion("phone between", value1, value2, "phone");
return (Criteria) this;
}
public Criteria andPhoneNotBetween(String value1, String value2) {
addCriterion("phone not between", value1, value2, "phone");
return (Criteria) this;
}
public Criteria andMailIsNull() {
addCriterion("mail is null");
return (Criteria) this;
}
public Criteria andMailIsNotNull() {
addCriterion("mail is not null");
return (Criteria) this;
}
public Criteria andMailEqualTo(String value) {
addCriterion("mail =", value, "mail");
return (Criteria) this;
}
public Criteria andMailNotEqualTo(String value) {
addCriterion("mail <>", value, "mail");
return (Criteria) this;
}
public Criteria andMailGreaterThan(String value) {
addCriterion("mail >", value, "mail");
return (Criteria) this;
}
public Criteria andMailGreaterThanOrEqualTo(String value) {
addCriterion("mail >=", value, "mail");
return (Criteria) this;
}
public Criteria andMailLessThan(String value) {
addCriterion("mail <", value, "mail");
return (Criteria) this;
}
public Criteria andMailLessThanOrEqualTo(String value) {
addCriterion("mail <=", value, "mail");
return (Criteria) this;
}
public Criteria andMailLike(String value) {
addCriterion("mail like", value, "mail");
return (Criteria) this;
}
public Criteria andMailNotLike(String value) {
addCriterion("mail not like", value, "mail");
return (Criteria) this;
}
public Criteria andMailIn(List<String> values) {
addCriterion("mail in", values, "mail");
return (Criteria) this;
}
public Criteria andMailNotIn(List<String> values) {
addCriterion("mail not in", values, "mail");
return (Criteria) this;
}
public Criteria andMailBetween(String value1, String value2) {
addCriterion("mail between", value1, value2, "mail");
return (Criteria) this;
}
public Criteria andMailNotBetween(String value1, String value2) {
addCriterion("mail not between", value1, value2, "mail");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
dao层(数据访问层)
/*@author*/
package baobaobaobao.dao;
import baobaobaobao.entity.Account;
import baobaobaobao.entity.AccountExample;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface AccountMapper {
long countByExample(AccountExample example);
int deleteByExample(AccountExample example);
int deleteByPrimaryKey(Integer id);
int insert(Account record);
int insertSelective(Account record);
List<Account> selectByExample(AccountExample example);
Account selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") Account record, @Param("example") AccountExample example);
int updateByExample(@Param("record") Account record, @Param("example") AccountExample example);
int updateByPrimaryKeySelective(Account record);
int updateByPrimaryKey(Account record);
}
service层(业务逻辑层)
package baobaobaobao.service;
import baobaobaobao.entity.Account;
import baobaobaobao.entity.EnUser;
import java.util.List;
/**
* Created by @author LiuChunhang on 2020/4/14.
*/
public interface SSMServiceface {
//插入成功并查询的业务
public int register(Account account);
public List validate(String string);
}
package baobaobaobao.service;
import baobaobaobao.dao.AccountMapper;
import baobaobaobao.entity.Account;
import baobaobaobao.entity.AccountExample;
import baobaobaobao.entity.EnUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by @author LiuChunhang on 2020/4/22.
*/
@Service
public class AccountService implements SSMServiceface {
@Autowired
public AccountMapper accountMapper;
public AccountMapper getAccountMapper() {
return accountMapper;
}
public void setAccountMapper(AccountMapper accountMapper) {
this.accountMapper = accountMapper;
}
@Override
@Transactional
public int register(Account account) {
int insert = accountMapper.insert(account);
return insert;
}
@Override
@Transactional
public List validate(String string) {
AccountExample accountExample = new AccountExample();
AccountExample.Criteria criteria = accountExample.createCriteria();
criteria.andAccountEqualTo(string);
List<Account> accounts = accountMapper.selectByExample(accountExample);
return accounts;
}
}
controller层 (视图控制层)
package baobaobaobao.controller;
import baobaobaobao.entity.Account;
import baobaobaobao.service.AccountService;
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.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
/**
* Created by @author LiuChunhang on 2020/4/22.
*/
@Controller
public class AccountController {
@Autowired
public AccountService accountService;
public AccountService getAccountService() {
return accountService;
}
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
//登录验证
@RequestMapping(value = "loginsubmit", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView login(Account account, HttpServletResponse response, HttpSession httpSession) {
ModelAndView modelAndView = new ModelAndView();
response.setContentType("text/html;charset=UTF-8");
String s = account.getAccount();
String s1 = account.getPassword();
System.out.println(s);
System.out.println(s1);
List<Account> list = accountService.validate(s);
//查看该账号在数据库中是否存在
if (list.isEmpty() || list.size()==0) {
try {
PrintWriter out = response.getWriter();
out.flush();
out.println("<script>");
out.println("alert('账户不存在!');");
out.println("</script>");
} catch (IOException e) {
e.printStackTrace();
}
modelAndView.setViewName("login");
}
//如果存在就查看密码是否正确
else {
Account o = list.get(0);
System.out.println(o.getAccount());
System.out.println(o.getPassword());
System.out.println(o.getStatus());
if (o.getPassword().equals(s1) ) {
//0为未激活,1为已激活
if (o.getStatus() == 1) {
//登陆成功,返回index页面,并在session中设定登录状态,使拦截器不再拦截之后的页面
httpSession.setAttribute("status","2");
modelAndView.setViewName("WEB-INF/temp");
return modelAndView;
}
//如果密码正确就查看账号是否被激活
else {
try {
PrintWriter out = response.getWriter();
out.flush();
out.println("<script>");
out.println("alert('账户未激活!');");
out.println("</script>");
} catch (IOException e) {
e.printStackTrace();
}
modelAndView.setViewName("login");
}
} else {
try {
PrintWriter out = response.getWriter();
out.flush();
out.println("<script>");
out.println("alert('密码错误!');");
out.println("</script>");
} catch (IOException e) {
e.printStackTrace();
}
modelAndView.setViewName("login");
}
}
return modelAndView;
}
//注册验证
@RequestMapping(value = "registerresult", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView register(Account account, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView();
//account.setStatus(1);
String s = account.getAccount();
System.out.println(s);
List<Account> list = accountService.validate(s);
for(Account recard:list){
System.out.println(recard);
}
if (list.isEmpty() || list == null) {
int register = accountService.register(account);
System.out.println(register);
if (register > 0) {
System.out.println("插入成功");
modelAndView.setViewName("WEB-INF/registerresult");
return modelAndView;
}
} else {
modelAndView.addObject("result", "账号已被注册");
response.setContentType("text/html;charset=UTF-8");
try {
PrintWriter out = response.getWriter();
out.flush();
out.println("<script>");
out.println("alert('此用户名已存在,请重新输入!');");
out.println("</script>");
} catch (IOException e) {
e.printStackTrace();
}
modelAndView.setViewName("WEB-INF/register");
}
return modelAndView;
}
}
package baobaobaobao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Created by @author LiuChunhang on 2020/4/8.
*/
@Controller
public class ViewController{
@RequestMapping(value = "linkAdmin",method = {RequestMethod.GET,RequestMethod.POST})
public ModelAndView linkAdmin() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("WEB-INF/linkAdmin");
return modelAndView;
}
@RequestMapping(value = "loginMiss",method = {RequestMethod.GET,RequestMethod.POST})
public ModelAndView loginMiss() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("WEB-INF/loginMiss");
return modelAndView;
}
@RequestMapping(value = "findAccount",method = {RequestMethod.GET,RequestMethod.POST})
public ModelAndView handleRequest() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("shuang","xiaohang");
modelAndView.setViewName("WEB-INF/findAccount");
return modelAndView;
}
@RequestMapping(value = "index",method = {RequestMethod.GET,RequestMethod.POST})
public String test(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
System.out.println("开始请求index页面");
System.out.println("啦啦啦啦啦啦啦啦啦啦");
HttpSession session = httpServletRequest.getSession();
String status = (String) session.getAttribute("status");
if (status.equals("2")){
System.out.println("登录状态:2,可以访问index页面");
return "WEB-INF/temp";
}else {
return "WEB-INF/login";
}
}
@RequestMapping(value = "login",method = {RequestMethod.GET,RequestMethod.POST})
public ModelAndView login(HttpSession httpSession){
//登录之后设置登录状态,也可以设置session过期时长
httpSession.setAttribute("status", "1");
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("WEB-INF/login");
return modelAndView;
}
@RequestMapping(value = "register",method = {RequestMethod.GET,RequestMethod.POST})
public String validateCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
return "WEB-INF/register";
}
@RequestMapping(value = "login3",method = {RequestMethod.GET,RequestMethod.POST})
public String login2(HttpServletRequest request, HttpServletResponse response) throws Exception{
return "login";
}
}
全局拦截层
package baobaobaobao.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Created by @author LiuChunhang on 2020/4/15.
*/
//自定义拦截器
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
// 获取请求路径
String uri = httpServletRequest.getRequestURI();
if (uri.contains("login")) {// 登录操作
System.out.println(uri);
System.out.println("uri包含login,放行.");
return true;
} else {// 非登录操作,需要验证是否登录过
// 1表示已经登录 0表示未登录
System.out.println(uri);
System.out.println("uri不包含login");
HttpSession session = httpServletRequest.getSession();
String attribute = (String) session.getAttribute("status");
System.out.println("登录状态:"+attribute+"\n"+",放行");
if ("1".equals(attribute)) {
return true;
}else {
System.out.println("uri:"+uri+"\n"+"拦截器①已拦截");
httpServletResponse.sendRedirect("login");
return false;
}
}
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
package baobaobaobao.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by @author LiuChunhang on 2020/4/15.
*/
public class XInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
全局异常层
package baobaobaobao.exception;
/**
* Created by @author LiuChunhang on 2020/4/16.
*/
public class CustomException extends RuntimeException {
//描述异常信息
public String message;
public CustomException(String message) {
//调用父类的构造方法
super(message);
this.message = message;
}
@Override
public String getMessage() {
return message;
}
}
package baobaobaobao.exception;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by @author LiuChunhang on 2020/4/16.
*/
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) {
//java多态
RuntimeException c =null;
//如果抛出的是系统自定义的异常则直接转换
if(e instanceof RuntimeException) {
//java多态
c = new CustomException(e.toString());
//打印异常类型
System.out.println("系统已知错误:"+"\n"+c.getMessage());
//打印异常信息
System.out.println("异常信息如下:");
e.printStackTrace();
} else {
c = new CustomException("系统未知错误");
System.out.println(c.getMessage());
}
//向前台返回错误信息
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exceptionmessage", c.getMessage());
//页面转发exception.jsp的内容,地址栏中的地址不变.
modelAndView.setViewName("WEB-INF/exception");
return modelAndView;
}
}
七 前台css+js+html架构
formtest.js(表单和解锁验证)
var result;
$(function() {
result = $("#myform").validate({
rules: {
account: {
required: true,
maxlength: 12,
minlength: 6
},
password: {
required: true,
rangelength: [6, 12]
},
conpassword: {
required: true,
equalTo: "#password"
},
enterprise: {
required: true,
maxlength: 9,
minlength: 2
},
phone: {
required: true,
number:true,
rangelength: [11, 11]
},
mail: {
required: true,
email: true
}
/*brithday: {
required:true,
dateISO:true
},*/
},
errorPlacement: function(error, element) {
error.appendTo(element.parent());
}
});
})
function confirmform() {
if(window.x) {
return result.form();
} else {
alert("未解锁")
return false;
}
}
jquery.validate.js
/*!
* jQuery Validation Plugin v1.15.0
*
* http://jqueryvalidation.org/
*
* Copyright (c) 2016 Jörn Zaefferer
* Released under the MIT license
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
define( ["jquery"], factory );
} else if (typeof module === "object" && module.exports) {
module.exports = factory( require( "jquery" ) );
} else {
factory( jQuery );
}
}(function( $ ) {
$.extend( $.fn, {
// http://jqueryvalidation.org/validate/
validate: function( options ) {
// If nothing is selected, return nothing; can't chain anyway
if ( !this.length ) {
if ( options && options.debug && window.console ) {
console.warn( "Nothing selected, can't validate, returning nothing." );
}
return;
}
// Check if a validator for this form was already created
var validator = $.data( this[ 0 ], "validator" );
if ( validator ) {
return validator;
}
// Add novalidate tag if HTML5.
this.attr( "novalidate", "novalidate" );
validator = new $.validator( options, this[ 0 ] );
$.data( this[ 0 ], "validator", validator );
if ( validator.settings.onsubmit ) {
this.on( "click.validate", ":submit", function( event ) {
if ( validator.settings.submitHandler ) {
validator.submitButton = event.target;
}
// Allow suppressing validation by adding a cancel class to the submit button
if ( $( this ).hasClass( "cancel" ) ) {
validator.cancelSubmit = true;
}
// Allow suppressing validation by adding the html5 formnovalidate attribute to the submit button
if ( $( this ).attr( "formnovalidate" ) !== undefined ) {
validator.cancelSubmit = true;
}
} );
// Validate the form on submit
this.on( "submit.validate", function( event ) {
if ( validator.settings.debug ) {
// Prevent form submit to be able to see console output
event.preventDefault();
}
function handle() {
var hidden, result;
if ( validator.settings.submitHandler ) {
if ( validator.submitButton ) {
// Insert a hidden input as a replacement for the missing submit button
hidden = $( "<input type='hidden'/>" )
.attr( "name", validator.submitButton.name )
.val( $( validator.submitButton ).val() )
.appendTo( validator.currentForm );
}
result = validator.settings.submitHandler.call( validator, validator.currentForm, event );
if ( validator.submitButton ) {
// And clean up afterwards; thanks to no-block-scope, hidden can be referenced
hidden.remove();
}
if ( result !== undefined ) {
return result;
}
return false;
}
return true;
}
// Prevent submit for invalid forms or custom submit handlers
if ( validator.cancelSubmit ) {
validator.cancelSubmit = false;
return handle();
}
if ( validator.form() ) {
if ( validator.pendingRequest ) {
validator.formSubmitted = true;
return false;
}
return handle();
} else {
validator.focusInvalid();
return false;
}
} );
}
return validator;
},
// http://jqueryvalidation.org/valid/
valid: function() {
var valid, validator, errorList;
if ( $( this[ 0 ] ).is( "form" ) ) {
valid = this.validate().form();
} else {
errorList = [];
valid = true;
validator = $( this[ 0 ].form ).validate();
this.each( function() {
valid = validator.element( this ) && valid;
if ( !valid ) {
errorList = errorList.concat( validator.errorList );
}
} );
validator.errorList = errorList;
}
return valid;
},
// http://jqueryvalidation.org/rules/
rules: function( command, argument ) {
// If nothing is selected, return nothing; can't chain anyway
if ( !this.length ) {
return;
}
var element = this[ 0 ],
settings, staticRules, existingRules, data, param, filtered;
if ( command ) {
settings = $.data( element.form, "validator" ).settings;
staticRules = settings.rules;
existingRules = $.validator.staticRules( element );
switch ( command ) {
case "add":
$.extend( existingRules, $.validator.normalizeRule( argument ) );
// Remove messages from rules, but allow them to be set separately
delete existingRules.messages;
staticRules[ element.name ] = existingRules;
if ( argument.messages ) {
settings.messages[ element.name ] = $.extend( settings.messages[ element.name ], argument.messages );
}
break;
case "remove":
if ( !argument ) {
delete staticRules[ element.name ];
return existingRules;
}
filtered = {};
$.each( argument.split( /\s/ ), function( index, method ) {
filtered[ method ] = existingRules[ method ];
delete existingRules[ method ];
if ( method === "required" ) {
$( element ).removeAttr( "aria-required" );
}
} );
return filtered;
}
}
data = $.validator.normalizeRules(
$.extend(
{},
$.validator.classRules( element ),
$.validator.attributeRules( element ),
$.validator.dataRules( element ),
$.validator.staticRules( element )
), element );
// Make sure required is at front
if ( data.required ) {
param = data.required;
delete data.required;
data = $.extend( { required: param }, data );
$( element ).attr( "aria-required", "true" );
}
// Make sure remote is at back
if ( data.remote ) {
param = data.remote;
delete data.remote;
data = $.extend( data, { remote: param } );
}
return data;
}
} );
// Custom selectors
$.extend( $.expr[ ":" ], {
// http://jqueryvalidation.org/blank-selector/
blank: function( a ) {
return !$.trim( "" + $( a ).val() );
},
// http://jqueryvalidation.org/filled-selector/
filled: function( a ) {
var val = $( a ).val();
return val !== null && !!$.trim( "" + val );
},
// http://jqueryvalidation.org/unchecked-selector/
unchecked: function( a ) {
return !$( a ).prop( "checked" );
}
} );
// Constructor for validator
$.validator = function( options, form ) {
this.settings = $.extend( true, {}, $.validator.defaults, options );
this.currentForm = form;
this.init();
};
// http://jqueryvalidation.org/jQuery.validator.format/
$.validator.format = function( source, params ) {
if ( arguments.length === 1 ) {
return function() {
var args = $.makeArray( arguments );
args.unshift( source );
return $.validator.format.apply( this, args );
};
}
if ( params === undefined ) {
return source;
}
if ( arguments.length > 2 && params.constructor !== Array ) {
params = $.makeArray( arguments ).slice( 1 );
}
if ( params.constructor !== Array ) {
params = [ params ];
}
$.each( params, function( i, n ) {
source = source.replace( new RegExp( "\\{" + i + "\\}", "g" ), function() {
return n;
} );
} );
return source;
};
$.extend( $.validator, {
defaults: {
messages: {},
groups: {},
rules: {},
errorClass: "error",
pendingClass: "pending",
validClass: "valid",
errorElement: "label",
focusCleanup: false,
focusInvalid: true,
errorContainer: $( [] ),
errorLabelContainer: $( [] ),
onsubmit: true,
ignore: ":hidden",
ignoreTitle: false,
onfocusin: function( element ) {
this.lastActive = element;
// Hide error label and remove error class on focus if enabled
if ( this.settings.focusCleanup ) {
if ( this.settings.unhighlight ) {
this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );
}
this.hideThese( this.errorsFor( element ) );
}
},
onfocusout: function( element ) {
if ( !this.checkable( element ) && ( element.name in this.submitted || !this.optional( element ) ) ) {
this.element( element );
}
},
onkeyup: function( element, event ) {
// Avoid revalidate the field when pressing one of the following keys
// Shift => 16
// Ctrl => 17
// Alt => 18
// Caps lock => 20
// End => 35
// Home => 36
// Left arrow => 37
// Up arrow => 38
// Right arrow => 39
// Down arrow => 40
// Insert => 45
// Num lock => 144
// AltGr key => 225
var excludedKeys = [
16, 17, 18, 20, 35, 36, 37,
38, 39, 40, 45, 144, 225
];
if ( event.which === 9 && this.elementValue( element ) === "" || $.inArray( event.keyCode, excludedKeys ) !== -1 ) {
return;
} else if ( element.name in this.submitted || element.name in this.invalid ) {
this.element( element );
}
},
onclick: function( element ) {
// Click on selects, radiobuttons and checkboxes
if ( element.name in this.submitted ) {
this.element( element );
// Or option elements, check parent select in that case
} else if ( element.parentNode.name in this.submitted ) {
this.element( element.parentNode );
}
},
highlight: function( element, errorClass, validClass ) {
if ( element.type === "radio" ) {
this.findByName( element.name ).addClass( errorClass ).removeClass( validClass );
} else {
$( element ).addClass( errorClass ).removeClass( validClass );
}
},
unhighlight: function( element, errorClass, validClass ) {
if ( element.type === "radio" ) {
this.findByName( element.name ).removeClass( errorClass ).addClass( validClass );
} else {
$( element ).removeClass( errorClass ).addClass( validClass );
}
}
},
// http://jqueryvalidation.org/jQuery.validator.setDefaults/
setDefaults: function( settings ) {
$.extend( $.validator.defaults, settings );
},
messages: {
required: "必填选项",
remote: "Please fix this field.",
email: "请输入有效邮箱",
url: "Please enter a valid URL.",
date: "请输入正确的日期格式",
dateISO: "请输入邮箱地址",
number: "请输入有效号码",
digits: "请输入有效数字",
equalTo: "密码不一致",
maxlength: $.validator.format( "最多{0}个字符" ),
minlength: $.validator.format( "最少{0}个字符" ),
rangelength: $.validator.format( "填入{0}到{1}个字符" ),
range: $.validator.format( "Please enter a value between {0} and {1}." ),
max: $.validator.format( "Please enter a value less than or equal to {0}." ),
min: $.validator.format( "Please enter a value greater than or equal to {0}." ),
step: $.validator.format( "Please enter a multiple of {0}." )
},
autoCreateRanges: false,
prototype: {
init: function() {
this.labelContainer = $( this.settings.errorLabelContainer );
this.errorContext = this.labelContainer.length && this.labelContainer || $( this.currentForm );
this.containers = $( this.settings.errorContainer ).add( this.settings.errorLabelContainer );
this.submitted = {};
this.valueCache = {};
this.pendingRequest = 0;
this.pending = {};
this.invalid = {};
this.reset();
var groups = ( this.groups = {} ),
rules;
$.each( this.settings.groups, function( key, value ) {
if ( typeof value === "string" ) {
value = value.split( /\s/ );
}
$.each( value, function( index, name ) {
groups[ name ] = key;
} );
} );
rules = this.settings.rules;
$.each( rules, function( key, value ) {
rules[ key ] = $.validator.normalizeRule( value );
} );
function delegate( event ) {
var validator = $.data( this.form, "validator" ),
eventType = "on" + event.type.replace( /^validate/, "" ),
settings = validator.settings;
if ( settings[ eventType ] && !$( this ).is( settings.ignore ) ) {
settings[ eventType ].call( validator, this, event );
}
}
$( this.currentForm )
.on( "focusin.validate focusout.validate keyup.validate",
":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], " +
"[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], " +
"[type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], " +
"[type='radio'], [type='checkbox'], [contenteditable]", delegate )
// Support: Chrome, oldIE
// "select" is provided as event.target when clicking a option
.on( "click.validate", "select, option, [type='radio'], [type='checkbox']", delegate );
if ( this.settings.invalidHandler ) {
$( this.currentForm ).on( "invalid-form.validate", this.settings.invalidHandler );
}
// Add aria-required to any Static/Data/Class required fields before first validation
// Screen readers require this attribute to be present before the initial submission http://www.w3.org/TR/WCAG-TECHS/ARIA2.html
$( this.currentForm ).find( "[required], [data-rule-required], .required" ).attr( "aria-required", "true" );
},
// http://jqueryvalidation.org/Validator.form/
form: function() {
this.checkForm();
$.extend( this.submitted, this.errorMap );
this.invalid = $.extend( {}, this.errorMap );
if ( !this.valid() ) {
$( this.currentForm ).triggerHandler( "invalid-form", [ this ] );
}
this.showErrors();
return this.valid();
},
checkForm: function() {
this.prepareForm();
for ( var i = 0, elements = ( this.currentElements = this.elements() ); elements[ i ]; i++ ) {
this.check( elements[ i ] );
}
return this.valid();
},
// http://jqueryvalidation.org/Validator.element/
element: function( element ) {
var cleanElement = this.clean( element ),
checkElement = this.validationTargetFor( cleanElement ),
v = this,
result = true,
rs, group;
if ( checkElement === undefined ) {
delete this.invalid[ cleanElement.name ];
} else {
this.prepareElement( checkElement );
this.currentElements = $( checkElement );
// If this element is grouped, then validate all group elements already
// containing a value
group = this.groups[ checkElement.name ];
if ( group ) {
$.each( this.groups, function( name, testgroup ) {
if ( testgroup === group && name !== checkElement.name ) {
cleanElement = v.validationTargetFor( v.clean( v.findByName( name ) ) );
if ( cleanElement && cleanElement.name in v.invalid ) {
v.currentElements.push( cleanElement );
result = result && v.check( cleanElement );
}
}
} );
}
rs = this.check( checkElement ) !== false;
result = result && rs;
if ( rs ) {
this.invalid[ checkElement.name ] = false;
} else {
this.invalid[ checkElement.name ] = true;
}
if ( !this.numberOfInvalids() ) {
// Hide error containers on last error
this.toHide = this.toHide.add( this.containers );
}
this.showErrors();
// Add aria-invalid status for screen readers
$( element ).attr( "aria-invalid", !rs );
}
return result;
},
// http://jqueryvalidation.org/Validator.showErrors/
showErrors: function( errors ) {
if ( errors ) {
var validator = this;
// Add items to error list and map
$.extend( this.errorMap, errors );
this.errorList = $.map( this.errorMap, function( message, name ) {
return {
message: message,
element: validator.findByName( name )[ 0 ]
};
} );
// Remove items from success list
this.successList = $.grep( this.successList, function( element ) {
return !( element.name in errors );
} );
}
if ( this.settings.showErrors ) {
this.settings.showErrors.call( this, this.errorMap, this.errorList );
} else {
this.defaultShowErrors();
}
},
// http://jqueryvalidation.org/Validator.resetForm/
resetForm: function() {
if ( $.fn.resetForm ) {
$( this.currentForm ).resetForm();
}
this.invalid = {};
this.submitted = {};
this.prepareForm();
this.hideErrors();
var elements = this.elements()
.removeData( "previousValue" )
.removeAttr( "aria-invalid" );
this.resetElements( elements );
},
resetElements: function( elements ) {
var i;
if ( this.settings.unhighlight ) {
for ( i = 0; elements[ i ]; i++ ) {
this.settings.unhighlight.call( this, elements[ i ],
this.settings.errorClass, "" );
this.findByName( elements[ i ].name ).removeClass( this.settings.validClass );
}
} else {
elements
.removeClass( this.settings.errorClass )
.removeClass( this.settings.validClass );
}
},
numberOfInvalids: function() {
return this.objectLength( this.invalid );
},
objectLength: function( obj ) {
/* jshint unused: false */
var count = 0,
i;
for ( i in obj ) {
if ( obj[ i ] ) {
count++;
}
}
return count;
},
hideErrors: function() {
this.hideThese( this.toHide );
},
hideThese: function( errors ) {
errors.not( this.containers ).text( "" );
this.addWrapper( errors ).hide();
},
valid: function() {
return this.size() === 0;
},
size: function() {
return this.errorList.length;
},
focusInvalid: function() {
if ( this.settings.focusInvalid ) {
try {
$( this.findLastActive() || this.errorList.length && this.errorList[ 0 ].element || [] )
.filter( ":visible" )
.focus()
// Manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
.trigger( "focusin" );
} catch ( e ) {
// Ignore IE throwing errors when focusing hidden elements
}
}
},
findLastActive: function() {
var lastActive = this.lastActive;
return lastActive && $.grep( this.errorList, function( n ) {
return n.element.name === lastActive.name;
} ).length === 1 && lastActive;
},
elements: function() {
var validator = this,
rulesCache = {};
// Select all valid inputs inside the form (no submit or reset buttons)
return $( this.currentForm )
.find( "input, select, textarea, [contenteditable]" )
.not( ":submit, :reset, :image, :disabled" )
.not( this.settings.ignore )
.filter( function() {
var name = this.name || $( this ).attr( "name" ); // For contenteditable
if ( !name && validator.settings.debug && window.console ) {
console.error( "%o has no name assigned", this );
}
// Set form expando on contenteditable
if ( this.hasAttribute( "contenteditable" ) ) {
this.form = $( this ).closest( "form" )[ 0 ];
}
// Select only the first element for each name, and only those with rules specified
if ( name in rulesCache || !validator.objectLength( $( this ).rules() ) ) {
return false;
}
rulesCache[ name ] = true;
return true;
} );
},
clean: function( selector ) {
return $( selector )[ 0 ];
},
errors: function() {
var errorClass = this.settings.errorClass.split( " " ).join( "." );
return $( this.settings.errorElement + "." + errorClass, this.errorContext );
},
resetInternals: function() {
this.successList = [];
this.errorList = [];
this.errorMap = {};
this.toShow = $( [] );
this.toHide = $( [] );
},
reset: function() {
this.resetInternals();
this.currentElements = $( [] );
},
prepareForm: function() {
this.reset();
this.toHide = this.errors().add( this.containers );
},
prepareElement: function( element ) {
this.reset();
this.toHide = this.errorsFor( element );
},
elementValue: function( element ) {
var $element = $( element ),
type = element.type,
val, idx;
if ( type === "radio" || type === "checkbox" ) {
return this.findByName( element.name ).filter( ":checked" ).val();
} else if ( type === "number" && typeof element.validity !== "undefined" ) {
return element.validity.badInput ? "NaN" : $element.val();
}
if ( element.hasAttribute( "contenteditable" ) ) {
val = $element.text();
} else {
val = $element.val();
}
if ( type === "file" ) {
// Modern browser (chrome & safari)
if ( val.substr( 0, 12 ) === "C:\\fakepath\\" ) {
return val.substr( 12 );
}
// Legacy browsers
// Unix-based path
idx = val.lastIndexOf( "/" );
if ( idx >= 0 ) {
return val.substr( idx + 1 );
}
// Windows-based path
idx = val.lastIndexOf( "\\" );
if ( idx >= 0 ) {
return val.substr( idx + 1 );
}
// Just the file name
return val;
}
if ( typeof val === "string" ) {
return val.replace( /\r/g, "" );
}
return val;
},
check: function( element ) {
element = this.validationTargetFor( this.clean( element ) );
var rules = $( element ).rules(),
rulesCount = $.map( rules, function( n, i ) {
return i;
} ).length,
dependencyMismatch = false,
val = this.elementValue( element ),
result, method, rule;
// If a normalizer is defined for this element, then
// call it to retreive the changed value instead
// of using the real one.
// Note that `this` in the normalizer is `element`.
if ( typeof rules.normalizer === "function" ) {
val = rules.normalizer.call( element, val );
if ( typeof val !== "string" ) {
throw new TypeError( "The normalizer should return a string value." );
}
// Delete the normalizer from rules to avoid treating
// it as a pre-defined method.
delete rules.normalizer;
}
for ( method in rules ) {
rule = { method: method, parameters: rules[ method ] };
try {
result = $.validator.methods[ method ].call( this, val, element, rule.parameters );
// If a method indicates that the field is optional and therefore valid,
// don't mark it as valid when there are no other rules
if ( result === "dependency-mismatch" && rulesCount === 1 ) {
dependencyMismatch = true;
continue;
}
dependencyMismatch = false;
if ( result === "pending" ) {
this.toHide = this.toHide.not( this.errorsFor( element ) );
return;
}
if ( !result ) {
this.formatAndAdd( element, rule );
return false;
}
} catch ( e ) {
if ( this.settings.debug && window.console ) {
console.log( "Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.", e );
}
if ( e instanceof TypeError ) {
e.message += ". Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.";
}
throw e;
}
}
if ( dependencyMismatch ) {
return;
}
if ( this.objectLength( rules ) ) {
this.successList.push( element );
}
return true;
},
// Return the custom message for the given element and validation method
// specified in the element's HTML5 data attribute
// return the generic message if present and no method specific message is present
customDataMessage: function( element, method ) {
return $( element ).data( "msg" + method.charAt( 0 ).toUpperCase() +
method.substring( 1 ).toLowerCase() ) || $( element ).data( "msg" );
},
// Return the custom message for the given element name and validation method
customMessage: function( name, method ) {
var m = this.settings.messages[ name ];
return m && ( m.constructor === String ? m : m[ method ] );
},
// Return the first defined argument, allowing empty strings
findDefined: function() {
for ( var i = 0; i < arguments.length; i++ ) {
if ( arguments[ i ] !== undefined ) {
return arguments[ i ];
}
}
return undefined;
},
defaultMessage: function( element, rule ) {
var message = this.findDefined(
this.customMessage( element.name, rule.method ),
this.customDataMessage( element, rule.method ),
// 'title' is never undefined, so handle empty string as undefined
!this.settings.ignoreTitle && element.title || undefined,
$.validator.messages[ rule.method ],
"<strong>Warning: No message defined for " + element.name + "</strong>"
),
theregex = /\$?\{(\d+)\}/g;
if ( typeof message === "function" ) {
message = message.call( this, rule.parameters, element );
} else if ( theregex.test( message ) ) {
message = $.validator.format( message.replace( theregex, "{$1}" ), rule.parameters );
}
return message;
},
formatAndAdd: function( element, rule ) {
var message = this.defaultMessage( element, rule );
this.errorList.push( {
message: message,
element: element,
method: rule.method
} );
this.errorMap[ element.name ] = message;
this.submitted[ element.name ] = message;
},
addWrapper: function( toToggle ) {
if ( this.settings.wrapper ) {
toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );
}
return toToggle;
},
defaultShowErrors: function() {
var i, elements, error;
for ( i = 0; this.errorList[ i ]; i++ ) {
error = this.errorList[ i ];
if ( this.settings.highlight ) {
this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
}
this.showLabel( error.element, error.message );
}
if ( this.errorList.length ) {
this.toShow = this.toShow.add( this.containers );
}
if ( this.settings.success ) {
for ( i = 0; this.successList[ i ]; i++ ) {
this.showLabel( this.successList[ i ] );
}
}
if ( this.settings.unhighlight ) {
for ( i = 0, elements = this.validElements(); elements[ i ]; i++ ) {
this.settings.unhighlight.call( this, elements[ i ], this.settings.errorClass, this.settings.validClass );
}
}
this.toHide = this.toHide.not( this.toShow );
this.hideErrors();
this.addWrapper( this.toShow ).show();
},
validElements: function() {
return this.currentElements.not( this.invalidElements() );
},
invalidElements: function() {
return $( this.errorList ).map( function() {
return this.element;
} );
},
showLabel: function( element, message ) {
var place, group, errorID, v,
error = this.errorsFor( element ),
elementID = this.idOrName( element ),
describedBy = $( element ).attr( "aria-describedby" );
if ( error.length ) {
// Refresh error/success class
error.removeClass( this.settings.validClass ).addClass( this.settings.errorClass );
// Replace message on existing label
error.html( message );
} else {
// Create error element
error = $( "<" + this.settings.errorElement + ">" )
.attr( "id", elementID + "-error" )
.addClass( this.settings.errorClass )
.html( message || "" );
// Maintain reference to the element to be placed into the DOM
place = error;
if ( this.settings.wrapper ) {
// Make sure the element is visible, even in IE
// actually showing the wrapped element is handled elsewhere
place = error.hide().show().wrap( "<" + this.settings.wrapper + "/>" ).parent();
}
if ( this.labelContainer.length ) {
this.labelContainer.append( place );
} else if ( this.settings.errorPlacement ) {
this.settings.errorPlacement( place, $( element ) );
} else {
place.insertAfter( element );
}
// Link error back to the element
if ( error.is( "label" ) ) {
// If the error is a label, then associate using 'for'
error.attr( "for", elementID );
// If the element is not a child of an associated label, then it's necessary
// to explicitly apply aria-describedby
} else if ( error.parents( "label[for='" + this.escapeCssMeta( elementID ) + "']" ).length === 0 ) {
errorID = error.attr( "id" );
// Respect existing non-error aria-describedby
if ( !describedBy ) {
describedBy = errorID;
} else if ( !describedBy.match( new RegExp( "\\b" + this.escapeCssMeta( errorID ) + "\\b" ) ) ) {
// Add to end of list if not already present
describedBy += " " + errorID;
}
$( element ).attr( "aria-describedby", describedBy );
// If this element is grouped, then assign to all elements in the same group
group = this.groups[ element.name ];
if ( group ) {
v = this;
$.each( v.groups, function( name, testgroup ) {
if ( testgroup === group ) {
$( "[name='" + v.escapeCssMeta( name ) + "']", v.currentForm )
.attr( "aria-describedby", error.attr( "id" ) );
}
} );
}
}
}
if ( !message && this.settings.success ) {
error.text( "" );
if ( typeof this.settings.success === "string" ) {
error.addClass( this.settings.success );
} else {
this.settings.success( error, element );
}
}
this.toShow = this.toShow.add( error );
},
errorsFor: function( element ) {
var name = this.escapeCssMeta( this.idOrName( element ) ),
describer = $( element ).attr( "aria-describedby" ),
selector = "label[for='" + name + "'], label[for='" + name + "'] *";
// 'aria-describedby' should directly reference the error element
if ( describer ) {
selector = selector + ", #" + this.escapeCssMeta( describer )
.replace( /\s+/g, ", #" );
}
return this
.errors()
.filter( selector );
},
// See https://api.jquery.com/category/selectors/, for CSS
// meta-characters that should be escaped in order to be used with JQuery
// as a literal part of a name/id or any selector.
escapeCssMeta: function( string ) {
return string.replace( /([\\!"#$%&'()*+,./:;<=>?@\[\]^`{|}~])/g, "\\$1" );
},
idOrName: function( element ) {
return this.groups[ element.name ] || ( this.checkable( element ) ? element.name : element.id || element.name );
},
validationTargetFor: function( element ) {
// If radio/checkbox, validate first element in group instead
if ( this.checkable( element ) ) {
element = this.findByName( element.name );
}
// Always apply ignore filter
return $( element ).not( this.settings.ignore )[ 0 ];
},
checkable: function( element ) {
return ( /radio|checkbox/i ).test( element.type );
},
findByName: function( name ) {
return $( this.currentForm ).find( "[name='" + this.escapeCssMeta( name ) + "']" );
},
getLength: function( value, element ) {
switch ( element.nodeName.toLowerCase() ) {
case "select":
return $( "option:selected", element ).length;
case "input":
if ( this.checkable( element ) ) {
return this.findByName( element.name ).filter( ":checked" ).length;
}
}
return value.length;
},
depend: function( param, element ) {
return this.dependTypes[ typeof param ] ? this.dependTypes[ typeof param ]( param, element ) : true;
},
dependTypes: {
"boolean": function( param ) {
return param;
},
"string": function( param, element ) {
return !!$( param, element.form ).length;
},
"function": function( param, element ) {
return param( element );
}
},
optional: function( element ) {
var val = this.elementValue( element );
return !$.validator.methods.required.call( this, val, element ) && "dependency-mismatch";
},
startRequest: function( element ) {
if ( !this.pending[ element.name ] ) {
this.pendingRequest++;
$( element ).addClass( this.settings.pendingClass );
this.pending[ element.name ] = true;
}
},
stopRequest: function( element, valid ) {
this.pendingRequest--;
// Sometimes synchronization fails, make sure pendingRequest is never < 0
if ( this.pendingRequest < 0 ) {
this.pendingRequest = 0;
}
delete this.pending[ element.name ];
$( element ).removeClass( this.settings.pendingClass );
if ( valid && this.pendingRequest === 0 && this.formSubmitted && this.form() ) {
$( this.currentForm ).submit();
this.formSubmitted = false;
} else if ( !valid && this.pendingRequest === 0 && this.formSubmitted ) {
$( this.currentForm ).triggerHandler( "invalid-form", [ this ] );
this.formSubmitted = false;
}
},
previousValue: function( element, method ) {
return $.data( element, "previousValue" ) || $.data( element, "previousValue", {
old: null,
valid: true,
message: this.defaultMessage( element, { method: method } )
} );
},
// Cleans up all forms and elements, removes validator-specific events
destroy: function() {
this.resetForm();
$( this.currentForm )
.off( ".validate" )
.removeData( "validator" )
.find( ".validate-equalTo-blur" )
.off( ".validate-equalTo" )
.removeClass( "validate-equalTo-blur" );
}
},
classRuleSettings: {
required: { required: true },
email: { email: true },
url: { url: true },
date: { date: true },
dateISO: { dateISO: true },
number: { number: true },
digits: { digits: true },
creditcard: { creditcard: true }
},
addClassRules: function( className, rules ) {
if ( className.constructor === String ) {
this.classRuleSettings[ className ] = rules;
} else {
$.extend( this.classRuleSettings, className );
}
},
classRules: function( element ) {
var rules = {},
classes = $( element ).attr( "class" );
if ( classes ) {
$.each( classes.split( " " ), function() {
if ( this in $.validator.classRuleSettings ) {
$.extend( rules, $.validator.classRuleSettings[ this ] );
}
} );
}
return rules;
},
normalizeAttributeRule: function( rules, type, method, value ) {
// Convert the value to a number for number inputs, and for text for backwards compability
// allows type="date" and others to be compared as strings
if ( /min|max|step/.test( method ) && ( type === null || /number|range|text/.test( type ) ) ) {
value = Number( value );
// Support Opera Mini, which returns NaN for undefined minlength
if ( isNaN( value ) ) {
value = undefined;
}
}
if ( value || value === 0 ) {
rules[ method ] = value;
} else if ( type === method && type !== "range" ) {
// Exception: the jquery validate 'range' method
// does not test for the html5 'range' type
rules[ method ] = true;
}
},
attributeRules: function( element ) {
var rules = {},
$element = $( element ),
type = element.getAttribute( "type" ),
method, value;
for ( method in $.validator.methods ) {
// Support for <input required> in both html5 and older browsers
if ( method === "required" ) {
value = element.getAttribute( method );
// Some browsers return an empty string for the required attribute
// and non-HTML5 browsers might have required="" markup
if ( value === "" ) {
value = true;
}
// Force non-HTML5 browsers to return bool
value = !!value;
} else {
value = $element.attr( method );
}
this.normalizeAttributeRule( rules, type, method, value );
}
// 'maxlength' may be returned as -1, 2147483647 ( IE ) and 524288 ( safari ) for text inputs
if ( rules.maxlength && /-1|2147483647|524288/.test( rules.maxlength ) ) {
delete rules.maxlength;
}
return rules;
},
dataRules: function( element ) {
var rules = {},
$element = $( element ),
type = element.getAttribute( "type" ),
method, value;
for ( method in $.validator.methods ) {
value = $element.data( "rule" + method.charAt( 0 ).toUpperCase() + method.substring( 1 ).toLowerCase() );
this.normalizeAttributeRule( rules, type, method, value );
}
return rules;
},
staticRules: function( element ) {
var rules = {},
validator = $.data( element.form, "validator" );
if ( validator.settings.rules ) {
rules = $.validator.normalizeRule( validator.settings.rules[ element.name ] ) || {};
}
return rules;
},
normalizeRules: function( rules, element ) {
// Handle dependency check
$.each( rules, function( prop, val ) {
// Ignore rule when param is explicitly false, eg. required:false
if ( val === false ) {
delete rules[ prop ];
return;
}
if ( val.param || val.depends ) {
var keepRule = true;
switch ( typeof val.depends ) {
case "string":
keepRule = !!$( val.depends, element.form ).length;
break;
case "function":
keepRule = val.depends.call( element, element );
break;
}
if ( keepRule ) {
rules[ prop ] = val.param !== undefined ? val.param : true;
} else {
$.data( element.form, "validator" ).resetElements( $( element ) );
delete rules[ prop ];
}
}
} );
// Evaluate parameters
$.each( rules, function( rule, parameter ) {
rules[ rule ] = $.isFunction( parameter ) && rule !== "normalizer" ? parameter( element ) : parameter;
} );
// Clean number parameters
$.each( [ "minlength", "maxlength" ], function() {
if ( rules[ this ] ) {
rules[ this ] = Number( rules[ this ] );
}
} );
$.each( [ "rangelength", "range" ], function() {
var parts;
if ( rules[ this ] ) {
if ( $.isArray( rules[ this ] ) ) {
rules[ this ] = [ Number( rules[ this ][ 0 ] ), Number( rules[ this ][ 1 ] ) ];
} else if ( typeof rules[ this ] === "string" ) {
parts = rules[ this ].replace( /[\[\]]/g, "" ).split( /[\s,]+/ );
rules[ this ] = [ Number( parts[ 0 ] ), Number( parts[ 1 ] ) ];
}
}
} );
if ( $.validator.autoCreateRanges ) {
// Auto-create ranges
if ( rules.min != null && rules.max != null ) {
rules.range = [ rules.min, rules.max ];
delete rules.min;
delete rules.max;
}
if ( rules.minlength != null && rules.maxlength != null ) {
rules.rangelength = [ rules.minlength, rules.maxlength ];
delete rules.minlength;
delete rules.maxlength;
}
}
return rules;
},
// Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
normalizeRule: function( data ) {
if ( typeof data === "string" ) {
var transformed = {};
$.each( data.split( /\s/ ), function() {
transformed[ this ] = true;
} );
data = transformed;
}
return data;
},
// http://jqueryvalidation.org/jQuery.validator.addMethod/
addMethod: function( name, method, message ) {
$.validator.methods[ name ] = method;
$.validator.messages[ name ] = message !== undefined ? message : $.validator.messages[ name ];
if ( method.length < 3 ) {
$.validator.addClassRules( name, $.validator.normalizeRule( name ) );
}
},
// http://jqueryvalidation.org/jQuery.validator.methods/
methods: {
// http://jqueryvalidation.org/required-method/
required: function( value, element, param ) {
// Check if dependency is met
if ( !this.depend( param, element ) ) {
return "dependency-mismatch";
}
if ( element.nodeName.toLowerCase() === "select" ) {
// Could be an array for select-multiple or a string, both are fine this way
var val = $( element ).val();
return val && val.length > 0;
}
if ( this.checkable( element ) ) {
return this.getLength( value, element ) > 0;
}
return value.length > 0;
},
// http://jqueryvalidation.org/email-method/
email: function( value, element ) {
// From https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address
// Retrieved 2014-01-14
// If you have a problem with this implementation, report a bug against the above spec
// Or use custom methods to implement your own email validation
return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test( value );
},
// http://jqueryvalidation.org/url-method/
url: function( value, element ) {
// Copyright (c) 2010-2013 Diego Perini, MIT licensed
// https://gist.github.com/dperini/729294
// see also https://mathiasbynens.be/demo/url-regex
// modified to allow protocol-relative URLs
return this.optional( element ) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test( value );
},
// http://jqueryvalidation.org/date-method/
date: function( value, element ) {
return this.optional( element ) || !/Invalid|NaN/.test( new Date( value ).toString() );
},
// http://jqueryvalidation.org/dateISO-method/
dateISO: function( value, element ) {
return this.optional( element ) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test( value );
},
// http://jqueryvalidation.org/number-method/
number: function( value, element ) {
return this.optional( element ) || /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test( value );
},
// http://jqueryvalidation.org/digits-method/
digits: function( value, element ) {
return this.optional( element ) || /^\d+$/.test( value );
},
// http://jqueryvalidation.org/minlength-method/
minlength: function( value, element, param ) {
var length = $.isArray( value ) ? value.length : this.getLength( value, element );
return this.optional( element ) || length >= param;
},
// http://jqueryvalidation.org/maxlength-method/
maxlength: function( value, element, param ) {
var length = $.isArray( value ) ? value.length : this.getLength( value, element );
return this.optional( element ) || length <= param;
},
// http://jqueryvalidation.org/rangelength-method/
rangelength: function( value, element, param ) {
var length = $.isArray( value ) ? value.length : this.getLength( value, element );
return this.optional( element ) || ( length >= param[ 0 ] && length <= param[ 1 ] );
},
// http://jqueryvalidation.org/min-method/
min: function( value, element, param ) {
return this.optional( element ) || value >= param;
},
// http://jqueryvalidation.org/max-method/
max: function( value, element, param ) {
return this.optional( element ) || value <= param;
},
// http://jqueryvalidation.org/range-method/
range: function( value, element, param ) {
return this.optional( element ) || ( value >= param[ 0 ] && value <= param[ 1 ] );
},
// http://jqueryvalidation.org/step-method/
step: function( value, element, param ) {
var type = $( element ).attr( "type" ),
errorMessage = "Step attribute on input type " + type + " is not supported.",
supportedTypes = [ "text", "number", "range" ],
re = new RegExp( "\\b" + type + "\\b" ),
notSupported = type && !re.test( supportedTypes.join() );
// Works only for text, number and range input types
// TODO find a way to support input types date, datetime, datetime-local, month, time and week
if ( notSupported ) {
throw new Error( errorMessage );
}
return this.optional( element ) || ( value % param === 0 );
},
// http://jqueryvalidation.org/equalTo-method/
equalTo: function( value, element, param ) {
// Bind to the blur event of the target in order to revalidate whenever the target field is updated
var target = $( param );
if ( this.settings.onfocusout && target.not( ".validate-equalTo-blur" ).length ) {
target.addClass( "validate-equalTo-blur" ).on( "blur.validate-equalTo", function() {
$( element ).valid();
} );
}
return value === target.val();
},
// http://jqueryvalidation.org/remote-method/
remote: function( value, element, param, method ) {
if ( this.optional( element ) ) {
return "dependency-mismatch";
}
method = typeof method === "string" && method || "remote";
var previous = this.previousValue( element, method ),
validator, data, optionDataString;
if ( !this.settings.messages[ element.name ] ) {
this.settings.messages[ element.name ] = {};
}
previous.originalMessage = previous.originalMessage || this.settings.messages[ element.name ][ method ];
this.settings.messages[ element.name ][ method ] = previous.message;
param = typeof param === "string" && { url: param } || param;
optionDataString = $.param( $.extend( { data: value }, param.data ) );
if ( previous.old === optionDataString ) {
return previous.valid;
}
previous.old = optionDataString;
validator = this;
this.startRequest( element );
data = {};
data[ element.name ] = value;
$.ajax( $.extend( true, {
mode: "abort",
port: "validate" + element.name,
dataType: "json",
data: data,
context: validator.currentForm,
success: function( response ) {
var valid = response === true || response === "true",
errors, message, submitted;
validator.settings.messages[ element.name ][ method ] = previous.originalMessage;
if ( valid ) {
submitted = validator.formSubmitted;
validator.resetInternals();
validator.toHide = validator.errorsFor( element );
validator.formSubmitted = submitted;
validator.successList.push( element );
validator.invalid[ element.name ] = false;
validator.showErrors();
} else {
errors = {};
message = response || validator.defaultMessage( element, { method: method, parameters: value } );
errors[ element.name ] = previous.message = message;
validator.invalid[ element.name ] = true;
validator.showErrors( errors );
}
previous.valid = valid;
validator.stopRequest( element, valid );
}
}, param ) );
return "pending";
}
}
} );
// Ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
var pendingRequests = {},
ajax;
// Use a prefilter if available (1.5+)
if ( $.ajaxPrefilter ) {
$.ajaxPrefilter( function( settings, _, xhr ) {
var port = settings.port;
if ( settings.mode === "abort" ) {
if ( pendingRequests[ port ] ) {
pendingRequests[ port ].abort();
}
pendingRequests[ port ] = xhr;
}
} );
} else {
// Proxy ajax
ajax = $.ajax;
$.ajax = function( settings ) {
var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
port = ( "port" in settings ? settings : $.ajaxSettings ).port;
if ( mode === "abort" ) {
if ( pendingRequests[ port ] ) {
pendingRequests[ port ].abort();
}
pendingRequests[ port ] = ajax.apply( this, arguments );
return pendingRequests[ port ];
}
return ajax.apply( this, arguments );
};
}
}));
jparticle.jquery.js(互动粒子页面特效)
引入方式
<div class="layui-canvs"></div>
(function initJParticle( $ ){
"use strict";
var createParticlesSandbox, Utils;
Utils = {};
/*
* Create jParticle animation.
* @param {Object} options Few jParticle options.
* @return {Object} jQuery object for chaining.
*/
$.fn.jParticle = function jParticle( options ){
this.each(function( _, el ){
if ( typeof el.sandbox === 'object' ) {
$( el ).removeJParticle();
}
el.sandbox = createParticlesSandbox( el, options );
});
return this;
};
/*
* Remove jParticle canvas.
* @return {Object} jQuery object for chaining.
*/
$.fn.removeJParticle = function removeJParticle(){
this.each(function( _, el ){
if ( el.sandbox ) {
el.sandbox.remove();
delete el.sandbox;
}
});
return this;
};
/*
* Freeze jParticle animation.
* @return {Object} jQuery object for chaining.
*/
$.fn.freezeJParticle = function freezeJParticle(){
this.each(function( _, el ){
if ( el.sandbox ) {
el.sandbox.freeze();
}
});
return this;
};
/*
* Unfreeze jParticle animation.
* @return {Object} jQuery object for chaining.
*/
$.fn.unfreezeJParticle = function unfreezeJParticle(){
this.each(function( _, el ){
if ( el.sandbox ) {
el.sandbox.unfreeze();
}
});
return this;
};
/*
* Create a particles sandbox instance.
* @param {Object} element Element for the sandbox.
* @param {Object} params Few sandbox's params.
* @return {Object} Particles sandbox object.
*/
createParticlesSandbox = function createParticlesSandbox( element, params ){
var ParticlesSandbox, createParticle;
ParticlesSandbox = {};
ParticlesSandbox.canvas = {};
ParticlesSandbox.mouse = {};
ParticlesSandbox.particles = [];
ParticlesSandbox.isAnimated = false;
/*
* Initialize the sandbox
* @param {Object} element Element for the sandbox.
* @param {Object} params Few sandbox's params.
*/
ParticlesSandbox.initialize = function initialize( element, params ){
ParticlesSandbox.initParams( params );
ParticlesSandbox.initHTML( element );
ParticlesSandbox.initParticles();
ParticlesSandbox.initEvents();
ParticlesSandbox.initAnimation();
};
/*
* Initialize sandbox's params.
* @param {Object} params Few sandbox's params.
*/
ParticlesSandbox.initParams = function initParams( params ){
if ( params && params.color && (!params.particle || ( params.particle && !params.particle.color ) ) ) {
if ( !params.particle ) {
params.particle = {};
}
params.particle.color = params.color;
}
ParticlesSandbox.params = $.extend({
particlesNumber: 100,
linkDist: 50,
createLinkDist: 150,
disableLinks: false,
disableMouse: false,
background: 'black',
color: 'white',
width: null,
height: null,
linksWidth: 1
}, params );
};
/*
* Initialize the sandbox's html.
* @param {Object} element Element for the sandbox.
*/
ParticlesSandbox.initHTML = function initHTML( element ){
var canvas;
canvas = ParticlesSandbox.canvas;
canvas.container = $( element );
canvas.element = $('<canvas/>');
canvas.context = canvas.element.get(0).getContext('2d');
canvas.container.append( canvas.element );
canvas.element.css( 'display', 'block' );
canvas.element.get(0).width = ( ParticlesSandbox.params.width ) ? ParticlesSandbox.params.width : canvas.container.width();
canvas.element.get(0).height = ( ParticlesSandbox.params.height ) ? ParticlesSandbox.params.height : canvas.container.height();
canvas.element.css( 'background', ParticlesSandbox.params.background );
};
/*
* Resize canvas.
*/
ParticlesSandbox.resize = function resize( width, height ){
if ( width ) {
canvas.element.get(0).width = width;
}
if ( height ) {
canvas.element.get(0).height = height;
}
};
/*
* Create all particles in the sandbox.
*/
ParticlesSandbox.initParticles = function initParticles(){
var i, count;
i = 0;
count = ParticlesSandbox.params.particlesNumber;
for ( ; i < count; i += 1 ) {
ParticlesSandbox.particles.push( createParticle(
ParticlesSandbox.canvas.element.get(0),
ParticlesSandbox.params.particle
) );
}
};
/*
* Initialize the sandbox's events.
*/
ParticlesSandbox.initEvents = function initEvents(){
ParticlesSandbox.canvas.element.mouseenter(function mouseEnterCallback(){
ParticlesSandbox.mouse.hoverCanvas = true;
if ( !ParticlesSandbox.isAnimated ) {
ParticlesSandbox.draw();
}
});
ParticlesSandbox.canvas.element.mouseleave(function mouseLeaveCallback(){
ParticlesSandbox.mouse.hoverCanvas = false;
});
ParticlesSandbox.canvas.element.mousemove(function mouseMoveCallback(e){
ParticlesSandbox.mouse = $.extend( ParticlesSandbox.mouse, Utils.getMousePosition( e, ParticlesSandbox.canvas.element[0] ) );
});
};
/*
* Initialize the sandbox's animation.
*/
ParticlesSandbox.initAnimation = function initAnimation(){
window.requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.ORequestAnimationFrame ||
window.msRequestAnimationFrame ||
function requestAnimFrame( callback ){
setTimeOut( callback, 1000/60 );
};
ParticlesSandbox.isAnimated = true;
ParticlesSandbox.draw();
};
/*
* Draw the sandbox canvas.
*/
ParticlesSandbox.draw = function draw(){
var i, j, count, canvas, particle, particle2;
i = 0;
count = ParticlesSandbox.particles.length;
canvas = ParticlesSandbox.canvas;
canvas.context.clearRect( 0, 0, canvas.element.get(0).width, canvas.element.get(0).height );
for ( ; i < count; i += 1 ) {
particle = ParticlesSandbox.particles[i];
if ( ParticlesSandbox.isAnimated ) {
particle.update();
}
particle.draw();
if ( !ParticlesSandbox.params.disableMouse && ParticlesSandbox.mouse.hoverCanvas ) {
ParticlesSandbox.drawLink(
particle.getPosition('x'),
particle.getPosition('y'),
ParticlesSandbox.mouse.x,
ParticlesSandbox.mouse.y
);
}
if ( !ParticlesSandbox.params.disableLinks ) {
for ( j = i+1; j < count; j += 1 ) {
particle2 = ParticlesSandbox.particles[j];
ParticlesSandbox.drawLink(
particle.getPosition('x'),
particle.getPosition('y'),
particle2.getPosition('x'),
particle2.getPosition('y')
);
}
}
}
ParticlesSandbox.requestID = window.requestAnimFrame( ParticlesSandbox.draw );
};
/*
* Draw a link between two particles.
* @param {int} x First object abscissa coords.
* @param {int} y First object ordered coords.
* @param {int} x2 Second object abscissa coords.
* @param {int} y2 Second object ordered coords.
*/
ParticlesSandbox.drawLink = function drawLink( x, y, x2, y2 ){
var context;
if ( Utils.getDistance( x, y, x2, y2 ) <= ParticlesSandbox.params.createLinkDist ) {
context = ParticlesSandbox.canvas.context;
context.save();
context.beginPath();
context.lineWidth = ParticlesSandbox.params.linksWidth;
context.moveTo( x, y );
context.lineTo( x2, y2 );
context.globalAlpha = ParticlesSandbox.getOpacityLink( x, y, x2, y2 );
context.strokeStyle = ParticlesSandbox.params.color;
context.lineCap = 'round';
context.stroke();
context.closePath();
context.restore();
}
};
/*
* Get opacity for link two particles.
* @param {int} x First object abscissa coords.
* @param {int} y First object ordered coords.
* @param {int} x2 Second object abscissa coords.
* @param {int} y2 Second object ordered coords.
* @return {int} 0 <= opacity <= 1
*/
ParticlesSandbox.getOpacityLink = function getOpacityLink( x, y, x2, y2 ){
var dist, opacity, linkDist, createLinkDist;
dist = Utils.getDistance( x, y, x2, y2 );
linkDist = ParticlesSandbox.params.linkDist;
createLinkDist = ParticlesSandbox.params.createLinkDist;
if ( dist <= linkDist ) {
opacity = 1;
} else if ( dist > createLinkDist ) {
opacity = 0;
} else {
opacity = 1 - ( ( ( dist - linkDist ) * 100 ) / ( createLinkDist - linkDist ) ) / 100;
}
return opacity;
};
/*
* Freeze the animation.
*/
ParticlesSandbox.freeze = function freeze(){
if ( ParticlesSandbox.isAnimated ) {
ParticlesSandbox.isAnimated = false;
}
};
/*
* Unfreeze the animation.
*/
ParticlesSandbox.unfreeze = function unfreeze(){
if ( !ParticlesSandbox.isAnimated ) {
ParticlesSandbox.isAnimated = true;
}
};
/*
* Remove the animation's canvas.
*/
ParticlesSandbox.remove = function remove(){
ParticlesSandbox.canvas.element.remove();
};
/*
* Create a particle instance.
* @param {Object} canvas DOM element.
* @param {Object} params Few particle's params.
* @return {Object} Particle object.
*/
createParticle = function createParticle( canvas, params ){
var Particle;
Particle = {};
Particle.canvas = {};
Particle.vector = {};
/*
* Initialize the particle.
* @param {Object} canvas DOM element.
* @param {Object} params Few particle's params.
*/
Particle.initialize = function initialize( canvas, params ){
Particle.params = $.extend({
color: 'white',
minSize: 2,
maxSize: 4,
speed: 60
}, params );
Particle.setCanvasContext( canvas );
Particle.initSize();
Particle.initPosition();
Particle.initVectors();
};
/*
* Initialize particle's position.
*/
Particle.initPosition = function initPosition(){
Particle.x = Utils.getRandNumber( 0 + Particle.radius, Particle.canvas.element.width - Particle.radius );
Particle.y = Utils.getRandNumber( 0 + Particle.radius, Particle.canvas.element.height - Particle.radius );
};
/*
* Initialize particle's size.
*/
Particle.initSize = function initSize(){
Particle.size = Utils.getRandNumber( Particle.params.minSize, Particle.params.maxSize );
Particle.radius = Particle.size / 2;
};
/*
* Initialize particle's vectors for speed.
*/
Particle.initVectors = function initVectors(){
do {
Particle.vector.x = Utils.getRandNumber( -Particle.params.speed / 60, Particle.params.speed / 60, false );
Particle.vector.y = Utils.getRandNumber( -Particle.params.speed / 60, Particle.params.speed / 60, false );
} while ( Particle.vector.x == 0 || Particle.vector.y == 0 )
};
/*
* Set the context to draw particles.
* @param {Object} canvas Canvas.
*/
Particle.setCanvasContext = function setCanvasContext( canvas ){
var context;
Particle.canvas.element = canvas;
context = canvas.getContext('2d');
if ( typeof context === 'object' && typeof context.canvas === 'object' ) {
Particle.canvas.context = context;
} else {
throw "Error: Can't set canvas context to Particle because context isn't a CanvasRenderingContext2D object.";
}
};
/*
* Draw particle.
*/
Particle.draw = function draw(){
var context = Particle.canvas.context;
context.beginPath();
context.arc( Particle.x, Particle.y, Particle.size /2, 0, Math.PI*2 );
context.fillStyle = Particle.params.color;
context.fill();
context.closePath();
};
/*
* Update the particle's position.
*/
Particle.update = function update(){
Particle.x += Particle.vector.x;
Particle.y += Particle.vector.y;
if ( 0 > ( Particle.x - Particle.radius ) || ( Particle.x + Particle.radius ) > Particle.canvas.element.width ) {
Particle.vector.x = -Particle.vector.x;
}
if ( 0 > ( Particle.y - Particle.radius ) || ( Particle.y + Particle.radius ) > Particle.canvas.element.height ) {
Particle.vector.y = -Particle.vector.y;
}
};
/*
* Return position of particle.
* @param {string} axis Optionnal axis.
* @return {int|Object} Return object if axis is not defined, else return int.
*/
Particle.getPosition = function getPosition( axis ){
if ( typeof axis === 'string' && ( axis != 'x' && axis != 'y' ) ) {
axis = null;
}
return ( typeof( axis ) === 'string' ) ? Particle[ axis ] : { x: Particle.x, y: Particle.y };
};
Particle.initialize( canvas, params );
return {
getPosition: Particle.getPosition,
update: Particle.update,
draw: Particle.draw
};
};
ParticlesSandbox.initialize( element, params );
return {
remove: ParticlesSandbox.remove,
freeze: ParticlesSandbox.freeze,
unfreeze: ParticlesSandbox.unfreeze,
resize: ParticlesSandbox.resize
};
};
/*
* Get rand number between x and y.
* @param {int} x Minimal number.
* @param {int} y Maximal number.
* @param {Boolean} round True is value shouldn't be round.
* @return {int} Rand number.
*/
Utils.getRandNumber = function getRandNumber( x, y, round ){
var value;
if( x == null ) {
x = 0;
}
if( y == null ) {
y = 10;
}
if( round == null ) {
round = true;
}
value = Math.random() * ( y - x ) + x;
return ( round ) ? Math.round( value ) : value;
};
/*
* Get distance between to cartesian points.
* @param {int} x First object abscissa coords.
* @param {int} y First object ordered coords.
* @param {int} x2 Second object abscissa coords.
* @param {int} y2 Second object ordered coords.
* @return {int} Distance.
*/
Utils.getDistance = function getDistance( x, y, x2, y2 ){
return Math.sqrt( Math.pow( x2 - x, 2 ) + Math.pow( y2 - y, 2 ) );
};
/*
* Get mouse position.
* @param {Object} event The HTML DOM events.
* @param {Object} element The DOM element.
* @return {Object} x/y position.
*/
Utils.getMousePosition = function getMousePosition( event, element ){
var rect;
if ( typeof element === 'undefined' ) {
element = $('body')[0];
}
rect = element.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
};
})( jQuery )
register.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/4/21
Time: 15:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>广告投放推荐系统</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">
<!-- load css -->
<link rel="stylesheet" type="text/css" href="layui/css/layui.css" media="all">
<link rel="stylesheet" type="text/css" href="css/loginto.css" media="all">
<style>
*{
padding: 0;
margin: 0;
}
#box{
align-content: center;
position:absolute;
width: 368px;
height: 42px;
margin: 0 auto;
margin-top: 0px;
background-color: #5cbdaa;
box-shadow: 1px 1px 5px rgba(0,0,0,0.2);
}
.bgColor{
position: absolute;
left:0;
top:0;
width:42px;
height: 42px;
background-color: lightblue;
}
.txt{
position: absolute;
width: 100%;
height: 42px;
line-height: 40px;
font-size: 18px;
color: #000;
text-align: center;
}
.slider{
position: absolute;
left:0;
top:0;
width: 50px;
height: 42px;
border: 1px solid #ccc;
background: #fff;
text-align: center;
cursor: move;
}
.slider>i{
position: absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
}
.slider.active>i{
color:#5cbdaa;
}
</style>
</head>
<body>
<div class="layui-canvs"></div>
<div class="layui-layout layui-layout-login">
<h1> <strong>智慧型广告投放推荐系统</strong> <em>@201612211214刘春航</em> </h1>
<form id="myform" action="${pageContext.request.contextPath}/registerresult" method="post" onsubmit="return confirmform()">
<div class="layui-user-icon larry-login">
<input type="text" placeholder="账号" class="login_txtbx" name="account" id="account"/>
</div>
<div class="layui-pwd-icon larry-login">
<input type="text" placeholder="密码" class="login_txtbx" name="password" id="password"/>
</div>
<div class="layui-pwd-icon larry-login">
<input type="text" placeholder="确认密码" class="login_txtbx" name="conpassword" id="conpassword"/>
</div>
<div class="layui-pwd-icon larry-login">
<input type="text" placeholder="企业名称" class="login_txtbx"name="enterprise" id="enterprise"/>
</div>
<div class="layui-pwd-icon larry-login">
<input type="text" placeholder="电话" class="login_txtbx" name="phone" id="phone"/>
</div>
<div class="layui-pwd-icon larry-login">
<input type="text" placeholder="邮箱" class="login_txtbx" name="mail" id="mail"/>
</div>
<div class="layui-val-icon larry-login">
<div id="box">
<div class="bgColor"></div>
<div class="txt" >滑动解锁</div>
<!--给i标签添加上相应字体图标的类名即可-->
<div class="slider"><i class="iconfont icon-double-right"></i></div>
</div>
</div>
<div class="layui-submit larry-login">
<input type="submit" type="button" value="立即注册" class="submit_btn" onclick="" />
</div>
</form>
<div class="layui-login-text">
<p>©2016-2020 河南工程学院 版权所有</p>
<p>豫ICP备20004232号</p>
</div>
</div>
<script type="text/javascript" src="layui/lay/dest/layui.all.js"></script>
<script type="text/javascript" src="js/login.js"></script>
<script type="text/javascript" src="js/jparticle.jquery.js"></script>
<script type="text/javascript" src="js/jquery.validate.js"></script>
<script type="text/javascript" src="js/formtest.js" ></script>
<script type="text/javascript">
$(function(){
$(".layui-canvs").jParticle({
background: "#141414",
color: "#E6E6E6"
});
});
//一、定义了一个获取元素的方法
function getEle(selector){
return document.querySelector(selector);
}
//二、获取到需要用到的DOM元素
var box = getEle("#box"),//容器
bgColor = getEle(".bgColor"),//背景色
txt = getEle(".txt"),//文本
slider = getEle(".slider"),//滑块
icon = getEle(".slider>i"),
successMoveDistance = box.offsetWidth- slider.offsetWidth,//解锁需要滑动的距离
downX,//用于存放鼠标按下时的位置
isSuccess = false;//是否解锁成功的标志,默认不成功
//三、给滑块添加鼠标按下事件
slider.onmousedown = mousedownHandler;
//3.1鼠标按下事件的方法实现
function mousedownHandler(e){
bgColor.style.transition = "";
slider.style.transition = "";
var e = e || window.event || e.which;
downX = e.clientX;
//在鼠标按下时,分别给鼠标添加移动和松开事件
document.onmousemove = mousemoveHandler;
document.onmouseup = mouseupHandler;
};
//四、定义一个获取鼠标当前需要移动多少距离的方法
function getOffsetX(offset,min,max){
if(offset < min){
offset = min;
}else if(offset > max){
offset = max;
}
return offset;
}
//3.1.1鼠标移动事件的方法实现
function mousemoveHandler(e){
var e = e || window.event || e.which;
var moveX = e.clientX;
var offsetX = getOffsetX(moveX - downX,0,successMoveDistance);
bgColor.style.width = offsetX + "px";
slider.style.left = offsetX + "px";
if(offsetX == successMoveDistance){
success();
}
//如果不设置滑块滑动时会出现问题(目前还不知道为什么)
e.preventDefault();
};
//3.1.2鼠标松开事件的方法实现
function mouseupHandler(e){
if(!isSuccess){
bgColor.style.width = 0 + "px";
slider.style.left = 0 + "px";
bgColor.style.transition = "width 0.8s linear";
slider.style.transition = "left 0.8s linear";
window.x=false;
alert(x);
alert("解锁失败,请重新滑动");
}
document.onmousemove = null;
document.onmouseup = null;
};
//五、定义一个滑块解锁成功的方法
function success(){
isSuccess= true;
txt.innerHTML = "解锁成功";
window.x=true;
bgColor.style.backgroundColor ="#5cbdaa";
slider.className = "slider active";
icon.className = "iconfont icon-xuanzhong";
//滑动成功时,移除鼠标按下事件和鼠标移动事件
slider.onmousedown = null;
document.onmousemove = null;
};
</script>
</body>
</html>
八 项目前后端所有完整资源
csdn下载:暂无
github下载:暂无