從零開始SSM搭建步驟(圖文)
本文介紹瞭從零開始SSM搭建步驟,分享給大傢,有助於更好的搭建ssm,具體如下:
第一章:搭建整合環境
1. 搭建整合環境
整合說明:SSM整合可以使用多種方式,咱們會選擇XML + 註解的方式
整合的思路
2.1. 先搭建整合的環境
2.2. 先把Spring的配置搭建完成
2.3. 再使用Spring整合SpringMVC框架
2.4. 最後使用Spring整合MyBatis框架
創建數據庫和表結構
3.1創建數據庫
create database ssm; create table account( id int primary key auto_increment, name varchar(20), money double );
4.創建maven工程
<properties> <spring.version>5.0.2.RELEASE</spring.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <mysql.version>5.1.6</mysql.version> <mybatis.version>3.4.5</mybatis.version> </properties> <dependencies> <!--spring--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency><dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--log start--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!--連接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version></dependency> </dependencies> <build> <finalName>ssm</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> <showWarnings>true</showWarnings> </configuration> </plugin> </plugins> </pluginManagement> </build>
編寫實體類,在ssm_domain項目中編寫
package com.qcby.entity; import java.io.Serializable; public class Account implements Serializable { // 主鍵 private int id; // 賬戶名稱 private String name; // 賬號的金額 private Double money; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } }
編寫service接口和實現類
package com.qcby.service; import com.qcby.entity.Account; import java.util.List; public interface AccountService { //查詢所有 public List<Account> findAll(); }
package com.qcby.service; import com.qcby.entity.Account; import org.springframework.stereotype.Service; import java.util.List; @Service public class AccountServiceImpl implements AccountService { //查詢所有 @Override public List<Account> findAll() { System.out.println("業務層:查詢所有"); return null; } }
第二章:Spring框架代碼的編寫
1. 搭建和測試Spring的開發環境
在ssm_web項目中創建spring.xml的配置文件,編寫具體的配置信息。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--開啟註解掃描,要掃描的是service--> <context:component-scan base-package="com.qcby.service"/> </beans>
在ssm_web項目中編寫測試方法,進行測試
package com.qcby.demo; import com.qcby.service.AccountService; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestSpring { @Test public void run(){ ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml"); AccountService service = ac.getBean(AccountService.class); service.findAll(); } }
第三章:Spring整合SpringMVC框架
1. 搭建和測試SpringMVC的開發環境
在web.xml中配置DispatcherServlet前端控制器
<!--配置前端控制器--> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--加載springmvc.xml配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 啟動加載--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
在web.xml中配置DispatcherServlet過濾器解決中文亂碼
<!--解決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>
創建springmvc.xml的配置文件,編寫配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--掃描controller的註解,別的不掃描--> <context:component-scan base-package="com.qcby.controller"/> <!-- 配置視圖解析器--> <bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--JSP文件所在的目錄--> <property name="prefix" value="/pages/"/> <!--文件的後綴名--> <property name="suffix" value=".jsp"/> </bean> <!--設置靜態資源不過濾--> <mvc:resources mapping="/source/css/**" location="/source/css/"/> <mvc:resources mapping="/source/js/**" location="/source/js/"/> <mvc:resources mapping="/source/images/**" location="/source/images/"/> <!--開啟springmvc--> <mvc:annotation-driven/> </beans>
測試SpringMVC的框架搭建是否成功
4.1. 編寫index.jsp和list.jsp編寫,超鏈接
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <a href="/account/findAll" rel="external nofollow" rel="external nofollow" >查詢所有</a> </body> </html>
4.2. 創建AccountController類,編寫方法,進行測試
package com.qcby.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/account") public class AccountController { /** * 查詢所有 * @return */ @RequestMapping("/findAll") public ModelAndView findAll(){ System.out.println("表現層:查詢所有"); ModelAndView mv = new ModelAndView(); mv.setViewName("suc"); return mv; } }
2. Spring整合SpringMVC的框架
目的:在controller中能成功的調用service對象中的方法。
在項目啟動的時候,就去加載spring.xml的配置文件,在web.xml中配置
ContextLoaderListener監聽器(該監聽器隻能加載WEB-INF目錄下的applicationContext.xml的配置文
件,所以要配置全局的變量加載類路徑下的配置文件)。
<!--配置Spring的監聽器--> <display-name>Archetype Created Web Application</display-name> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置加載類路徑的配置文件--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param>
在controller中註入service對象,調用service對象的方法進行測試
package com.qcby.controller; import com.qcby.entity.Account; import com.qcby.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.util.List; @Controller @RequestMapping("/account") public class AccountController { //依賴註入 @Autowired private AccountService accountService; /** * 查詢所有 * @return */ @RequestMapping("/findAll") public ModelAndView findAll(){ System.out.println("表現層:查詢所有"); //調用service的方法 List<Account> list = accountService.findAll(); ModelAndView mv = new ModelAndView(); mv.setViewName("suc"); return mv; } }
第四章:Spring整合MyBatis框架
1. 搭建和測試MyBatis的環境
在web項目中編寫SqlMapConfig.xml的配置文件,編寫核心配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="jdbc.properties"></properties> <!--定義別名--> <typeAliases> <!--把com.qcby.entity.User使用user別名來顯示,別名user User USER都可以,默認是忽略大寫的--> <!--<typeAlias type="com.qcby.entity.User" alias="user"/>--> <!--針對com.qcby.entity包下的所有的類,都可以使用當前的類名做為別名--> <package name="com.qcby.entity"/> </typeAliases> <environments default="mysql"> <environment id="mysql"> <!--配置事務的類型,使用本地事務策略--> <transactionManager type="JDBC"></transactionManager> <!--是否使用連接池 POOLED表示使用鏈接池,UNPOOLED表示不使用連接池--> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/AccountDao.xml"></mapper> </mappers> </configuration>
AccountDao接口
package com.qcby.dao; import com.qcby.entity.Account; import java.util.List; public interface AccountDao { //查詢所有 public List<Account> findAll(); }
編寫AccountDao.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.qcby.dao.AccountDao"> <select id="findAll" resultType="account"> select * from account </select> </mapper>
編寫測試的方法
package com.qcby.demo; import com.qcby.dao.AccountDao; import com.qcby.entity.Account; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; public class TestMybatis { @Test public void run() throws IOException { InputStream in = Resources.getResourceAsStream("mybatis.xml"); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); SqlSession session = factory.openSession(); AccountDao mapper = session.getMapper(AccountDao.class); List<Account> list = mapper.findAll(); for (Account account : list) { System.out.println(account); } //關閉資源 session.close(); in.close(); } }
2. Spring整合MyBatis框架
目的:把SqlMapConfig.xml配置文件中的內容配置到applicationContext.xml配置文件中
在service中註入dao對象,進行測試
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 加載數據庫配置屬性文件--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--開啟註解掃描,要掃描的是service--> <context:component-scan base-package="com.qcby.service"/> <!--配置數據庫連接池--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--Spring整合MyBatis框架,SqlSessionFactoryBean創建工廠對象--> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 註入數據庫連接池 --> <property name="dataSource" ref="dataSource"/> <!-- 掃描entity包 使用別名 --> <property name="typeAliasesPackage" value="com.qcby.entity" /> <!-- 掃描sql配置文件:mapper需要的xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!--配置掃描Dao接口包,動態實現Dao接口,註入到ioc容器中--> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.qcby.dao"/> </bean> </beans>
service代碼如下
package com.qcby.service; import com.qcby.dao.AccountDao; import com.qcby.entity.Account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; //查詢所有 @Override public List<Account> findAll() { System.out.println("業務層:查詢所有"); List<Account> list = accountDao.findAll(); return list; } }
controller代碼如下
package com.qcby.controller; import com.qcby.entity.Account; import com.qcby.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.util.List; @Controller @RequestMapping("/account") public class AccountController { //依賴註入 @Autowired private AccountService accountService; /** * 查詢所有 * @return */ @RequestMapping("/findAll") public ModelAndView findAll(){ System.out.println("表現層:查詢所有"); //調用service的方法 List<Account> list = accountService.findAll(); for (Account account : list) { System.out.println(account); } ModelAndView mv = new ModelAndView(); mv.setViewName("suc"); return mv; } }
spring.xml配置聲明式事務管理
<!-- 配置聲明式事務管理--> <!--平臺事務管理器--> <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--配置事務的通知--> <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*" /> </tx:attributes> </tx:advice> <!--配置事務的增強--> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(public * com.qcby.service.*ServiceImpl.*(..))"/> </aop:config>
表單代碼
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <a href="/account/findAll" rel="external nofollow" rel="external nofollow" >查詢所有</a> <form action="/account/save" method="post"> 姓名:<input type="text" name="name" /><br/> 金額:<input type="text" name="money" /><br/> <input type="submit" value="保存" /> </form> </body> </html>
controller代碼
package com.qcby.controller; import com.qcby.entity.Account; import com.qcby.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.util.List; @Controller @RequestMapping("/account") public class AccountController { //依賴註入 @Autowired private AccountService accountService; /** * 查詢所有 * @return */ @RequestMapping("/findAll") public ModelAndView findAll(){ System.out.println("表現層:查詢所有"); //調用service的方法 List<Account> list = accountService.findAll(); for (Account account : list) { System.out.println(account); } ModelAndView mv = new ModelAndView(); mv.setViewName("suc"); return mv; } @RequestMapping("/save") public String save(Account account){ //Service的保存方法 accountService.save(account); return "suc"; } }
service接口和實現類代碼
package com.qcby.service; import com.qcby.entity.Account; import java.util.List; public interface AccountService { //查詢所有 public List<Account> findAll(); //保存 void save(Account account); }
package com.qcby.service; import com.qcby.dao.AccountDao; import com.qcby.entity.Account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; //查詢所有 @Override public List<Account> findAll() { System.out.println("業務層:查詢所有"); List<Account> list = accountDao.findAll(); return list; } @Override public void save(Account account) { accountDao.save(account); } }
dao代碼
package com.qcby.dao; import com.qcby.entity.Account; import java.util.List; public interface AccountDao { //查詢所有 public List<Account> findAll(); //保存 void save(Account account); }
dao.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.qcby.dao.AccountDao"> <select id="findAll" resultType="account"> select * from account </select> <insert id="save" parameterType="account"> insert into account (name,money) values(#{name},#{money}) </insert> </mapper>
到此這篇關於從零開始SSM搭建步驟(圖文)的文章就介紹到這瞭,更多相關SSM搭建內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- None Found