上一篇我使用maven創建一個web項目Maven項目的搭建 。今天將在那個的基礎上進行完善,做成SSM模式的web框架.
1. 在src/mian/java/下面創建Package,格式如下:
2. 在src/main/resources下創建配置文件
其中log4j.properties爲日誌文件;
spring-mvc.xml爲springMVC的配置文件;
spring-mybatis.xml爲spring和mybatis的整合文件.
3.修改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>test-maven-web</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和mybatis的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- Spring監聽器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring內存溢出監聽器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Spring MVC -->
<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-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<!-- 字符編碼過濾器 -->
<filter>
<filter-name>characterEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
加載Spring和mybatis的配置文件
Spring監聽器
防止Spring內溢出監聽器
Spring MVC
字符編碼過濾器
4. 配置spring-mybatis.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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"
default-autowire="byName">
<!-- 自動掃描 -->
<context:component-scan base-package="com.cn.service" />
<!-- 未使用org.apache.commons.dbcp.BasicDataSource -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/testsql?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="123456" />
<!-- 初始化連接大小
<property name="initialSize" value="${initialSize}"></property>
連接池最大數量
<property name="maxActive" value="${maxActive}"></property>
連接池最大空閒
<property name="maxIdle" value="${maxIdle}"></property>
連接池最小空閒
<property name="minIdle" value="${minIdle}"></property>
獲取連接最大等待時間
<property name="maxWait" value="${maxWait}"></property> -->
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自動掃描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/cn/mapping/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring會自動查找其下的類 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.cn.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
5. spring-mvc.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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自動掃描該包,使SpringMVC認爲包下用了@controller註解的類是控制器 -->
<context:component-scan base-package="com.cn.controller" />
<!--避免IE執行AJAX時,返回JSON出現下載文件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 定義跳轉的文件的前後綴 ,視圖模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 自動給後面action的方法return的字符串加上前綴和後綴,變成一個 可用的url地址 -->
<property name="prefix" value="/jsp" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置文件上傳,如果沒有使用文件上傳可以不用配置,當然如果不配,那麼配置文件中也不必引入上傳組件包 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默認編碼 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 內存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
<!-- 解除servlet對靜態資源文件訪問的限制 -->
<mvc:default-servlet-handler/>
<!-- 不然訪問不到@RequestMapping的路徑 -->
<mvc:annotation-driven/>
</beans>
至此,SSM框架已經搭載完成了,
現在寫功能進行測試吧
6. 完成查詢功能
在此先說一下mybatis的Generator代碼生成工具,可以通過數據庫表,直接生成實體類,dao接口,以及mapper的增刪改查,不清楚的可以查看我寫的博文,使用Generator自動生成代碼 。
數據庫中有一張表,結構如下:
先在Service聲明一個接口一個實現類:
接口代碼如下:
package com.cn.service;
import com.cn.pojo.Root;
public interface RootService {
/**
* 通過id主鍵查詢數據
* @return
*/
public Root selectByPrimaryKey(Integer id);
}
實現類通過@Autowired調用dao層接口進行數據查詢
package com.cn.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cn.dao.RootMapper;
import com.cn.pojo.Root;
import com.cn.service.RootService;
@Service("rootService")
public class RootServiceImpl implements RootService {
@Autowired
private RootMapper rootMapper;
@Override
public Root selectByPrimaryKey(Integer id) {
// TODO Auto-generated method stub
return this.rootMapper.selectByPrimaryKey(id);
}
}
Controller層代碼:
package com.cn.controller;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
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.cn.pojo.Root;
import com.cn.service.RootService;
@Controller
public class RootController {
private static Logger logger = Logger.getLogger(RootController.class);
@Autowired
private RootService rootservice = null;
@RequestMapping(value = "/manage/rootId")
@ResponseBody
public String rootById(HttpServletRequest request) {
String id = request.getParameter("id");
logger.info("通過id進行Root查詢,id是:" + id);
Root root = rootservice.selectByPrimaryKey(1);
if (root == null) {
return "no data!";
} else {
return root.getRootName();
}
}
}
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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.2.1.js"></script>
<title>index頁面</title>
</head>
<body>
<h1>七夕節</h1>
id:<input type="text" id="txtId"><span id="contentSpan"></span><br/>
<input type="button" value="查詢" id="searchBtn">
<script type="text/javascript">
$(function() {
$("#searchBtn").click(function() {
var id = $("#txtId").val();
$.post("${pageContext.request.contextPath}/manage/rootId",{"id":id}, function (data) {
$("#contentSpan").text(data);
})
})
});
</script>
</body>
</html>
頁面使用jquery異步加載,所以項目中要添加jquery支持,最終整個目錄結構如下圖: