1. 程式人生 > >SSM框架搭建(spring+springmvc+mybatis)

SSM框架搭建(spring+springmvc+mybatis)

一.建立web專案(eclipse)

 File-->new-->Dynamic Web Project (這裡我們建立的專案名為SSM)

下面是大致目錄結構

 

二. SSM所需jar包。

 jar包連結:https://pan.baidu.com/s/1dTClhO 密碼:n4mm

三.整合開始

1.mybatis配置檔案(resource/mybatis/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>

</configuration>

2.Dao,mybatis整合spring,通過spring管理

SqlSessionFactory、mapper代理物件

(resource/spring/applicationContext-dao.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">

	<!-- 資料庫連線池 -->
	<!-- 載入配置檔案 -->
	<context:property-placeholder location="classpath:*.properties" />
	<!-- 資料庫連線池 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		destroy-method="close">
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="maxActive" value="10" />
		<property name="minIdle" value="5" />
	</bean>
	<!-- 讓spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 資料庫連線池 -->
		<property name="dataSource" ref="dataSource" />
		<!-- 載入mybatis的全域性配置檔案 -->
		<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
	</bean>
	<!-- 自動掃描 將Mapper介面生成代理注入到Spring -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.mapper" />
	</bean>
</beans>

這裡用的是阿里的連線池,當然也可以用c3p0,個人建議用阿里

3. 所有的實現類都放到spring容器中管理。由spring建立資料庫連線池,並有spring管理實務。

(resource/spring/applicationContext-service.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">
		
		<!-- spring自動去掃描base-pack下面或者子包下面的java檔案-->
		<!--管理Service實現類-->
		<context:component-scan base-package="com.service"/>
</beans>

配置spring管理實務

 (resource/spring/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="add*" propagation="REQUIRED" />
			<tx:method name="create*" 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="select*" 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(* com.service.*.*(..))" />
	</aop:config>
</beans>

4. Springmvc整合spring框架,由springmvc管理controller

(resource/spring/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:p="http://www.springframework.org/schema/p"
	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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
	
	<!-- 掃描controller -->
	<context:component-scan base-package="com.controller" />
	
	<!-- Spring 來掃描指定包下的類,並註冊被@Component,@Controller,@Service,@Repository等註解標記的元件 -->
	<mvc:annotation-driven />
	
	<!-- 配置SpringMVC的檢視解析器-->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

5. 2中載入的屬性配置檔案(dbconfig.properties)

根據自己的資料庫更改使用者名稱密碼以及庫

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

6. 配置log4j

(log4j.properties)

log4j.rootLogger=error,CONSOLE,A
log4j.addivity.org.apache=false

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=error
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} -%-4r [%t] %-5p  %x - %m%n
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.Encoding=gbk
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout


log4j.appender.A=org.apache.log4j.DailyRollingFileAppender  
log4j.appender.A.File=${catalina.home}/logs/FH_log/PurePro_
log4j.appender.A.DatePattern=yyyy-MM-dd'.log'
log4j.appender.A.layout=org.apache.log4j.PatternLayout  
log4j.appender.A.layout.ConversionPattern=[FH_sys]  %d{yyyy-MM-dd HH\:mm\:ss} %5p %c{1}\:%L \: %m%n


 (log4j.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

	<!-- Appenders -->
	<appender name="console" class="org.apache.log4j.ConsoleAppender">
		<param name="Target" value="System.out" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d{yyyy HH:mm:ss} %-5p %c - %m%n" />
		</layout>
	</appender>
	
	<!-- Application Loggers -->
	<logger name="com">
		<level value="error" />
	</logger>
	
	<!-- 3rdparty Loggers -->
	<logger name="org.springframework.core">
		<level value="error" />
	</logger>	
	
	<logger name="org.springframework.beans">
		<level value="error" />
	</logger>
	
	<logger name="org.springframework.context">
		<level value="error" />
	</logger>

	<logger name="org.springframework.web">
		<level value="error" />
	</logger>

	<logger name="org.springframework.jdbc">
		<level value="error" />
	</logger>

	<logger name="org.mybatis.spring">
		<level value="error" />
	</logger>
	<logger name="java.sql">
		<level value="error" />
	</logger>
	<!-- Root Logger -->
	<root>
		<priority value="error" />
		<appender-ref ref="console" />
	</root>
	
</log4j:configuration>

 SSM框架整合完成,至於mybatis逆向工程生成的mapper.xml和pojo請放到第一張圖的目錄下

注:逆向工程是根據資料庫表反向生成pojo以及mapper.xml,所以,請先自動在資料庫配置好user表。逆向工程得配置在下面得連結裡面有詳細註釋。

測試資料庫表(User)

    private String id;

    private String username;

    private String password;

    private String company;

    private Integer age;

    private Integer sex;

根據型別建立表即可

逆向工程專案我會貼出連結,解壓匯入改路徑執行main方法就會自動生成了,注意配置生成的路徑

逆向工程連結: 連結:https://pan.baidu.com/s/1QvSskH2UEC6EQF7MgVDOAQ 密碼:t2pc

到這裡專案整合完成,接下來是測試!
 UserController.java

package com.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.pojo.User;
import com.service.UserService;

@Controller
@RequestMapping("/user")  
public class UserController {
	
	@Resource(name="userService")
	private UserService userService;
	/**
	 * 根據id查詢
	 */
	@RequestMapping(value="/queryById")
	public ModelAndView queryById(HttpServletRequest request){
		ModelAndView mv = new ModelAndView();
		String id = request.getParameter("id");
		try{
			User var = userService.findById(id);
			mv.setViewName("index");
			mv.addObject("var", var);
		} catch(Exception e){
            e.printStackTrace();
		}
		return mv;
	}
}

UserService.java

package com.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.mapper.UserMapper;
import com.pojo.User;

@Service("userService")
public class UserService {
	@Resource
	private UserMapper dao;
	/*
	* 通過id獲取資料
	*/
	public User findById(String id)throws Exception{
		return (User)dao.selectByPrimaryKey(id);
	}
}

補上之前漏掉得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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	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">
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<!-- 載入spring容器 -->
	<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>

	<!-- 解決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>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param> -->
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>


	<!-- springmvc的前端控制器 -->
<!-- 	<servlet>
		<servlet-name>taotao-manager</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		contextConfigLocation不是必須的, 如果不配置contextConfigLocation, springmvc的配置檔案預設在:WEB-INF/servlet的name+"-servlet.xml"
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring/springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>SSM</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping> -->
	
	  <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:spring/springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
	
</web-app>

為節省篇幅,更快的搭建成功,這裡只寫了一個方法,根據id查詢資料

WebContent/index.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">
<%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>查詢使用者</title>
</head>
<body>
	<form action="user/queryById.do" method="post">
		輸入要查詢的id:	<input type="text" name="id" value="123456"/>
		<button type="submit">提交</button>
	</form>
</body>
</html>

 WebContent/WEB-INF/jsp/index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@page import="com.pojo.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<style type="text/css">
	.td td{
		width: 100px;
	}
	.table{
		text-align: center;
		margin: 0 auto;
	}
</style>
</head>
<body>
<%
	User user = ((User)request.getAttribute("var"));
%>

	<table class="table">
		<tr class="td">
			<td>ID</td>
			<td>使用者名稱</td>
			<td>密碼</td>
			<td style="width: 200px">公司</td>
			<td>年齡</td>
			<td>性別</td>
		</tr>
<%if(user!=null){%>
		<tr class="td">
			<td><%=user.getId()%></td>
			<td><%=user.getUsername()%></td>
			<td><%=user.getPassword()%></td>
			<td><%=user.getCompany()%></td>
			<td><%=user.getAge()%></td>
			<td><%=user.getSex()==1?"男":"女"%></td>
		</tr>
	<%}else{ %>
		<tr class="td">
			<td style="color: red;">暫無相關資料</td>
		</tr>
<%} %>
	</table>

</body>
</html>

啟動專案,輸入localhost:8080/SSM 訪問

為方便新手查錯,博主按照博文重新搭建了一次,測試無誤後將專案打包,上傳至雲盤,供您使用。(建議:希望您按照博文從頭搭建,便於印象深刻)

專案完整連結(含資料庫): https://pan.baidu.com/s/17O8HgkoSYblFfC3uziMrdA 密碼:cw77

 文中連結失效+Q:171727855  補發

有問題加群:757477675 (Java企業開發交流群,資料免費分享)

轉載文章請註明出處!