在本文中,我们将为您详细介绍springMVC+mybatis+mysql学习心得的相关知识,此外,我们还会提供一些关于Ajax+SpringMVC+Spring+Mybatis+MySql+js用户
在本文中,我们将为您详细介绍springMVC+mybatis+mysql学习心得的相关知识,此外,我们还会提供一些关于Ajax+SpringMVC+Spring+Mybatis+MySql+js用户注册实例、maven 整合 spring+springmvc+mybatis+mysql、maven+springmvc+spring+mybatis+mysql详细搭建整合过程讲解、Spring MVC +MyBatis +MySQL 登录查询Demo 解决了mybatis异常【转】的有用信息。
本文目录一览:- springMVC+mybatis+mysql学习心得
- Ajax+SpringMVC+Spring+Mybatis+MySql+js用户注册实例
- maven 整合 spring+springmvc+mybatis+mysql
- maven+springmvc+spring+mybatis+mysql详细搭建整合过程讲解
- Spring MVC +MyBatis +MySQL 登录查询Demo 解决了mybatis异常【转】
MyBatis 是一个可以自定义SQL、存储过程和高级映射的持久层框架。
MyBatis 摒除了大部分的JDBC代码、手工设置参数和结果集重获。
MyBatis 只使用简单的XML 和注解来配置和映射基本数据类型、Map 接口和POJO 到数据库记录。
相对Hibernate和Apache OJB等“一站式”ORM解决方案而言,Mybatis 是一种“半自动化”的ORM实现。
需要使用的Jar包:mybatis-3.0.2.jar(mybatis核心包),mybatis-spring-1.0.0.jar(与Spring结合包)。
MyBatis+Spring+MySql简单配置过程:
(1)搭建Spring环境:加入Spring框架、配置文件,加入所需要的jar包,更改web.xml和spring的配置文件,添加jsp页面和对应的Controller。
(2)在MySql中创建数据库和相应的表;
(3)创建实体Bean,Bean与数据库映射的SQLMap文件;
(4)创建数据访问Dao接口的类;
(5)Ibatis总配置文件,sqlMapConfig.xml;
(6)修改Spring 的配置文件,需要指定配置文件位置和dataSource,数据访问接口对应的实现bean。
林炳文Evankaka原创作品。转载请注明出处http://www.jb51.cc/tag/http://blog.csdn.net/evankaka
摘要:这几天研究了下Ajax注册的方法,通过在注册时输入用户名或邮箱等,就可以判断这个用户是否存在,以免用户来注册,然后提交了,系统才提示该用户名或邮箱不可用。使用Ajax便可实现这一功能,看了网上的都是PHP的,想想索性来写一个SpringMVC+Spring+Mybatis的。文章内容用到了很多技术,包括javascript、jquery、json、e表达式等。
本文工程免费下载
先来看看最终效果:
注册成功的样子:
注册过程中参数的检验:
下面,让我们开始这次的编程吧!
首先,数据库准备,新建一张用户表,并自己插入一些数据
CREATE TABLE t_user ( USER_ID INT NOT NULL AUTO_INCREMENT,USER_NAME CHAr(30) NOT NULL,USER_PASSWORD CHAr(10) NOT NULL,USER_EMAIL CHAr(30) NOT NULL,PRIMARY KEY (USER_ID) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;好,数据库建好了,接下来就是整个工程了。
项目类型:Dynamic Web Project
开发环境:
Eclipse Java EE IDE for Web Developers.
Version: Luna Service Release 2 (4.4.2)
Build id: 20150219-0600
JDK版本:
jdk1.6.0_45
本文工程免费下载
工程的其它参数:
json使用的包。这里下载
spring+sprngMvc的包。
mybatis的包
MysqL连接的包
logger的包(日记 打印的)
如下:
jquery-1.11.3.min.js
这是还没有展开的
然后把各个都展开:
其中src放置java的文件、config放置SpringMVC+Spring+Mybatis的配置文件以及日记打印的log4j.properties
web-inf下面:js用来放置调用 的js文件,lib就是最上面说的jar包的位置,view是各个jsp文件
这里分了5层,按照标准的web工程来
这里是使用Mybatis Generator自动生成的:User.java
package com.lin.domain; public class User { private Integer userId; private String userName; private String userPassword; private String userEmail; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword == null ? null : userPassword.trim(); } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail == null ? null : userEmail.trim(); } }然后还有一个example文件:UserExample.java
package com.lin.domain; import java.util.ArrayList; import java.util.List; public class UserExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public UserExample() { oredCriteria = new ArrayList<Criteria>(); } 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<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } 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 andUserIdisNull() { addCriterion("USER_ID is null"); return (Criteria) this; } public Criteria andUserIdisNotNull() { addCriterion("USER_ID is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Integer value) { addCriterion("USER_ID =",value,"userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Integer value) { addCriterion("USER_ID <>","userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Integer value) { addCriterion("USER_ID >","userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanorEqualTo(Integer value) { addCriterion("USER_ID >=","userId"); return (Criteria) this; } public Criteria andUserIdLessthan(Integer value) { addCriterion("USER_ID <","userId"); return (Criteria) this; } public Criteria andUserIdLessthanorEqualTo(Integer value) { addCriterion("USER_ID <=","userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Integer> values) { addCriterion("USER_ID in",values,"userId"); return (Criteria) this; } public Criteria andUserIdnotin(List<Integer> values) { addCriterion("USER_ID not in","userId"); return (Criteria) this; } public Criteria andUserIdBetween(Integer value1,Integer value2) { addCriterion("USER_ID between",value2,"userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Integer value1,Integer value2) { addCriterion("USER_ID not between","userId"); return (Criteria) this; } public Criteria andUserNameIsNull() { addCriterion("USER_NAME is null"); return (Criteria) this; } public Criteria andUserNameIsNotNull() { addCriterion("USER_NAME is not null"); return (Criteria) this; } public Criteria andUserNameEqualTo(String value) { addCriterion("USER_NAME =","userName"); return (Criteria) this; } public Criteria andUserNameNotEqualTo(String value) { addCriterion("USER_NAME <>","userName"); return (Criteria) this; } public Criteria andUserNameGreaterThan(String value) { addCriterion("USER_NAME >","userName"); return (Criteria) this; } public Criteria andUserNameGreaterThanorEqualTo(String value) { addCriterion("USER_NAME >=","userName"); return (Criteria) this; } public Criteria andUserNameLessthan(String value) { addCriterion("USER_NAME <","userName"); return (Criteria) this; } public Criteria andUserNameLessthanorEqualTo(String value) { addCriterion("USER_NAME <=","userName"); return (Criteria) this; } public Criteria andUserNameLike(String value) { addCriterion("USER_NAME like","userName"); return (Criteria) this; } public Criteria andUserNameNotLike(String value) { addCriterion("USER_NAME not like","userName"); return (Criteria) this; } public Criteria andUserNameIn(List<String> values) { addCriterion("USER_NAME in","userName"); return (Criteria) this; } public Criteria andUserNamenotin(List<String> values) { addCriterion("USER_NAME not in","userName"); return (Criteria) this; } public Criteria andUserNameBetween(String value1,String value2) { addCriterion("USER_NAME between","userName"); return (Criteria) this; } public Criteria andUserNameNotBetween(String value1,String value2) { addCriterion("USER_NAME not between","userName"); return (Criteria) this; } public Criteria andUserPasswordisNull() { addCriterion("USER_PASSWORD is null"); return (Criteria) this; } public Criteria andUserPasswordisNotNull() { addCriterion("USER_PASSWORD is not null"); return (Criteria) this; } public Criteria andUserPasswordEqualTo(String value) { addCriterion("USER_PASSWORD =","userPassword"); return (Criteria) this; } public Criteria andUserPasswordNotEqualTo(String value) { addCriterion("USER_PASSWORD <>","userPassword"); return (Criteria) this; } public Criteria andUserPasswordGreaterThan(String value) { addCriterion("USER_PASSWORD >","userPassword"); return (Criteria) this; } public Criteria andUserPasswordGreaterThanorEqualTo(String value) { addCriterion("USER_PASSWORD >=","userPassword"); return (Criteria) this; } public Criteria andUserPasswordLessthan(String value) { addCriterion("USER_PASSWORD <","userPassword"); return (Criteria) this; } public Criteria andUserPasswordLessthanorEqualTo(String value) { addCriterion("USER_PASSWORD <=","userPassword"); return (Criteria) this; } public Criteria andUserPasswordLike(String value) { addCriterion("USER_PASSWORD like","userPassword"); return (Criteria) this; } public Criteria andUserPasswordNotLike(String value) { addCriterion("USER_PASSWORD not like","userPassword"); return (Criteria) this; } public Criteria andUserPasswordIn(List<String> values) { addCriterion("USER_PASSWORD in","userPassword"); return (Criteria) this; } public Criteria andUserPasswordnotin(List<String> values) { addCriterion("USER_PASSWORD not in","userPassword"); return (Criteria) this; } public Criteria andUserPasswordBetween(String value1,String value2) { addCriterion("USER_PASSWORD between","userPassword"); return (Criteria) this; } public Criteria andUserPasswordNotBetween(String value1,String value2) { addCriterion("USER_PASSWORD not between","userPassword"); return (Criteria) this; } public Criteria andUserEmailIsNull() { addCriterion("USER_EMAIL is null"); return (Criteria) this; } public Criteria andUserEmailIsNotNull() { addCriterion("USER_EMAIL is not null"); return (Criteria) this; } public Criteria andUserEmailEqualTo(String value) { addCriterion("USER_EMAIL =","userEmail"); return (Criteria) this; } public Criteria andUserEmailNotEqualTo(String value) { addCriterion("USER_EMAIL <>","userEmail"); return (Criteria) this; } public Criteria andUserEmailGreaterThan(String value) { addCriterion("USER_EMAIL >","userEmail"); return (Criteria) this; } public Criteria andUserEmailGreaterThanorEqualTo(String value) { addCriterion("USER_EMAIL >=","userEmail"); return (Criteria) this; } public Criteria andUserEmailLessthan(String value) { addCriterion("USER_EMAIL <","userEmail"); return (Criteria) this; } public Criteria andUserEmailLessthanorEqualTo(String value) { addCriterion("USER_EMAIL <=","userEmail"); return (Criteria) this; } public Criteria andUserEmailLike(String value) { addCriterion("USER_EMAIL like","userEmail"); return (Criteria) this; } public Criteria andUserEmailNotLike(String value) { addCriterion("USER_EMAIL not like","userEmail"); return (Criteria) this; } public Criteria andUserEmailIn(List<String> values) { addCriterion("USER_EMAIL in","userEmail"); return (Criteria) this; } public Criteria andUserEmailnotin(List<String> values) { addCriterion("USER_EMAIL not in","userEmail"); return (Criteria) this; } public Criteria andUserEmailBetween(String value1,String value2) { addCriterion("USER_EMAIL between","userEmail"); return (Criteria) this; } public Criteria andUserEmailNotBetween(String value1,String value2) { addCriterion("USER_EMAIL not between","userEmail"); 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; 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; } protected Criterion(String condition) { super(); this.condition = condition; this.novalue = true; } protected Criterion(String condition,Object value) { super(); this.condition = condition; this.value = value; if (value instanceof List<?>) { this.listValue = true; } else { this.singlevalue = true; } } protected Criterion(String condition,Object secondValue) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.betweenValue = true; } } }
这里是使用Mybatis Generator自动生成的:UserDao.java
package com.lin.dao; import com.lin.domain.User; import com.lin.domain.UserExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface UserDao { int countByExample(UserExample example); int deleteByExample(UserExample example); int deleteByPrimaryKey(Integer userId); int insert(User record); int insertSelective(User record); List<User> selectByExample(UserExample example); User selectByPrimaryKey(Integer userId); int updateByExampleSelective(@Param("record") User record,@Param("example") UserExample example); int updateByExample(@Param("record") User record,@Param("example") UserExample example); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); }
这里就设计了两个方法,一个查找和一个插入
接口类:
package com.lin.service; import com.lin.domain.User; import com.lin.domain.UserExample; public interface IRegisterService { public int insert(User record); public int countByExample(UserExample example); }
实现类:
package com.lin.service.impl; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import com.lin.dao.UserDao; import com.lin.domain.User; import com.lin.domain.UserExample; import com.lin.service.IRegisterService; @Service("registerService") public class RegisterServiceImpl implements IRegisterService{ private static Logger logger = Logger.getLogger(RegisterServiceImpl.class); @Resource private UserDao userDao; @Override public int insert(User record) { try { return userDao.insert(record); } catch (Exception e) { e.printstacktrace(); } return 0; } @Override public int countByExample(UserExample example) { try { return userDao.countByExample(example); } catch (Exception e) { e.printstacktrace(); } return 0; } }
这里是使用Mybatis Generator自动生成的:UserMapper.xml。放在src下面的com.lin.mapper包下
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.lin.dao.UserDao"> <resultMap id="baseResultMap" type="com.lin.domain.User"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator,do not modify. --> <id column="USER_ID" jdbcType="INTEGER" property="userId" /> <result column="USER_NAME" jdbcType="CHAR" property="userName" /> <result column="USER_PASSWORD" jdbcType="CHAR" property="userPassword" /> <result column="USER_EMAIL" jdbcType="CHAR" property="userEmail" /> </resultMap> <sql id="Example_Where_Clause"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator,do not modify. --> <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"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator,do not modify. --> <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"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator,do not modify. --> USER_ID,USER_NAME,USER_PASSWORD,USER_EMAIL </sql> <select id="selectByExample" parameterType="com.lin.domain.UserExample" resultMap="baseResultMap"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator,do not modify. --> select <if test="distinct"> distinct </if> <include refid="base_Column_List" /> from t_user <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"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator,do not modify. --> select <include refid="base_Column_List" /> from t_user where USER_ID = #{userId,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator,do not modify. --> delete from t_user where USER_ID = #{userId,jdbcType=INTEGER} </delete> <delete id="deleteByExample" parameterType="com.lin.domain.UserExample"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator,do not modify. --> delete from t_user <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </delete> <insert id="insert" parameterType="com.lin.domain.User"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator,do not modify. --> insert into t_user (USER_ID,USER_EMAIL) values (#{userId,jdbcType=INTEGER},#{userName,jdbcType=CHAR},#{userPassword,#{userEmail,jdbcType=CHAR}) </insert> <insert id="insertSelective" parameterType="com.lin.domain.User"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator,do not modify. --> insert into t_user <trim prefix="(" suffix=")" suffixOverrides=","> <if test="userId != null"> USER_ID,</if> <if test="userName != null"> USER_NAME,</if> <if test="userPassword != null"> USER_PASSWORD,</if> <if test="userEmail != null"> USER_EMAIL,</if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="userId != null"> #{userId,</if> <if test="userName != null"> #{userName,</if> <if test="userPassword != null"> #{userPassword,</if> <if test="userEmail != null"> #{userEmail,</if> </trim> </insert> <select id="countByExample" parameterType="com.lin.domain.UserExample" resultType="java.lang.Integer"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator,do not modify. --> select count(*) from t_user <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </select> <update id="updateByExampleSelective" parameterType="map"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator,do not modify. --> update t_user <set> <if test="record.userId != null"> USER_ID = #{record.userId,</if> <if test="record.userName != null"> USER_NAME = #{record.userName,</if> <if test="record.userPassword != null"> USER_PASSWORD = #{record.userPassword,</if> <if test="record.userEmail != null"> USER_EMAIL = #{record.userEmail,</if> </set> <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByExample" parameterType="map"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator,do not modify. --> update t_user set USER_ID = #{record.userId,USER_NAME = #{record.userName,USER_PASSWORD = #{record.userPassword,USER_EMAIL = #{record.userEmail,jdbcType=CHAR} <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByPrimaryKeySelective" parameterType="com.lin.domain.User"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator,do not modify. --> update t_user <set> <if test="userName != null"> USER_NAME = #{userName,</if> <if test="userPassword != null"> USER_PASSWORD = #{userPassword,</if> <if test="userEmail != null"> USER_EMAIL = #{userEmail,</if> </set> where USER_ID = #{userId,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.lin.domain.User"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator,do not modify. --> update t_user set USER_NAME = #{userName,USER_PASSWORD = #{userPassword,USER_EMAIL = #{userEmail,jdbcType=CHAR} where USER_ID = #{userId,jdbcType=INTEGER} </update> </mapper>
<?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> </configuration>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 把标记了@Controller注解的类转换为bean --> <context:component-scan base-package="com.lin.controller" /> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean/> <!-- 静态资源访问(不拦截此目录下的东西的访问) --> <mvc:annotation-driven /> <mvc:resources location="/WEB-INF//js/" mapping="/js*.xml"/> <property name="configLocation" value="classpath:mybatis-config.xml" /> <!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model" /> --> </bean> <!-- 自动扫描注解的bean --> <context:component-scan base-package="com.lin.controller" /> <context:component-scan base-package="com.lin.service.impl" /> </beans>
log4j.rootLogger =DEBEG,stdout,debug log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
6、web文件配置,放在WebContent下面
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>JsLearning3</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- Spring 容器加载 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application.xml</param-value> </context-param> <!-- 统一设置编码,防止出现中文乱码 --> <filter> <filter-name>Set Character Encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>Set Character Encoding</filter-name> <url-pattern> function getRootPath() { var pathName = window.location.pathname.substring(1); var webName = pathName == '' ? '' : pathName.substring(0,pathName .indexOf('/')); return window.location.protocol + '//' + window.location.host + '/' + webName + '/'; } function checkUserName(obj) { if (checks(obj.value) == false) { showInfo("username_notice",username_invalid); } else if (obj.value.length < 1) { showInfo("username_notice",username_empty); }else if (obj.value.length < 3) { showInfo("username_notice",username_shorter); } else if(obj.value.length>30){ showInfo("username_notice",username_longer); }else { // 调用Ajax函数,向服务器端发送查询 $.ajax({ //一个Ajax过程 type: "post",//以post方式与后台沟通 url :getRootPath()+"/register/checkUserName",//与此页面沟通 dataType:'json',//返回的值以 JSON方式 解释 data: 'userName='+obj.value,//发给的数据 success: function(json){//如果调用成功 if(json.flag){ showInfo("username_notice",username_have_register); }else { showInfo("username_notice",username_can_register); name_flag=true; change_submit(); return; } } }); } name_flag=false; change_submit(); } function checks(t) { szMsg = "[#%&'"\,;:=!^@]" for (i = 1; i < szMsg.length + 1; i++) { if (t.indexOf(szMsg.substring(i - 1,i)) > -1) { return false; } } return true; } function checkEmail(email) { var re = /^(w-*.*)+@(w-?)+(.w{2,})+$/ if (email.value.length < 1) { showInfo("email_notice",email_empty); } else if (!re.test(email.value)) { email.className = "frameDivWarn"; showInfo("email_notice",email_invalid); } else { // 调用Ajax函数,向服务器端发送查询 $.ajax({ //一个Ajax过程 type: "post",//以post方式与后台沟通 url :getRootPath()+"/register/checkEmail",//返回的值以 JSON方式 解释 data: 'email='+email.value,//发给的数据 success: function(json){//如果调用成功 if(json.flag){ showInfo("email_notice",email_have_register); }else { showInfo("email_notice",email_can_register); email_flag=true; change_submit(); return; } } }); } email_flag=false; change_submit(); } function checkPassword( password ) { if(password.value.length < 1){ password_flag=false; showInfo("password_notice",password_empty); }else if ( password.value.length < 6 ) { password_flag=false; showInfo("password_notice",password_shorter_s); } else if(password.value.length > 30){ password_flag=false; showInfo("password_notice",password_shorter_m); } else { showInfo("password_notice",info_right); } change_submit(); } function checkConformPassword(conform_password) { password = $("#password").val(); if (password.length < 1) { showInfo("conform_password_notice",password_empty); } else if ( conform_password.value!= password) { showInfo("conform_password_notice",/confirm/i_password_invalid); } else { showInfo("conform_password_notice",info_right); password_flag=true; change_submit(); return; } password_flag=false; change_submit(); } function checkIntensity(pwd) { var Mcolor = "#FFF",Lcolor = "#FFF",Hcolor = "#FFF"; var m=0; var Modes = 0; for (i=0; i<pwd.length; i++) { var charType = 0; var t = pwd.charCodeAt(i); if (t>=48 && t <=57) { charType = 1; } else if (t>=65 && t <=90) { charType = 2; } else if (t>=97 && t <=122) charType = 4; else charType = 4; Modes |= charType; } for (i=0;i<4;i++) { if (Modes & 1) m++; Modes>>>=1; } if (pwd.length<=4) { m = 1; } switch(m) { case 1 : Lcolor = "2px solid red"; Mcolor = Hcolor = "2px solid #DADADA"; break; case 2 : Mcolor = "2px solid #f90"; Lcolor = Hcolor = "2px solid #DADADA"; break; case 3 : Hcolor = "2px solid #3c0"; Lcolor = Mcolor = "2px solid #DADADA"; break; case 4 : Hcolor = "2px solid #3c0"; Lcolor = Mcolor = "2px solid #DADADA"; break; default : Hcolor = Mcolor = Lcolor = ""; break; } document.getElementById("pwd_lower").style.borderBottom = Lcolor; document.getElementById("pwd_middle").style.borderBottom = Mcolor; document.getElementById("pwd_high").style.borderBottom = Hcolor; } //--------------注册协议复选框状态检测---------------------// function checkAgreement(obj){ if(document.getElementById("agreement").checked){ showInfo("agreement_notice",agreement_yes); accept_flag=true; change_submit(); }else{ showInfo("agreement_notice",agreement_no); } } function change_submit() { if(name_flag&&email_flag&&password_flag&&accept_flag){ document.forms['formUser'].elements['Submit1'].disabled = ''; } else { document.forms['formUser'].elements['Submit1'].disabled = 'disabled'; } } function showInfo(target,Infos){ document.getElementById(target).innerHTML = Infos; } function showclass(target,Infos){ document.getElementById(target).className = Infos; }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="https://www.12519.com/mysql/<%=request.getcontextpath()%>/js/jquery-1.11.3.min.js" ></script> <script type="text/javascript" src="https://www.12519.com/mysql/<%=request.getcontextpath()%>/js/registerCheck.js" ></script> <title>Ajax+SpringMVC+Spring+MyBatis+MysqL注册验证实例</title> </head> <body> <div id="reg"> <FORM name="formUser" action="<%=request.getcontextpath()%>/register/successed" method=post> <BR> <TABLE width="100%" align=center border=0> <TBODY> <TR> <TD align=right width="15%"><STRONG>用户名:</STRONG></TD> <TD width="57%"><INPUT id="username" onBlur="checkUserName(this)" name="username"> <SPAN id="username_notice" >*</SPAN></TD> </TR> <TR> <TD align=right><STRONG>邮箱:</STRONG></TD> <TD><INPUT id="email" onBlur="checkEmail(this)" name="email"> <SPAN id=email_notice >*</SPAN></TD> </TR> <TR> <TD align=right><STRONG>密码:</STRONG></TD> <TD><INPUT id="password" onBlur="checkPassword(this)" onkeyup="checkIntensity(this.value)" type="password" name="password"> <SPAN id=password_notice >*</SPAN></TD> </TR> <TR> <TD align=right><STRONG>密码强度:</STRONG></TD> <TD><TABLE cellSpacing=0 cellPadding=1 width=145 border=0> <TBODY> <TR align=middle> <TD id=pwd_lower width="33%">弱</TD> <TD id=pwd_middle width="33%">中</TD> <TD id=pwd_high width="33%">强</TD> </TR> </TBODY> </TABLE></TD> </TR> <TR> <TD align=right><STRONG>确认密码:</STRONG></TD> <TD><INPUT id="conform_password" onBlur="checkConformPassword(this)" type="password" name="/confirm/i_password"> <SPAN id=conform_password_notice >*</SPAN></TD> </TR> <TR> <TD> </TD> <TD><LABEL> <INPUT type="checkBox" id="agreement" onclick="checkAgreement(this)"> <B>我已看过并接受《<a href="https://www.12519.com#">用户协议</a>》<SPAN id=agreement_notice >*</SPAN></B></LABEL></TD> </TR> <TR> <TD ><INPUT type=hidden value=act_register name=act></TD> <TD ><input type=submit value=确认注册 name="Submit1"disabled></TD> </TR> <TR> <TD colSpan=2> </TD> </TR> </TBODY> </TABLE> </FORM> </div> </body> </html>
<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>用户注册成功</title> </head> <body> <center> <h1><b>欢迎新用户</b></h1> 用户名:${requestScope.username}<br> 邮箱:${requestScope.email}<br> </center> </body> </html>
使用SpringMVC就得要自己来写Controller,拦截各个请求,处理后再返回给请求者,放在src下的。com.lin.controller
package com.lin.controller; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.log4j.Logger; 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 com.lin.domain.User; import com.lin.domain.UserExample; import com.lin.domain.UserExample.Criteria; import com.lin.service.IRegisterService; @Controller public class RegisterController { private static Logger logger = Logger.getLogger(RegisterController.class); @Resource private IRegisterService registerService; @RequestMapping({"/register","/"}) public String register(){ return "register"; } @RequestMapping(value="/register/checkUserName",method = RequestMethod.POST) public String checkUserName(HttpServletRequest request,HttpServletResponse response) throws IOException{ String userName=(String)request.getParameter("userName"); //检验用户名是否存在 UserExample userExample=new UserExample(); Criteria conditionCri = userExample.createCriteria(); conditionCri.andUserNameEqualTo(userName); int num=registerService.countByExample(userExample); //用户名是否存在的标志 boolean flag=false; if(num>0){ flag=true; } //将数据转换成json Map<String,Object> map = new HashMap<String,Object>(); map.put("flag",flag); String json = JSONObject.fromObject(map).toString(); //将数据返回 response.setCharacterEncoding("UTF-8"); response.flushBuffer(); response.getWriter().write(json); response.getWriter().flush(); response.getWriter().close(); return null; } @RequestMapping(value="/register/checkEmail",method = RequestMethod.POST) public String checkEmail(HttpServletRequest request,HttpServletResponse response) throws IOException{ String email=(String)request.getParameter("email"); //检验邮箱是否存在 UserExample userExample=new UserExample(); Criteria conditionCri = userExample.createCriteria(); conditionCri.andUserEmailEqualTo(email); int num=registerService.countByExample(userExample); //用户名是否存在的标志 boolean flag=false; if(num>0){ flag=true; } //将数据转换成json Map<String,flag); String json = JSONObject.fromObject(map).toString(); //将数据返回 response.setCharacterEncoding("UTF-8"); response.flushBuffer(); response.getWriter().write(json); response.getWriter().flush(); response.getWriter().close(); return null; } @RequestMapping(value="/register/successed") public ModelAndView successed(HttpServletRequest request,HttpServletResponse response) throws IOException{ String username=(String)request.getParameter("username"); String email=(String)request.getParameter("email"); String password=(String)request.getParameter("password"); if(username==null||email==null||password==null){ return new ModelAndView("redirect:/register"); } //新增用户插入数据库 User user=new User(); user.setUserName(username); user.setUserEmail(email); user.setUserPassword(password); registerService.insert(user); //将数据转换成 Map<String,Object>(); map.put("username",username); map.put("email",email); map.put("password",password); return new ModelAndView("successed",map); } }
这是要验证用户名:
每次输入后,移开鼠标后就验证,并返回结果
这是在验证邮箱:
这是还没注册之前的:
这是数据成功插入之后的”,我做了很多次,所以数据有点多。
本文工程免费下载
maven 环境变量配置
Maven 下载
下载地址:http://maven.apache.org/download.cgi
apache-maven 路径(版本是会不断更新的)
系统环境变量配置 HOME_MAVEN
电脑 ——> 属性 ——> 高级系统设置 ——> 环境变量
1 新建环境变量(用户变量)HOME_MAVEN,变量值是 apache-maven 路径。
2. 编辑系统变量里的 path,把 apache-maven 里的 bin 路径添加到变量值的后面,我的是 ;F:mvnapache-maven-3.5.4bin; 。(注意前后要有;号,也可以是 %MAVEN_HOME%bin,如何用这个报错可以试试前面的绝对路径。 )
3. 配置本地 maven 仓库路径
找到文件 settings.xml , 我的在 F:mvnapache-maven-3.5.4conf 文件夹下
默认的本地库的路径是 C 盘的 ${user}/.m2/repository/
配置自定义仓库地址
<localRepository>F:/repository</localRepository>
maven 配置阿里镜像。
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
4.eclipse 配置 maven。
Windows->preferences, 配置 maven 的 installations,点击 add,点击 directory,installation home 是 maven 安装的路径,installation name 自动带出。
配置 maven user settins。点击 Window 的属性。
下面这个配置,解决更新项目的时候,报 Dmaven.multiModuleProjectDirectory 某某 set 的问题。
在 default vm 处配置改为 - Dmaven.multiModuleProjectDirectory=$MAVEN_HOME。(等号前面固定,等号后边是 Maven 配置的变量名称)。
* 新建 maven 工程。
建好项目后会报红星错误,bulid path jdk 版本换成默认的,或者和下面 jdk 相同版本,然后按照下面的配置,然后 clean 一下。
点击 project 里的属性。
上面错误解决方式。
1.web.xml 里的
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"> 的 web-app 的版本号改为 3.0.
2. 找到 org.eclipse.wst.common.project.facet.core.xml 文件,修改 java 为 1.8,jst.web 为 3.0.
如果没有显示.settings 文件夹。按照下面操作。
1. 选中工程,选择 Filters
2. 取消.resources 勾选,点击 OK. 显示.settings 文件夹,.classpath 文件,.project 文件,.gitignore 文件
新建 src/main/resources.(注意一定要是新建 source Folder 类型的)
SSM 整合。
一先整体看下项目的目录结构
未展开的目录结构。
展开后的目录结构。
二、maven 需要引入的 jar 包,pom.xml
#数据库驱动
driver=com.mysql.jdbc.Driver
#数据库连接
url=jdbc:mysql://localhost:3306/konglx?useUnicode=true&characterEncoding=UTF-8
#用户名
username=root
#用户密码
password=root
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
# This is the configuring for logging displayed in the Application Server
log4j.rootCategory=INFO, stdout,common-default,common-warn,common-error
# project loggers
#log4j.logger.com.konglx.dao=INFO,project-dao
log4j.logger.com.konglx.service=INFO,project-service
log4j.logger.com.konglx.controller=INFO,project-web
# common appenders
#stdout configure
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n
#common-default file appender
log4j.appender.common-default=org.apache.log4j.DailyRollingFileAppender
log4j.appender.common-default.file=${user.home}/logs/common-default.log
log4j.appender.common-default.layout=org.apache.log4j.PatternLayout
log4j.appender.common-default.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n
#common-warn file appender
log4j.appender.common-warn=org.apache.log4j.DailyRollingFileAppender
log4j.appender.common-warn.file=${user.home}/logs/common-warn.log
log4j.appender.common-warn.layout=org.apache.log4j.PatternLayout
log4j.appender.common-warn.filter.ID=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.common-warn.filter.ID.levelMin=WARN
log4j.appender.common-warn.filter.ID.levelMax=WARN
log4j.appender.common-warn.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n
#common-error file appender
log4j.appender.common-error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.common-error.file=${user.home}/logs/common-error.log
log4j.appender.common-error.layout=org.apache.log4j.PatternLayout
log4j.appender.common-error.threshold=ERROR
log4j.appender.common-error.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n
#common-dao file appender
log4j.appender.common-dao=org.apache.log4j.DailyRollingFileAppender
log4j.appender.common-dao.file=${user.home}/logs/common-dao.log
log4j.appender.common-dao.layout=org.apache.log4j.PatternLayout
log4j.appender.common-dao.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n
#common-web file appender
log4j.appender.common-web=org.apache.log4j.DailyRollingFileAppender
log4j.appender.common-web.file=${user.home}/logs/common-web.log
log4j.appender.common-web.layout=org.apache.log4j.PatternLayout
log4j.appender.common-web.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n
#common-pageNotFound file appender
log4j.appender.common-pageNotFound=org.apache.log4j.DailyRollingFileAppender
log4j.appender.common-pageNotFound.file=${user.home}/logs/common-pageNotFound.log
log4j.appender.common-pageNotFound.layout=org.apache.log4j.PatternLayout
log4j.appender.common-pageNotFound.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n
# project appenders
#project-dao file appender
#log4j.appender.project-dao=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.project-dao.file=${user.home}/logs/project-dao.log
#log4j.appender.project-dao.layout=org.apache.log4j.PatternLayout
#log4j.appender.project-dao.threshold=INFO
#log4j.appender.project-dao.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n
#project-web file appender
log4j.appender.project-web=org.apache.log4j.DailyRollingFileAppender
log4j.appender.project-web.file=${user.home}/logs/project-web.log
log4j.appender.project-web.layout=org.apache.log4j.PatternLayout
log4j.appender.project-web.threshold=INFO
log4j.appender.project-web.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n
#project-service file appender
log4j.appender.project-service=org.apache.log4j.DailyRollingFileAppender
log4j.appender.project-service.file=${user.home}/logs/project-service.log
log4j.appender.project-service.layout=org.apache.log4j.PatternLayout
log4j.appender.project-service.threshold=INFO
log4j.appender.project-service.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n
# open source framework loggers
#spring
log4j.logger.org.springframework=INFO
log4j.logger.org.springframework.jdbc=DEBUG,common-dao
# debug log for ibatis2.3
#log4j.logger.java.sql.Connection=DEBUG,common-dao
#log4j.logger.java.sql.Statement=INFO,common-dao
#log4j.logger.java.sql.PreparedStatement=INFO,common-dao
#log4j.logger.java.sql.ResultSet=INFO,common-dao
# debug log for mybatis
log4j.logger.java.sql.Connection=DEBUG,common-dao
log4j.logger.java.sql.Statement=DEBUG,common-dao
log4j.logger.java.sql.PreparedStatement=DEBUG,common-dao
log4j.logger.java.sql.ResultSet=DEBUG,common-dao
log4j.logger.org.mybatis.spring=DEBUG,common-dao
log4j.logger.com.springframework=DEBUG
# hibernate: Changing the log level to DEBUG will display SQL Hibernate generated
#log4j.logger.org.hibernate=INFO,common-dao
#log4j.logger.org.hibernate.SQL=ERROR
#log4j.logger.org.hibernate.cache=ERROR
#log4j.logger.net.sf.ehcache=ERROR
#springmvc pageNotFound
log4j.logger.org.springframework.web.servlet.PageNotFound=INFO,common-pageNotFound
#Hibernatevalidator
log4j.logger.org.apache.commons.validator.ValidatorResources=INFO
#log4jdbc,
log4j.logger.jdbc.sqlonly=ON
log4j.logger.jdbc.sqltiming=INFO,common-dao
log4j.logger.jdbc.audit=ON
log4j.logger.jdbc.resultset=ON
log4j.logger.jdbc.connection=ON
#====add==
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change ''info'' to ''debug'' ###
log4j.rootLogger = debug , stdout
#log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug
### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug
### log just the SQL
#log4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###
#log4j.logger.org.hibernate.type=trace
#log4j.logger.org.hibernate.type=debug
### log schema export/update ###
#log4j.logger.org.hibernate.tool.hbm2ddl=debug
### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug
### log cache activity ###
#log4j.logger.org.hibernate.cache=debug
### log transaction activity
#log4j.logger.org.hibernate.transaction=debug
### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
这个文件就是用来完成 spring 和 mybatis 的整合的,包含 spring 和 mybatis 的配置,包括自动扫描,自动注入,配置数据库;
六、整合 springMVC,spring-mvc.xml
上面已经完成了 2 大框架的整合,SpringMVC 的配置文件单独放,然后在 web.xml 中配置整合,主要是自动扫描控制器,视图模式,注解的启动这三个
这里面是对 spring-mybatis.xml 的引入以及配置的 spring-mvc 的 Servlet 就是为了完成 SSM 整合,之前 2 框架整合不需要在此处进行任何配置。
到目前为止,所有的整合已经完成,配置文件也搞好了,接下来就利用 mybatis 来自动生成一些 java 代码:
首先,我们建立数据库:下面是建库建表的语句
在 f 盘上建立一个文件夹(本文用到的文件夹不包含中文字符),然后在里面建个 src 文件夹,里面的东西如下图:
generatorConfig.xml 需要手动配置,下面附上配置的内容信息:
最后,打开 cmd,进入该文件夹(也可以在这个文件夹中按住 shift + 右击,选择 "在此处打开命令窗口"),复制粘贴以下代码 + 回车
完成后,到该文件夹下打开 src, 如下
利用 java 生成代码,只要在 generatorTemp.java 文件运行 main 方法就可以了。run as ->java applicatoin.F5 刷新整个项目,会在下面目录生成目录文件。
generatorTemp.java 文件和 generator.xml 文件的目录。
generatorTemp.java 文件内容。
generator.xml 文件内容。
service 接口
serviceImpl 实现类
手动创建 jsp 页面
手动创建 controller
至此,所有的代码已经完成了
最后,项目右键 - maven-update project。然后 maven-maven install。然后部署项目到 Tomcat。
启动服务,访问 url。 http://localhost:8080/project_star/user/test?id=1
启动成功,没有报错如下图。
转自:https://www.cnblogs.com/lmei/p/7190755.html?utm_source=itdadao&utm_medium=referral
@_@ 写在最前
之前分享过下面这几篇:
mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(上)(附demo和搭建过程遇到的问题解决方法)
mybatis学习笔记(六) -- maven+spring+mybatis从零开始搭建整合详细过程(下)
springmvc学习笔记(一) -- 从零搭建,基础入门
这一篇,在这些练习的基础上,将它们整合在一起!
搭建步骤如下
一、新建maven项目,配置环境,测试是否配置成功
二、整合spring+mybatis,添加ApplicationContext.xml文件,修改pom.xml,,并连接mysql,测试是否搭建成功
(如果想了解单独的mybatis项目,可参考mybatis学习笔记(一)-- 简单入门(附测试Demo详细过程))
三、整合springmvc,添加springmvc-servlet.xml文件,修改调整,测试是否搭建成功
附:第一,二步详细操作步骤可参考
mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(上)
mybatis学习笔记(六) -- maven+spring+mybatis从零开始搭建整合详细过程(下)
当然下面也会附上详细的搭建过程!
项目结构一览
现在开始体验!!!
一、新建maven项目
1、新建项目,然后修改几个配置,修改完如下:
2、添加Dynamic Web Module
Apply后,查看项目结构可以看到多了个WebContent
3、将WebContent下的两个文件复制到src/main/webapp下,然后将WebContent整个删掉
4、修改Deployment Assembly,只留下下面几个
新增/src/main/webapp,步骤Add->Floder->src->main->webapp->finish
5、测试,在src/main/webapp下,新建一个index.jsp文件
修改web.xml
运行tomcat,访问:http://localhost:8888/SSM01/,页面显示“hello”
到此,第一步骤完成!!!
二、整合Spring+MyBatis
1、修改pom.xml,加载项目需要的jar
2、数据库准备
新建数据表tb_book,添加测试数据
3、新建包和类
(1)添加实体类Book
(2)添加Dao,BookDao
(3)添加service,BookService
(4)添加impl,BookServiceImpl实现BookService
(5)添加BookMapper
4、添加ApplicationContext.xm和db.propertiesl文件,并注册映射
ApplicationContext.xml
db.properties
5、添加测试类
TestMyBatisSpring
Run As->JUnit Test
到此,第二步完成Spring+MyBatis+Mysql!!!
三、整合springmvc
1、修改实体类Book
2、在WEB-INF下新建一个文件夹view,然后在里面新建hello.jsp文件,用来测试springmvc是否搭建成功
路径webapp/WEB-INF/view/hello.jsp
3、新建一个controller,HelloWorld.java
HelloWorld.java代码:
4、添加springmvc-servlet.xml
5、修改web.xml
之前在测试过程中,不小心把<url-pattern>/ 写错成 /*,导致springmvc把*.jsp,*.sql,*.txt都当做txt处理,访问页面时,直接在浏览器加载了jsp源码。
导致测试页面hello.jsp中的${message}一直取不到Controller传过来的值。
6、测试,项目右键->Run As->Run On Server->Tomcat...
运行成功后,访问:http://localhost:8888/SSM01/Hello/SayHello
控制台输出:输出true,表示${message}赋值成功
浏览器输出:
到此,SpringMVC搭建成功 !!!
继续整合!!!
7、在controller包下,新建一个BookController
8、在WEB-INFO/view下新建一个文件夹Book,然后在文件夹内添加index.jsp
Book/index.jsp代码:
9、测试
运行服务器,在浏览器访问:http://localhost:8888/SSM01/Book/getAllBook
到此,完成SpringMVC+Spring+MyBatis的整合!!!
1.整体结构
2.准备工作
数据库:
--Mysql 5.6
创建数据库 wolf
1
创建用户表 user
1
2
3
4
5
6
向表中插入测试数据
1
2
3
4
所需Jar包
jar:
1.驱动:mysql-connector-java-5.1.7-bin.jar
2.jstl 的
jstl.jar
standard.jar
3.spring 的
spring-aop-4.0.0.M2.jar
spring-beans-4.0.0.M2.jar
spring-context-4.0.0.M2.jar
spring-core-4.0.0.M2.jar
(若出现问题,可以替换 spring-core-4.0.0.RELEASE.jar)
spring-expression-4.0.0.M2.jar
spring-jdbc-4.0.0.M2.jar
spring-test-4.0.0.M2.jar
spring-tx-4.0.0.M2.jar
4.mybatis 的
mybatis-3.1.1.jar
log4j-1.2.16.jar
mybatis-spring-1.2.1.jar
5.以及spring-depend
aopalliance-1.0.jar
cglib-nodep-2.1_3.jar
commons-logging-1.1.1.jar
6.web 相关的
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
下面是jar包在项目中的结构图
框架/平台构成:
Maven+Springmvc + Mybatis + Shiro(权限)+ Tiles(模板) +ActiveMQ(消息队列) + Rest(服务) + WebService(服务)+ EHcache(缓存) + Quartz(定时调度)+ Html5(支持PC、IOS、Android)
用户权限系统:
组织结构:角色、用户、用户组、组织机构;权限点:页面、方法、按钮、数据权限、分级授权
项目管理新体验:
快速出原型系统、组件树、版本控制、模块移植、协同开发、实时监控、发布管理
可持续集成:
所有组件可移植、可定制、可扩充,开发成果不断积累,形成可持续发展的良性循环
支持平台平台:
Windows XP、Windows 7 、Windows 10 、 Linux 、 Unix
服务器容器:
Tomcat 5/6/7 、Jetty、JBoss、WebSphere 8.5
到这里配置文件基本配置完毕
今天关于springMVC+mybatis+mysql学习心得的讲解已经结束,谢谢您的阅读,如果想了解更多关于Ajax+SpringMVC+Spring+Mybatis+MySql+js用户注册实例、maven 整合 spring+springmvc+mybatis+mysql、maven+springmvc+spring+mybatis+mysql详细搭建整合过程讲解、Spring MVC +MyBatis +MySQL 登录查询Demo 解决了mybatis异常【转】的相关知识,请在本站搜索。