SSM: SpringMVC + Spring + MyBatis.javascript
SpringMVC:視圖層,界面層,負責接收請求,顯示處理結果的。
Spring:業務層,管理service,dao,工具類對象的。
MyBatis:持久層, 訪問數據庫的html
用戶發起請求--SpringMVC接收--Spring中的Service對象--MyBatis處理數據java
SSM整合也叫作SSI (IBatis也就是mybatis的前身), 整合中有容器。mysql
咱們要作的把使用的對象交給合適的容器建立,管理。 把Controller還有web開發的相關對象交給springmvc容器, 這些web用的對象寫在springmvc配置文件中jquery
service,dao對象定義在spring的配置文件中,讓spring管理這些對象web
springmvc容器和spring容器是有關係的,關係已經肯定好了ajax
springmvc容器是spring容器的子容器, 相似java中的繼承。 子能夠訪問父的內容
在子容器中的Controller能夠訪問父容器中的Service對象, 就能夠實現controller使用service對象spring
實現步驟:sql
使用ssm的mysql庫, 表使用student(id auto_increment, name, age)數據庫
新建maven web項目
加入依賴
springmvc,spring,mybatis三個框架的依賴,jackson依賴,mysql驅動,druid鏈接池
jsp,servlet依賴
寫web.xml
建立包, Controller包, service ,dao,實體類包名建立好
寫springmvc,spring,mybatis的配置文件
寫代碼, dao接口和mapper文件, service和實現類,controller, 實體類。
寫jsp頁面
需求:完成學生的註冊和信息瀏覽
經過maven
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.md</groupId> <artifactId>07-ssm</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--servlet依賴--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- jsp依賴 --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2.1-b03</version> <scope>provided</scope> </dependency> <!--springmvc依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.5.RELEASE</version> </dependency> <!--事務--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory><!--所在的目錄--> <includes><!--包括目錄下的.properties,.xml 文件都會掃描到--> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build> </project>
jdbc屬性配置文件jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/ssm jdbc.username=root jdbc.password=123456 jdbc.maxActive=20
Spring配置文件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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--spring的配置文件,聲明service、dao、工具類對象--> <!--註冊組件掃描器--> <!--聲明service的註解@Service所在的包名位置--> <context:component-scan base-package="com.md.service"/> <!--聲明數據源,鏈接數據庫--> <context:property-placeholder location="classpath:conf/jdbc.properties"/> <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="${jdbc.maxActive}" /> </bean> <!--SqlSessionFactory--> <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="myDataSource"/> <property name="configLocation" value="classpath:/conf/mybatis.xml"/> </bean> <!--建立 dao對象--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="SqlSessionFactory"/> <!--指定包名,包名是dao接口所在的包名,dao默認對象的名稱:是接口名字的首字母小寫--> <property name="basePackage" value="com.md.dao"/> </bean> <!--上面的這個是一個模板,只有一些配置文件的路徑是根據本身建立寫的--> </beans>
SpringMVC的配置文件,dispatcherServlet.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- springmvc的配置文件,聲明controller和其餘web相關的對象--> <!-- 註冊組件掃描器,指定@Controller註解所在的類--> <context:component-scan base-package="com.md.controller"/> <!-- 指定視圖解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!--註冊註解驅動 1. 響應ajax請求,返回json 2. 解決靜態資源訪問問題 --> <mvc:annotation-driven/> </beans>
mybatis的配置文件 , mybatis.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> <!--<settings>--> <!--<!–設置日誌–>--> <!--<setting name="logImpl" value="STDOUT_LOGGING"/>--> <!--</settings>--> <!--設置別名,在mapper.xml文件中,返回值不用在寫包名了,直接寫類名便可--> <typeAliases> <package name="com.md.domain"/> </typeAliases> <!-- sql映射文件的位置 --> <mappers> <!--name是包名,這個包中全部mapper.xml一次加載 使用package的要求 1. mapper文件名稱和dao接口名稱必須徹底同樣 2. mapper文件和dao接口必須在同一目錄 --> <package name="com.md.dao"/> </mappers> </configuration>
因爲自動生成的是這樣的,版本過低,須要換成如今高的版本,直接把以前寫好的複製過來就行
換成這樣
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--註冊中央調度器--> <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:conf/dispatcherServlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!--註冊spring監聽器--> <context-param> <param-name>contextConfigLocation</param-name> <!--自定義路徑--> <param-value>classpath:conf/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--註冊字符集過濾器--> <!--聲明過濾器,解決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> <init-param> <param-name>forceRequestEncoding</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <!--/* : 全部的請求都會先經過這個過濾器--> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
package com.md.domain; /** * @author MD * @create 2020-08-13 20:21 */ public class Student { private Integer id; private String name; private Integer age; public Student() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
都在是dao包下,且文件名相同
package com.md.dao; import com.md.domain.Student; import java.util.List; /** * @author MD * @create 2020-08-13 20:22 */ public interface StudentDao { int insertStudent(Student student); List<Student> selectStudents(); }
StudentDao.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.md.dao.StudentDao"> <insert id="insertStudent" > insert into student(name,age) values(#{name} , #{age}) </insert> <!--設置了別名,這裏返回值直接寫類名--> <select id="selectStudents" resultType="Student"> select id, name , age from student </select> </mapper>
package com.md.service; import com.md.domain.Student; import java.util.List; /** * @author MD * @create 2020-08-13 20:31 */ public interface StudentService { int addStudent(Student student); List<Student> findStudents(); }
實現類
package com.md.service.impl; import com.md.dao.StudentDao; import com.md.domain.Student; import com.md.service.StudentService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * @author MD * @create 2020-08-13 20:32 */ @Service public class StudentServiceImpl implements StudentService { // 引用數據類型的自動注入@Resource、@Autowired @Resource private StudentDao studentDao; @Override public int addStudent(Student student) { int nums = studentDao.insertStudent(student); return nums; } @Override public List<Student> findStudents() { return studentDao.selectStudents(); } }
在controller包下
package com.md.controller; import com.md.domain.Student; import com.md.service.StudentService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; import java.util.List; /** * @author MD * @create 2020-08-13 20:37 */ @Controller @RequestMapping("/student") public class StudentController { // 自動注入 @Resource private StudentService service; // 註冊學生 @RequestMapping("/addStudent.do") public ModelAndView addStudent(Student student){ ModelAndView mv = new ModelAndView(); String tips = "註冊失敗"; // 調用service處理student int nums = service.addStudent(student); if (nums > 0){ tips = "註冊成功"; } // 添加數據,指定頁面 mv.addObject("tips",tips); mv.setViewName("result"); return mv; } // 處理查詢,響應ajax @RequestMapping("/queryStudent.do") @ResponseBody public List<Student> queryStudent(){ List<Student> students = service.findStudents(); // 會被框架轉爲json的數組 return students; } }
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <% String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %> <html> <head> <title>功能入口</title> <base href="<%=basePath%>"> </head> <body> <div align="center"> <h2>SSM整合</h2> <table> <tr> <td> <a href="addStudent.jsp">學生註冊</a> </td> </tr> <br> <tr> <td><a href="listStudent.jsp">學生信息</a> </td> </tr> </table> </div> </body> </html>
addStudent.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <% String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %> <html> <head> <title>學生註冊</title> <base href="<%=basePath%>"> </head> <body> <div align="center"> <form action="student/addStudent.do" method="post"> <table> <tr> <td>姓名:</td> <td><input type="text" name="name"></td> </tr> <tr> <td>年齡:</td> <td><input type="text" name="age"></td> </tr> <tr> <td> </td> <td><input type="submit" value="注 冊"></td> </tr> </table> </form> </div> </body> </html>
在/WEB-INF/jsp/result.jsp
<%-- Created by IntelliJ IDEA. User: MD Date: 2020/8/13 Time: 20:45 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>註冊結果:${tips}</h1> </body> </html>
listStudent.jsp
<%-- Created by IntelliJ IDEA. User: MD Date: 2020/8/13 Time: 21:10 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %> <html> <head> <title>學生信息</title> <base href="<%=basePath%>"> <script type="text/javascript" src="js/jquery-3.4.1.js"></script> <script type="text/javascript" > $(function () { // 在當前的頁面加載後執行loadStudent函數 loadStudent(); $("#btn").click(function () { loadStudent(); }); }); // 自定義函數 function loadStudent() { $.ajax({ url:"student/queryStudent.do", type:"get", dataType:"json", success:function (data) { // 清除舊數據 $("#info").html(""); $.each(data,function (i,n) { // 添加新數據 $("#info").append("<tr>") .append("<td>"+n.id+"</td>") .append("<td>"+n.name+"</td>") .append("<td>"+n.age+"</td>") .append("</tr>") }) } }); } </script> </head> <body> <div align="center"> <table> <thead> <tr> <td>學號</td> <td>姓名</td> <td>年齡</td> </tr> </thead> <tbody id="info"> </tbody> </table> <input type="button" id="btn" value="查詢數據"> </div> </body> </html>
此時再配置Tomcat運行便可,以後再添加新的功能