eclipse搭建ssm框架
新建数据库ssm
建立数据库表user
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT ,
`sex` varchar(255) NULL ,
`name` varchar(255) NULL ,
PRIMARY KEY (`id`)
);
新建一个Java web工程 SSM,目录结构如下
下面挨个看下配置文件
conf.properties配置详情
url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
driver=com.mysql.jdbc.Driver
username=root
password=root
log4j.properties配置详情
log4j.rootLogger=info, live, file
log4j.logger.org.springframework=ERROR
log4j.logger.org.logicalcobwebs.proxool=ERROR
log4j.appender.live=org.apache.log4j.ConsoleAppender
log4j.appender.live.Target=System.out
log4j.appender.live.layout=org.apache.log4j.PatternLayout
log4j.appender.live.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss}(%r)%n--> [%t] %l: %m %x %n
log4j.appender.file.File=/log/liveApi.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss}(%r)%n--> [%t] %l: %m %x %n
log4j.appender.file.DatePattern='.'yyyy-MM-dd'.log'
log4j.logger.com.ssm.dao=DEBUG
web.xml配置详情
<?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>SSM</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>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<!-- 配置DispatchcerServlet -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置Spring mvc下的配置文件的位置和名称 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc.xml</param-value>
</init-param> <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- spring Web MVC框架提供了org.springframework.web.filter.CharacterEncodingFilter用于解决POST方式造成的中文乱码问题 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<!-- force强制,促使 -->
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- 异常页面捕获 -->
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/500.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/500.html</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>
</web-app>
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:mvc="http://www.springframework.org/schema/mvc"
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-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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "> <!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.ssm">
<!-- 制定扫包规则 ,扫描除去使用@Controller注解的JAVA类 -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan> <!-- ===========================数据源配置=============================== -->
<!-- 引入外部数据源配置信息 -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:conf.properties</value>
</property>
</bean> <!-- 配置数据源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" /> <property name="validationQuery">
<value>SELECT 1</value>
</property>
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" /> <!-- 监控数据库 -->
<!-- <property name="filters" value="stat" /> -->
<property name="filters" value="mergeStat" />
</bean>
<!-- 配置MyBatis session工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/ssm/mapper/*.xml"></property>
</bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean> <!-- (事务管理)transaction manager -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <!-- 注解方式配置事物 -->
<tx:annotation-driven transaction-manager="transactionManager" /> </beans>
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:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
">
<!-- ====================================================== -->
<!-- 配置@ResponseBody 保证返回值为UTF-8 -->
<!-- 因为StringHttpMessageConverter默认是ISO8859-1 -->
<!-- 用于使用@ResponseBody后返回中文避免乱码 -->
<bean id="utf8Charset" class="java.nio.charset.Charset"
factory-method="forName">
<constructor-arg value="UTF-8" />
</bean> <!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.ssm">
<!-- 制定扫包规则 ,只扫描使用@Controller注解的JAVA类 -->
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan> <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!-- 配置Fastjson支持 -->
<bean
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="charset" value="UTF-8" />
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json</value>
<value>application/xml;charset=UTF-8</value>
</list>
</property>
<property name="features">
<list>
<!-- 输出key时是否使用双引号 -->
<value>QuoteFieldNames</value>
<!-- 是否输出值为null的字段 -->
<!-- <value>WriteMapNullValue</value> -->
<!-- 数值字段如果为null,输出为0,而非null -->
<value>WriteNullNumberAsZero</value>
<!-- List字段如果为null,输出为[],而非null -->
<value>WriteNullListAsEmpty</value>
<!-- 字符类型字段如果为null,输出为"",而非null -->
<value>WriteNullStringAsEmpty</value>
<!-- Boolean字段如果为null,输出为false,而非null -->
<value>WriteNullBooleanAsFalse</value>
<!-- null String不输出 -->
<value>WriteNullStringAsEmpty</value>
<!-- null String也要输出 -->
<!-- <value>WriteMapNullValue</value> --> <!-- Date的日期转换器 -->
<value>WriteDateUseDateFormat</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven> <!-- 文件上传配置 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<!-- 100M 1024 * 1024 * 100 -->
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
</beans>
==============顺便介绍一下数据库逆向生成工具(网上应该也有现成的)================================start
新建一个java 工程generatorSqlmapCustom,如下图所示
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://localhost:3306/ssm" userId="root"
password="root">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver> <!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.ssm.pojo"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.ssm.dao"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.ssm.dao"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<table schema="" tableName="user"></table>
</context>
</generatorConfiguration>
GeneratorSqlmap.java代码
public void generator() throws Exception{ List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//指定 逆向工程配置文件
File configFile = new File("generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null); }
public static void main(String[] args) throws Exception {
try {
GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
} }
执行main函数 生成对应的映射文件,然后刷新项目
==============顺便介绍一下数据库逆向生成工具================================end
将逆向生成的文件拷贝到对应的文件夹
如果不想使用逆向工程,手动配置一下也可以
User.java
package com.ssm.pojo; public class User {
private Integer id; private String sex; private String name; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
} public String getName() {
return name;
} public void setName(String name) {
this.name = name == null ? null : name.trim();
}
}
UserExample.java其实这个类可以没有,这个类主要就是方便配置sql查询条件
package com.ssm.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 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 andSexIsNull() {
addCriterion("sex is null");
return (Criteria) this;
} public Criteria andSexIsNotNull() {
addCriterion("sex is not null");
return (Criteria) this;
} public Criteria andSexEqualTo(String value) {
addCriterion("sex =", value, "sex");
return (Criteria) this;
} public Criteria andSexNotEqualTo(String value) {
addCriterion("sex <>", value, "sex");
return (Criteria) this;
} public Criteria andSexGreaterThan(String value) {
addCriterion("sex >", value, "sex");
return (Criteria) this;
} public Criteria andSexGreaterThanOrEqualTo(String value) {
addCriterion("sex >=", value, "sex");
return (Criteria) this;
} public Criteria andSexLessThan(String value) {
addCriterion("sex <", value, "sex");
return (Criteria) this;
} public Criteria andSexLessThanOrEqualTo(String value) {
addCriterion("sex <=", value, "sex");
return (Criteria) this;
} public Criteria andSexLike(String value) {
addCriterion("sex like", value, "sex");
return (Criteria) this;
} public Criteria andSexNotLike(String value) {
addCriterion("sex not like", value, "sex");
return (Criteria) this;
} public Criteria andSexIn(List<String> values) {
addCriterion("sex in", values, "sex");
return (Criteria) this;
} public Criteria andSexNotIn(List<String> values) {
addCriterion("sex not in", values, "sex");
return (Criteria) this;
} public Criteria andSexBetween(String value1, String value2) {
addCriterion("sex between", value1, value2, "sex");
return (Criteria) this;
} public Criteria andSexNotBetween(String value1, String value2) {
addCriterion("sex not between", value1, value2, "sex");
return (Criteria) this;
} public Criteria andNameIsNull() {
addCriterion("name is null");
return (Criteria) this;
} public Criteria andNameIsNotNull() {
addCriterion("name is not null");
return (Criteria) this;
} public Criteria andNameEqualTo(String value) {
addCriterion("name =", value, "name");
return (Criteria) this;
} public Criteria andNameNotEqualTo(String value) {
addCriterion("name <>", value, "name");
return (Criteria) this;
} public Criteria andNameGreaterThan(String value) {
addCriterion("name >", value, "name");
return (Criteria) this;
} public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("name >=", value, "name");
return (Criteria) this;
} public Criteria andNameLessThan(String value) {
addCriterion("name <", value, "name");
return (Criteria) this;
} public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("name <=", value, "name");
return (Criteria) this;
} public Criteria andNameLike(String value) {
addCriterion("name like", value, "name");
return (Criteria) this;
} public Criteria andNameNotLike(String value) {
addCriterion("name not like", value, "name");
return (Criteria) this;
} public Criteria andNameIn(List<String> values) {
addCriterion("name in", values, "name");
return (Criteria) this;
} public Criteria andNameNotIn(List<String> values) {
addCriterion("name not in", values, "name");
return (Criteria) this;
} public Criteria andNameBetween(String value1, String value2) {
addCriterion("name between", value1, value2, "name");
return (Criteria) this;
} public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("name not between", value1, value2, "name");
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);
}
}
}
UserMapper.java
package com.ssm.dao;
import com.ssm.pojo.User;
import com.ssm.pojo.UserExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UserMapper {
int countByExample(UserExample example); int deleteByExample(UserExample example); int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); List<User> selectByExample(UserExample example); User selectByPrimaryKey(Integer id); 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);
}
UserMapper.xml (注意标红的地方,主键已经在数据库中设置为自动递增,所以插入sql得手动配一下)
<?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.ssm.dao.UserMapper" >
<resultMap id="BaseResultMap" type="com.ssm.pojo.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="sex" property="sex" jdbcType="VARCHAR" />
<result column="name" property="name" 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" >
id, sex, name
</sql>
<select id="selectByExample" resultMap="BaseResultMap" parameterType="com.ssm.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 id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<delete id="deleteByExample" parameterType="com.ssm.pojo.UserExample" >
delete from user
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.ssm.pojo.User" useGeneratedKeys="true" keyProperty="id">
insert into user (sex, name
)
values (#{sex,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.ssm.pojo.User" >
insert into user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="sex != null" >
sex,
</if>
<if test="name != null" >
name,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="sex != null" >
#{sex,jdbcType=VARCHAR},
</if>
<if test="name != null" >
#{name,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.ssm.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.id != null" >
id = #{record.id,jdbcType=INTEGER},
</if>
<if test="record.sex != null" >
sex = #{record.sex,jdbcType=VARCHAR},
</if>
<if test="record.name != null" >
name = #{record.name,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 id = #{record.id,jdbcType=INTEGER},
sex = #{record.sex,jdbcType=VARCHAR},
name = #{record.name,jdbcType=VARCHAR}
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.ssm.pojo.User" >
update user
<set >
<if test="sex != null" >
sex = #{sex,jdbcType=VARCHAR},
</if>
<if test="name != null" >
name = #{name,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.ssm.pojo.User" >
update user
set sex = #{sex,jdbcType=VARCHAR},
name = #{name,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
新建一个vo类,UserVo.java
package com.ssm.vo; public class UserVo {
private String id; private String sex; private String name; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} }
新建一个service接口,IUserService.java
package com.ssm.service;
import java.util.Map;
import com.ssm.vo.UserVo;
public interface IUserService { public Map<String,String> onSave(UserVo userVo);
}
实现IUserService接口,UserServiceImpl.java
package com.ssm.service.impl; import java.util.HashMap;
import java.util.Map; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.ssm.dao.UserMapper;
import com.ssm.pojo.User;
import com.ssm.service.IUserService;
import com.ssm.vo.UserVo; @Service
public class UserServiceImpl implements IUserService{ @Autowired
private UserMapper userMapper; @Override
public Map<String, String> onSave(UserVo userVo) {
Map<String, String> map = new HashMap<String,String>();
try {
User user = new User();
user.setName(userVo.getName());
user.setSex(userVo.getSex());
int i = userMapper.insert(user);
if(i > 0){
map.put("status", "Y");
map.put("message", "新增成功");
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
} }
新建一个control类,UserController.java
package com.ssm.controller; import java.util.HashMap;
import java.util.Map; 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.ResponseBody; import com.ssm.service.IUserService;
import com.ssm.vo.UserVo; @RequestMapping("/user")
@Controller
public class UserController {
@Autowired
private IUserService userService; @RequestMapping("/onSave")
@ResponseBody
public Map<String,String> onSave(UserVo userVo){
Map<String,String> map = new HashMap<String,String>();
try {
map = userService.onSave(userVo);
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}
在WebContent目录下,新增static目录,如下图所示:
新增index.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<base href="${pageContext.request.contextPath}/static/"></base>
<meta charset="utf-8" />
<script src="js/jquery-1.12.4.min.js"></script> <script type="text/javascript">
$(document).ready(function() {
onSave();
}); function onSave() {
$.ajax({
type : "post",
url : "${pageContext.request.contextPath}/user/onSave",
async : false,
timeout : 30000,
data : {
"sex":"男",
"name":"张三"
},
dataType : 'json',
beforeSend : function(XMLHttpRequest) { },
success : function(result) {
alert(result.message)
},
error : function() {
}
});
} </script>
</head> <body>
欢迎您!!!!!!!!!!!!!!!!
</body> </html>
在浏览器地址栏,输入http://127.0.0.1:8080/SSM/index.jsp,回车,结果如下图所示
看下数据库表
eclipse搭建ssm框架的更多相关文章
- [框架]eclipse搭建ssm框架 一 标签: eclipsetomcat框架 2017-03-25 21:28 1085人阅读 评论(
虽然现在也做过一些项目,但是自己从头搭起来的框架几乎没有,所以这两天自己搭了一下ssm的框架,下面写一下框架的搭建过程.并且给出增删改查四条线来方便大家熟悉代码. 环境准备 maven3.2.3 ec ...
- 使用Eclipse搭建SSM框架(Spring + Spring MVC + Mybatis)
1.创建项目 1)打开Eclipse,点击File --> New --> Other 2)输入maven,找到Maven Project 3)然后一直按Next,直到出现一下界面: 4) ...
- eclipse搭建ssm框架的maven的工程
版本:eclipse:Indigo Service Release 2. jdk :jdk1.7.0_03. maven:apache-maven-3.3.3 . 上面的3个东西 先下载下来.然后运 ...
- Eclipse中使用Maven搭建SSM框架
Eclipse中不使用Maven搭建SSM框架:https://www.cnblogs.com/xuyiqing/p/9569459.html IDEA中使用Maven搭建SSM框架:https:// ...
- 使用Maven搭建SSM框架(Eclipse)
今天学习一下使用Maven搭建SSM框架,以前都是用别人配置好的框架写代码,今天试试自己配置一下SSM框架. 这里我的参数是Windows7 64位,tomcat9,eclipse-jee-neon- ...
- maven/eclipse搭建ssm(spring+spring mvc+mybatis)
maven/eclipse搭建ssm(spring+spring mvc+mybatis) 前言 本文旨在利用maven搭建ssm环境,而关于maven的具体内容,大家可以去阅读<Maven 实 ...
- 快速搭建ssm框架
快速搭建SSM框架 因为最近有很多朋友问我自己的项目搭建的不够完善,并且经常出现一些小问题,那么今天我又整理了一下文档教大家如何快速搭建SSM框架我是用 eclipse搭建的,如果想用idear的话我 ...
- 利用maven/eclipse搭建ssm(spring+spring mvc+mybatis)
前言 本文旨在利用maven搭建ssm环境,而关于maven的具体内容,大家可以去阅读<Maven 实战>.其实园内这方面文章已有不少,那么为什么我还要重复造轮子呢?我只是想记录自己的实践 ...
- 使用maven搭建ssm框架的javaweb项目
目前主流的javaweb项目,常会用到ssm(Spring+Spring MVC+Mybatis)框架来搭建项目的主体框架,本篇介绍搭建SSM框架的maven项目的实施流程.记之共享! 一.SSM框架 ...
随机推荐
- android -------- 颜色的半透明效果配置
最近有朋友问我 Android 背景颜色的半透明效果配置,我网上看资料,总结了一下, 开发中也是常常遇到的,所以来写篇博客 常用的颜色值格式有: RGB ARGB RRGGBB AA ...
- hdu6331 Walking Plan
题意: sol: 考虑floyed 直接暴力做的话复杂度是kn^3会炸. 考虑一个比较神仙的分块做法. 注意到我们是可以直接求单独某个k的矩阵,使用矩阵快速幂即可(取min的矩阵乘法). 单独求一次的 ...
- python记录_day31 进程同步和进程通信
一.进程同步 1.同步锁(又叫互斥锁) 加锁的代码以后,同一时间内只能被一个进程执行 from multiprocessing import Process, Lock def fun(loc): l ...
- 『MXNet』第五弹_MXNet.image图像处理
简单处理API 读取图像: image.imdecode(open('../img/cat1.jpg', 'rb').read()) 图像类型转换: img.astype('float32') 图像增 ...
- tmp目录自动清除和tmpwatch命令
习惯性的将一些临时文件放在tmp目录下,让其自然删除.同时,为了保证tmp目录不爆满,系统默认情况下每日会处理一次tmp目录文件,原理就是使用了tmpwatch.在系统最小安装情况下,这个功能是没有安 ...
- 牛客练习赛24-B-贪心
链接:https://www.nowcoder.com/acm/contest/157/B来源:牛客网 题目描述 凤凰于飞,翙翙其羽,亦集爰止. ...
- Leetcode 969. 煎饼排序
969. 煎饼排序 显示英文描述 我的提交返回竞赛 用户通过次数134 用户尝试次数158 通过次数135 提交次数256 题目难度Medium 给定数组 A,我们可以对其进行煎饼翻转:我们选择 ...
- 五、持久层框架(Hibernate)
一.分页查询 使用Criteria进行分页查询,无论是使用Oracle,MySQL,NoSQL,DB2,分页查询的代码写法都相同. 分页查询代码示例: package com.demo.test; i ...
- Charles破解网站收藏(持续更新)
1. 在这个网站(http://charles.iiilab.com/)下载破解文件 charles.jar 2. 替换掉原文件夹里的charles.jar Mac: /Applications/Ch ...
- Mysql SQL优化系列之——执行计划连接方式浅释
关系库SQL调优中,虽然思路都是一样的,具体方法和步骤也是大同小异,但细节却不容忽视,尤其是执行计划的具体细节的解读中,各关系库确实有区别,特别是mysql数据库,与其他关系库的差别更大些,下面,我们 ...