SSM框架目前依然仍是流行的框架,以前看別人作了一下基本的框架,這裏打算從零開始作這個框架,閒話少說,開始出手。java
mvn archetype:generate -DgroupId=com.mxsoft -DartifactId=ssm-demo -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=falsemysql
成功後, 生成文件目錄以下:git
用idea導入projectweb
UTF-8 UTF-8 UTF-8 properties>
javax.servletgroupId> javax.servlet-apiartifactId> 3.0.1version> providedscope> dependency>
這裏請指定maven座標的scope爲provided, 不然,後面用tomcat插件啓動的時候,會報錯spring
首先添加tomcat7 maven插件sql
org.apache.tomcat.mavengroupId> tomcat7-maven-pluginartifactId> 2.2version> /path> 8888port> configuration> plugin>
修改web.xml文件, 拷貝servlet 3.0 頭, 在tomcat7以上版本中, 打開${tomcat_home}/webapps/ROOT/WEB-INF/目錄下的web.xml
拷貝里面的內容到咱們工程的web.xml文件中便可,編碼修改成UTF-8
數據庫
mvn -U clean tomcat7:run
打開瀏覽器 http://localhost:8888/ 看到hello World 輸出, 代表成功了
express
mysqlgroupId> mysql-connector-javaartifactId> 5.1.6version> dependency>
這裏咱們使用mysql數據庫,若是要使用apache
org.mybatisgroupId> mybatisartifactId> 3.4.5version> dependency>
在src/main/resources/目錄下建立mybatis文件,進一步建立mybatis-config.xml配置文件 文件內容以下:
settings> configuration>
官方文檔地址:http://www.mybatis.org/spring/zh/json
版本匹配要求以下:
org.mybatisgroupId> mybatis-springartifactId> 1.3.1version> dependency>
spring 分爲幾個模塊,分別以下:
從圖中, 能夠看出spring 框架包括 Core Container、AOP and Instrumentation、Messaging、Web、Data Access/Integration、Test等6個模塊
org.springframeworkgroupId> spring-coreartifactId> 4.3.13.RELEASEversion> dependency> org.springframeworkgroupId> spring-beansartifactId> 4.3.13.RELEASEversion> dependency> org.springframeworkgroupId> spring-contextartifactId> 4.3.13.RELEASEversion> dependency> org.springframeworkgroupId> spring-context-supportartifactId> 4.3.13.RELEASEversion> dependency> org.springframeworkgroupId> spring-expressionartifactId> 4.3.13.RELEASEversion> dependency>
org.springframeworkgroupId> spring-aopartifactId> 4.3.13.RELEASEversion> dependency> org.springframeworkgroupId> spring-aspectsartifactId> 4.3.13.RELEASEversion> dependency> org.aspectjgroupId> aspectjweaverartifactId> 1.8.11version> dependency> org.aspectjgroupId> aspectjrtartifactId> 1.8.11version> dependency> org.springframeworkgroupId> spring-instrumentartifactId> 4.3.13.RELEASEversion> dependency>
org.springframeworkgroupId> spring-messagingartifactId> 4.3.13.RELEASEversion> dependency> org.springframeworkgroupId> spring-jmsartifactId> 4.3.13.RELEASEversion> dependency>
org.springframeworkgroupId> spring-webartifactId> 4.3.13.RELEASEversion> dependency> org.springframeworkgroupId> spring-webmvcartifactId> 4.3.13.RELEASEversion> dependency> org.springframeworkgroupId> spring-websocketartifactId> 4.3.13.RELEASEversion> dependency> org.springframeworkgroupId> spring-webmvc-portletartifactId> 4.3.13.RELEASEversion> dependency>
org.springframework spring-jdbc 4.3.13.RELEASE org.springframework spring-tx 4.3.13.RELEASE org.springframework spring-orm 4.3.13.RELEASE org.springframework spring-oxm 4.3.13.RELEASE org.springframework spring-orm 4.3.13.RELEASE
org.springframeworkgroupId> spring-testartifactId> 4.3.13.RELEASEversion> testscope> dependency>
在src/main/resources/目錄下建立spring文件夾
4.一、spring 配置文件
在src/main/resources/spring文件夾下,建立spring-mybatis.xml文件
內容以下:
settings> configuration>
在src/main/resources/spring文件夾下,建立applicationContext.xml文件,內容以下:
context:component-scan> bean> bean> property> bean> property> bean> bean> bean> beans>
在src/main/resources文件夾下,建立jdbc.properties文件,內容以下:
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/ssmdemo?useUnicode=true&characterEncoding=gbk username=root password=rootroot
根據提示建立package,
com.mxsoft.ssmdemo.mapper
com.mxsoft.ssmdemo.service
com.mxsoft.ssmdemo.web
根據提示在src/main/resources目錄下建立*mapper.xml文件的目錄,com/mxsoft/ssmdemo/mappers/
在src/main/webapp/WEB-INF/目錄下,建立dispatcher-servlet.xml
<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" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.mxsoft.ssmdemo.web"/> <mvc:annotation-driven /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
修改web.xml文件, 內容以下:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0" metadata-complete="true"> <display-name>SSM demo</display-name> <description> Welcome to ssm demo </description> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>throwExceptionIfNoHandlerFound</param-name> <param-value>true</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
首先,建立表t_foo,腳本以下:
CREATE TABLE `t_foo` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵', `version` int(11) NOT NULL DEFAULT '0' COMMENT '版本', `create_date` timestamp NULL DEFAULT NULL COMMENT '數據庫插入時間', `create_by` varchar(30) DEFAULT NULL COMMENT '建立人', `username` varchar(100) DEFAULT NULL COMMENT '用戶名', `password` varchar(100) DEFAULT NULL COMMENT '密碼', `update_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '數據庫更新時間', `update_by` varchar(100) DEFAULT NULL COMMENT '修改人', `is_delete` varchar(10) DEFAULT NULL COMMENT '是否刪除 1 刪除 0 未刪除 ', `memo` varchar(255) DEFAULT NULL COMMENT '備註', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='foo記錄';
在包com.mxsoft.ssmdemo.model裏面建立Foo.java,內容以下:
package com.mxsoft.ssmdemo.model; import java.io.Serializable; import java.util.Date; /** * @author zhangyingxuan */ public class Foo implements Serializable{ private Long id; private Integer version; private String createBy; private Date createDate; private String updateBy; private Date updateDate; private String isDelete; private String memo; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public String getIsDelete() { return isDelete; } public void setIsDelete(String isDelete) { this.isDelete = isDelete; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } }
在包com.mxsoft.ssmdemo.mapper下面,建立接口FooMapper.java,內容以下:
package com.mxsoft.ssmdemo.mapper; import com.mxsoft.ssmdemo.model.Foo; import java.util.List; /** * @author zhangyingxuan */ public interface FooMapper { int insert(Foo foo); int update(Foo foo); int delete(Long id); List<Foo> selectAll(); Foo selectById(Long id); }
在src/main/resources/com/mxsoft/ssmdemo/mappers目錄下, 建立FooMapper.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="com.mxsoft.ssmdemo.mapper.FooMapper"> <!-- 通用查詢映射結果 --> <resultMap id="BaseResultMap" type="com.mxsoft.ssmdemo.model.Foo"> <id column="id" property="id"/> <result column="version" property="version"/> <result column="create_date" property="addTime"/> <result column="create_by" property="createBy"/> <result column="update_date" property="updateTime"/> <result column="update_by" property="updateBy"/> <result column="is_delete" property="isDelete"/> <result column="memo" property="memo"/> <result column="username" property="username"/> <result column="password" property="password"/> </resultMap> <!-- 通用查詢結果列 --> <sql id="Base_Column_List"> id,version,create_date,create_by,username,password,update_date,update_by,is_delete,memo </sql> <select id="findById" resultMap="BaseResultMap"> SELECT <include refid="Base_Column_List"/> FROM t_foo WHERE id = #{id, jdbcType=INTEGER} </select> <select id="findAll" resultMap="BaseResultMap"> SELECT <include refid="Base_Column_List"/> FROM t_foo </select> <insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.mxsoft.ssmdemo.model.Foo"> INSERT INTO t_foo (create_date, create_by, username, password) values (now(), #{createBy}, #{username}, #{password}); </insert> <update id="update" parameterType="com.mxsoft.ssmdemo.model.Foo"> UPDATE t_foo set password = #{password} WHERE id = #{id, jdbcType=INTEGER} </update> <delete id="delete"> DELETE FROM t_foo WHERE id = #{id, jdbcType=INTEGER} </delete> </mapper>
在包com.mxsoft.ssmdemo.service下,建立IFooService.java接口:
package com.mxsoft.ssmdemo.service; import com.mxsoft.ssmdemo.model.Foo; import java.util.List; /** * @author zhangyingxuan */ public interface IFooService { int add(Foo foo); int edit(Foo foo); int delete(Long id); List<Foo> findAll(); Foo findById(Long id); }
在包com.mxsoft.ssmdemo.service.impl下,建立FooServiceImpl.java,內容以下:
package com.mxsoft.ssmdemo.service.impl; import com.mxsoft.ssmdemo.mapper.FooMapper; import com.mxsoft.ssmdemo.model.Foo; import com.mxsoft.ssmdemo.service.IFooService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author zhangyingxuan */ @Service public class FooServiceImpl implements IFooService { @Autowired private FooMapper fooMapper; @Override public int add(Foo foo) { return fooMapper.insert(foo); } @Override public int edit(Foo foo) { return fooMapper.update(foo); } @Override public int delete(Long id) { return fooMapper.delete(id); } @Override public List<Foo> findAll() { return fooMapper.selectAll(); } @Override public Foo findById(Long id) { return fooMapper.selectById(id); } }
在包com.mxsoft.ssmdemo.web.controller下,建立FooController.java,內容以下:
package com.mxsoft.ssmdemo.web.controller; import com.mxsoft.ssmdemo.model.Foo; import com.mxsoft.ssmdemo.service.IFooService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @author zhangyingxuan */ @RestController @RequestMapping("/api/foo") public class FooController { @Autowired private IFooService fooService; @RequestMapping(value = "/", method = RequestMethod.POST) public Object add(Foo foo) { int add = fooService.add(foo); if (add > 0) { return foo; } return null; } @RequestMapping(value = "/", method = RequestMethod.PUT) public Object edit(Foo foo) { int add = fooService.edit(foo); if (add > 0) { return foo; } return null; } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public Object delete(@PathVariable("id") Long id) { int add = fooService.delete(id); if (add > 0) { return add; } return null; } @RequestMapping(value = "/", method = RequestMethod.GET) public Object findByID() { List<Foo> fooList = fooService.findAll(); return fooList; } }
在src/test/java目錄下,建立測試用例FooTestCase.java,內容以下:
package com.mxsoft.ssmdemo.web.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.mxsoft.ssmdemo.model.Foo; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration(value = "src/main/webapp") @ContextHierarchy({ @ContextConfiguration(name = "parent", locations = "classpath:spring/applicationContext.xml"), @ContextConfiguration(name = "child", locations = "file:src/main/webapp/WEB-INF/dispatcher-servlet.xml") }) public class FooTestCase { @Autowired private WebApplicationContext webApplicationContext; private MockMvc mockMvc; @Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void testInsert() throws Exception { Foo foo = new Foo(); foo.setUsername("testusername"); foo.setPassword("password"); MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/api/foo").contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(foo))).andExpect(MockMvcResultMatchers.status().is(HttpStatus.OK.value())).andReturn(); Assert.assertNotNull(mvcResult); } }
補充:
這裏爲了轉換json, 加了三個依賴包, 以下:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.0</version> </dependency>