----------------------------------------------------------------------------------------------------------------
- 1.导入Jar包
- 2.创建目录,数据库
Java Resources/src/controller,Java Resources/src/dao,Java Resources/src/pojo,Java Resources/src/service
Java Resources/config
----------------------------------------------------------------------------------------------------------------
- 3.逆向工程
具体参考:逆向工程教程
逆向创建pojo,Dao里面的mapper文件
XXXMapper.java:对应XXXMapper.xml接口,函数名对应xml中id,传参类型对应parameterType,返回类型对应resultType
XXXMapper.xml:写SQL语句实现功能
例如,逆向生成的
pojo里的bean
package pojo; public class User { private Integer uid; private String username; private String password; public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } }
pojo里的Example
package pojo; 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> 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 andUidIsNull() { addCriterion("uid is null"); return (Criteria) this; } public Criteria andUidIsNotNull() { addCriterion("uid is not null"); return (Criteria) this; } public Criteria andUidEqualTo(Integer value) { addCriterion("uid =", value, "uid"); return (Criteria) this; } public Criteria andUidNotEqualTo(Integer value) { addCriterion("uid <>", value, "uid"); return (Criteria) this; } public Criteria andUidGreaterThan(Integer value) { addCriterion("uid >", value, "uid"); return (Criteria) this; } public Criteria andUidGreaterThanOrEqualTo(Integer value) { addCriterion("uid >=", value, "uid"); return (Criteria) this; } public Criteria andUidLessThan(Integer value) { addCriterion("uid <", value, "uid"); return (Criteria) this; } public Criteria andUidLessThanOrEqualTo(Integer value) { addCriterion("uid <=", value, "uid"); return (Criteria) this; } public Criteria andUidIn(List<Integer> values) { addCriterion("uid in", values, "uid"); return (Criteria) this; } public Criteria andUidNotIn(List<Integer> values) { addCriterion("uid not in", values, "uid"); return (Criteria) this; } public Criteria andUidBetween(Integer value1, Integer value2) { addCriterion("uid between", value1, value2, "uid"); return (Criteria) this; } public Criteria andUidNotBetween(Integer value1, Integer value2) { addCriterion("uid not between", value1, value2, "uid"); return (Criteria) this; } public Criteria andUsernameIsNull() { addCriterion("username is null"); return (Criteria) this; } public Criteria andUsernameIsNotNull() { addCriterion("username is not null"); return (Criteria) this; } public Criteria andUsernameEqualTo(String value) { addCriterion("username =", value, "username"); return (Criteria) this; } public Criteria andUsernameNotEqualTo(String value) { addCriterion("username <>", value, "username"); return (Criteria) this; } public Criteria andUsernameGreaterThan(String value) { addCriterion("username >", value, "username"); return (Criteria) this; } public Criteria andUsernameGreaterThanOrEqualTo(String value) { addCriterion("username >=", value, "username"); return (Criteria) this; } public Criteria andUsernameLessThan(String value) { addCriterion("username <", value, "username"); return (Criteria) this; } public Criteria andUsernameLessThanOrEqualTo(String value) { addCriterion("username <=", value, "username"); return (Criteria) this; } public Criteria andUsernameLike(String value) { addCriterion("username like", value, "username"); return (Criteria) this; } public Criteria andUsernameNotLike(String value) { addCriterion("username not like", value, "username"); return (Criteria) this; } public Criteria andUsernameIn(List<String> values) { addCriterion("username in", values, "username"); return (Criteria) this; } public Criteria andUsernameNotIn(List<String> values) { addCriterion("username not in", values, "username"); return (Criteria) this; } public Criteria andUsernameBetween(String value1, String value2) { addCriterion("username between", value1, value2, "username"); return (Criteria) this; } public Criteria andUsernameNotBetween(String value1, String value2) { addCriterion("username not between", value1, value2, "username"); 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 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里的mapper
package dao; import java.util.List; import org.apache.ibatis.annotations.Param; import pojo.User; import pojo.UserExample; @Component public interface UserMapper { int countByExample(UserExample example); int deleteByExample(UserExample example); int deleteByPrimaryKey(Integer uid); int insert(User record); int insertSelective(User record); List<User> selectByExample(UserExample example); User selectByPrimaryKey(Integer uid); 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); }
Dao里的mapper.xml
mapper.xml里面的sql语句#{xx}里面xx元素与传递类型的属性相关,xxx=#{},xxx与数据库相关
<?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="dao.UserMapper" > <resultMap id="BaseResultMap" type="pojo.User" > <id column="uid" property="uid" jdbcType="INTEGER" /> <result column="username" property="username" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> </resultMap> <sql id="Example_Where_Clause" > <where > <foreach collection="oredCriteria" item="criteria" separator="or" > <if test="criteria.valid" > <trim prefix="(" suffix=")" prefixOverrides="and" > <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 collection="criterion.value" item="listItem" open="(" close=")" 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="(" suffix=")" prefixOverrides="and" > <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 collection="criterion.value" item="listItem" open="(" close=")" separator="," > #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Base_Column_List" > uid, username, password </sql> <select id="selectByExample" resultMap="BaseResultMap" parameterType="pojo.UserExample" > select <if test="distinct" > distinct </if> <include refid="Base_Column_List" /> from user <if test="_parameter != null" > <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null" > order by ${orderByClause} </if> </select> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from user where uid = #{uid,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from user where uid = #{uid,jdbcType=INTEGER} </delete> <delete id="deleteByExample" parameterType="pojo.UserExample" > delete from user <if test="_parameter != null" > <include refid="Example_Where_Clause" /> </if> </delete> <insert id="insert" parameterType="pojo.User" > insert into user (uid, username, password ) values (#{uid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR} ) </insert> <insert id="insertSelective" parameterType="pojo.User" > insert into user <trim prefix="(" suffix=")" suffixOverrides="," > <if test="uid != null" > uid, </if> <if test="username != null" > username, </if> <if test="password != null" > password, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="uid != null" > #{uid,jdbcType=INTEGER}, </if> <if test="username != null" > #{username,jdbcType=VARCHAR}, </if> <if test="password != null" > #{password,jdbcType=VARCHAR}, </if> </trim> </insert> <select id="countByExample" parameterType="pojo.UserExample" resultType="java.lang.Integer" > select count(*) from user <if test="_parameter != null" > <include refid="Example_Where_Clause" /> </if> </select> <update id="updateByExampleSelective" parameterType="map" > update user <set > <if test="record.uid != null" > uid = #{record.uid,jdbcType=INTEGER}, </if> <if test="record.username != null" > username = #{record.username,jdbcType=VARCHAR}, </if> <if test="record.password != null" > password = #{record.password,jdbcType=VARCHAR}, </if> </set> <if test="_parameter != null" > <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByExample" parameterType="map" > update user set uid = #{record.uid,jdbcType=INTEGER}, username = #{record.username,jdbcType=VARCHAR}, password = #{record.password,jdbcType=VARCHAR} <if test="_parameter != null" > <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByPrimaryKeySelective" parameterType="pojo.User" > update user <set > <if test="username != null" > username = #{username,jdbcType=VARCHAR}, </if> <if test="password != null" > password = #{password,jdbcType=VARCHAR}, </if> </set> where uid = #{uid,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="pojo.User" > update user set username = #{username,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR} where uid = #{uid,jdbcType=INTEGER} </update> </mapper>
----------------------------------------------------------------------------------------------------------------
- 4.config下创建SqlMapConfig.xml,log4j.properties,db.properties
Mybait核心配置文件和约束
<?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>
log4j.properties
日志文件
# Global logging configuration log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
db.properties
数据库信息
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/springmvc?characterEncoding=utf-8 jdbc.username=root jdbc.password=root
----------------------------------------------------------------------------------------------------------------
- 5.config下创建ApplicationContext-dao.xml,ApplicationContext-service.xml,ApplicationContext-trans.xml
ApplicationContext-dao.xml
加入数据库信息,对Mapper中Sql语句扫描
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 加载配置文件 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 数据库连接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="10" /> <property name="maxIdle" value="5" /> </bean> <!-- mapper配置 --> <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据库连接池 --> <property name="dataSource" ref="dataSource" /> <!-- 加载mybatis的全局配置文件 --> <property name="configLocation" value="classpath:SqlMapConfig.xml" /> </bean> <!-- 配置Mapper扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="dao"/> </bean> </beans>
ApplicationContext-service.xml
扫描@service注解,约束和上面一样
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- @Service扫描 --> <context:component-scan base-package="service"></context:component-scan> </beans>
ApplicationContext-trans.xml
事务管理文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 数据源 --> <property name="dataSource" ref="dataSource" /> </bean> <!-- 通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 传播行为 --> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="find*" propagation="SUPPORTS" read-only="true" /> <tx:method name="get*" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <!-- 切面 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* service.*.*(..))" /> </aop:config> </beans>
----------------------------------------------------------------------------------------------------------------
- 6.Config下创建SpringMvc.xml
SpringMvc.xml
包括了对Controller注解的扫描,注解驱动,视图解析器作用就是Controller return的值进行页面跳转,Controller的return是根据解析器配置的,相对于WebContent目录来说,前缀和后缀都很重要,return list相当于返回到webcontent/前缀目录下/list/后缀目录,拼接起来的返回
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- @Controller注解扫描 --> <context:component-scan base-package="controller"></context:component-scan> <!-- 注解驱动: 替我们显示的配置了最新版的注解的处理器映射器和处理器适配器 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 配置视图解析器 作用:在controller中指定页面路径的时候就不用写页面的完整路径名称了,可以直接写页面去掉扩展名的名称 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 真正的页面路径 = 前缀 + 去掉后缀名的页面名称 + 后缀 --> <!-- controller里面方法return结果跳转设置,已经默认到WebContent --> <!-- 前缀 --> <property name="prefix" value="/jsp/"></property> <!-- 后缀 --> <property name="suffix" value=".jsp"></property> </bean> </beans>
----------------------------------------------------------------------------------------------------------------
- 7.WEB-INF下创建web.xml
web.xml
spring容器就是监听器,启动服务器是启动spring(AppilcationContext.xml)配置,前端控制器就是Form表单提交时直接可以根据@RequestMapping跳转,根据@RequestMapping里面的值加上action进行跳转,*.action就是扫描到所有action的值,只有form表单提交时<%=basePath%>获取相对路径后不是明确的指定路径(路径符号"/"),是一个xxx.jsp或者xxx.action,xxx.do的话,就会根据@RequestMapping扫描来跳转,扫描到action结尾的,post乱码就是提交表单时防止乱码一般用在提交数据页面上也可以在get时可在获取时通过设置utf-8或者设置服务起来解析
<?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_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>ssm0523</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容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:ApplicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- springmvc前端控制器 --> <servlet> <servlet-name>springMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:SpringMvc.xml</param-value> </init-param> <!-- 在tomcat启动的时候就加载这个servlet --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <!-- 配置Post请求乱码 --> <filter> <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
----------------------------------------------------------------------------------------------------------------
8.创建Controller,Service文件,注入对象
Controller
package controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; 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 service.UserService; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; }
Service
package service; import java.util.List; import pojo.User; public interface UserService { }
ServiceImpl
package service; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import dao.UserMapper; import pojo.User; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; }
插入一点:@Autowired 和@Resource的最大区别在于,一个接口有多个实现类时,接口创建对象后,用@Autowired注入,就分辨不清楚要注入哪个实现类对象,要用@Resource("实现类名称")来区分,当只有一个实现类时可以用@Autowired或者Resource,多个实现类时得用@Resource
----------------------------------------------------------------------------------------------------------------
- 9.总结
pojo和映射文件以及接口使用逆向工程生成
SqlMapConfig.xml mybatis核心配置文件
ApplicationContext-dao.xml 整合后spring在dao层的配置
数据源
会话工厂
扫描Mapper
2)service层
事务 ApplicationContext-trans.xml
@Service注解扫描 ApplicationContext-service.xml
3)controller层
SpringMvc.xml
注解扫描:扫描@Controller注解
注解驱动:替我们显示的配置了最新版的处理器映射器和处理器适配器
视图解析器:显示的配置是为了在controller中不用每个方法都写页面的全路径
4)web.xml
springMvc前端控制器配置
spring监听
----------------------------------------------------------------------------------------------------------------
- 10.登录案例
login.jsp
<%@ 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> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <form action="<%=basePath%>user/login.action" method="post"> 账号名:<input type="text" name="username"><br> 密码:<input type="text" name="password"><br> <input type="submit" value="提交"> </form> </body>
UserController
绑定参数属性,和jsp input控件里面的name属性名称一样,则可以直接传递数据,不要通过request获取前端jsp里input的数据
package controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; 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 service.UserService; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; // 不用request,根据input name属性,一样直接传递 @RequestMapping("/login") public String login(String username, String password) { if (userService.login(username, password) == "ok") { return "success"; } return "login"; } }
UserService
package service; import java.util.List; import pojo.User; public interface UserService { public String login(String username,String password); }
UserServiceImpl
package service; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import dao.UserMapper; import pojo.User; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public String login(String username, String password) { User user = new User(); user.setUsername(username); user.setPassword(password); List<User> list = userMapper.selectByNameAndPass(user); if (list.size() > 0) { return "ok"; } return null; } }
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="dao.UserMapper" > <resultMap id="BaseResultMap" type="pojo.User" > <id column="uid" property="uid" jdbcType="INTEGER" /> <result column="username" property="username" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> </resultMap> <sql id="Example_Where_Clause" > <where > <foreach collection="oredCriteria" item="criteria" separator="or" > <if test="criteria.valid" > <trim prefix="(" suffix=")" prefixOverrides="and" > <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 collection="criterion.value" item="listItem" open="(" close=")" 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="(" suffix=")" prefixOverrides="and" > <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 collection="criterion.value" item="listItem" open="(" close=")" separator="," > #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Base_Column_List" > uid, username, password </sql> <select id="selectByExample" resultMap="BaseResultMap" parameterType="pojo.UserExample" > select <if test="distinct" > distinct </if> <include refid="Base_Column_List" /> from user <if test="_parameter != null" > <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null" > order by ${orderByClause} </if> </select> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from user where uid = #{uid,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from user where uid = #{uid,jdbcType=INTEGER} </delete> <delete id="deleteByExample" parameterType="pojo.UserExample" > delete from user <if test="_parameter != null" > <include refid="Example_Where_Clause" /> </if> </delete> <insert id="insert" parameterType="pojo.User" > insert into user (uid, username, password ) values (#{uid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR} ) </insert> <insert id="insertSelective" parameterType="pojo.User" > insert into user <trim prefix="(" suffix=")" suffixOverrides="," > <if test="uid != null" > uid, </if> <if test="username != null" > username, </if> <if test="password != null" > password, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="uid != null" > #{uid,jdbcType=INTEGER}, </if> <if test="username != null" > #{username,jdbcType=VARCHAR}, </if> <if test="password != null" > #{password,jdbcType=VARCHAR}, </if> </trim> </insert> <select id="countByExample" parameterType="pojo.UserExample" resultType="java.lang.Integer" > select count(*) from user <if test="_parameter != null" > <include refid="Example_Where_Clause" /> </if> </select> <update id="updateByExampleSelective" parameterType="map" > update user <set > <if test="record.uid != null" > uid = #{record.uid,jdbcType=INTEGER}, </if> <if test="record.username != null" > username = #{record.username,jdbcType=VARCHAR}, </if> <if test="record.password != null" > password = #{record.password,jdbcType=VARCHAR}, </if> </set> <if test="_parameter != null" > <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByExample" parameterType="map" > update user set uid = #{record.uid,jdbcType=INTEGER}, username = #{record.username,jdbcType=VARCHAR}, password = #{record.password,jdbcType=VARCHAR} <if test="_parameter != null" > <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByPrimaryKeySelective" parameterType="pojo.User" > update user <set > <if test="username != null" > username = #{username,jdbcType=VARCHAR}, </if> <if test="password != null" > password = #{password,jdbcType=VARCHAR}, </if> </set> where uid = #{uid,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="pojo.User" > update user set username = #{username,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR} where uid = #{uid,jdbcType=INTEGER} </update> <select id="selectByNameAndPass" parameterType="pojo.User" resultType="pojo.User"> select * from user u where u.username=#{username} and u.password=#{password} </select> </mapper>
UserMapper.java
package dao; import java.util.List; import org.apache.ibatis.annotations.Param; import pojo.User; import pojo.UserExample; @Component public interface UserMapper { int countByExample(UserExample example); int deleteByExample(UserExample example); int deleteByPrimaryKey(Integer uid); int insert(User record); int insertSelective(User record); List<User> selectByExample(UserExample example); User selectByPrimaryKey(Integer uid); 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); List<User> selectByNameAndPass(User user); }
SSM:Jsp表单根据Controller里面的@RequestMapping进行提交数据,找到对应的@RequestMapping函数执行,根据jsp里面name属性和函数的传参属性一样进行传参,最后通过return返回页面。Jsp请求时要自己手动加相对路径来请求,return已经默认相对路径WebContent了,则不用自己手动写。
SSH:Jsp表单根据struts里面配置的acitonname进行提交数据,struts里面对应actionname里面对应不同的方法,执行对应action里面的方法后通过action页面返回的值来对应struts上的result的页面进行跳转。
----------------------------------------------------------------------------------------------------------------
2018-06-15 更新~~~
springMVC常用注解@Controller,@Service,@repository,@Component以及区别看这里:
https://blog.csdn.net/simon_it/article/details/80708889
----------------------------------------------------------------------------------------------------------------
因为在xml里已经配置Dao层的扫描配置,已经对mapper进行扫描,所以Dao层里的@Component注解可加可不加