Java框架搭建-Maven、Mybatis、Spring MVC整合搭建
1. 下載eclipse
到網站下載 http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/marsr
選擇自己所要的版本
2. 新建Maven項目
選擇File –> New –> Maven Project
可看到下面界面
點擊Next,可看到下面界面,我們選擇maven-archetype-webapp
點擊Next,可看到。Group Id為包名,Artifact Id為項目名。這裡我們輸入Group Id=com.cjt, Artifact Id=MyMaven。
最後點擊Finish成功創建項目
3. 項目運行前准備工作
新建項目之後,可以看到錯誤,這是build path與沒有引入javaee包引起的。
1)設置build path
右鍵項目 –> Build Path --> Configure Build Path…
然後選擇Libraries
Maven默認是選擇一個Library的,這個錯誤的,我們雙擊這個來Edit。
下面界面我們選擇Alternate JRE或者Workspace default JRE。這裡我們選擇Alternate JRE。
2)引入javaee包
在pom.xml上引入javaee包
<!-- 導入java ee jar 包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
4. 項目配置文件設置
1) 設置pom.xml
我們現在設置pom.xml,下載jar包,這個過程可能有點慢
Pom.xml:
<projectxmlns="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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cjt</groupId>
<artifactId>MyMaven</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>TestMaven01 Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<!-- spring版本號-->
<spring.version>4.0.2.RELEASE</spring.version>
<!-- mybatis版本號-->
<mybatis.version>3.2.6</mybatis.version>
<!-- log4j日志文件管理包版本-->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- 導入java ee jar 包-->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- spring核心包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-oxm</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>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mybatis核心包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- 導入java ee jar 包-->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- 導入Mysql數據庫鏈接jar包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫-->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- JSTL標簽類-->
<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>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</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-->
<!-- 映入JSON-->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!-- 上傳組件包-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
</dependencies>
<build>
<finalName>TestMaven01</finalName>
</build>
</project>
2) 創建jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=
#定義初始連接數
initialSize=1
#定義最大連接數
maxActive=20
#定義最大空閒
maxIdle=20
#定義最小空閒
minIdle=1
#定義最長等待時間
maxWait=60000
3) log4j.properties
### set log levels ###
#log4j.rootLogger = debug , stdout , D , E
log4j.rootLogger = debug , stdout , D
### output to the console ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%n
log4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n
### Output to the log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ${springmvc.root}/WEB-INF/logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### Save exception information to separate file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ${springmvc.root}/WEB-INF/logs/error.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = ERROR
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
4) spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beansxmlns="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.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自動掃描該包,使SpringMVC認為包下用了@controller注解的類是控制器-->
<context:component-scanbase-package="com.cjt.controller" />
<!--避免IE執行AJAX時,返回JSON出現下載文件-->
<beanid="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<propertyname="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 啟動SpringMVC的注解功能,完成請求和注解POJO的映射-->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<propertyname="messageConverters">
<list>
<refbean="mappingJacksonHttpMessageConverter" /> <!-- JSON轉換器-->
</list>
</property>
</bean>
<!-- 定義跳轉的文件的前後綴 ,視圖模式配置-->
<beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 這裡的配置我的理解是自動給後面action的方法return的字符串加上前綴和後綴,變成一個 可用的url地址-->
<propertyname="prefix" value="/WEB-INF/jsp/" />
<propertyname="suffix" value=".jsp" />
</bean>
<!-- 配置文件上傳,如果沒有使用文件上傳可以不用配置,當然如果不配,那麼配置文件中也不必引入上傳組件包-->
<beanid="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默認編碼-->
<propertyname="defaultEncoding" value="utf-8" />
<!-- 文件大小最大值-->
<propertyname="maxUploadSize" value="10485760000" />
<!-- 內存中的最大值-->
<propertyname="maxInMemorySize" value="40960" />
</bean>
</beans>
5) spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beansxmlns="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.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自動掃描-->
<context:component-scanbase-package="com.cjt.service" />
<!-- 引入配置文件-->
<beanid="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<propertyname="location" value="classpath:jdbc.properties" />
</bean>
<beanid="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<propertyname="driverClassName" value="${driver}" />
<propertyname="url" value="${url}" />
<propertyname="username" value="${username}" />
<propertyname="password" value="${password}" />
<!-- 初始化連接大小-->
<propertyname="initialSize" value="${initialSize}"></property>
<!-- 連接池最大數量-->
<propertyname="maxActive" value="${maxActive}"></property>
<!-- 連接池最大空閒-->
<propertyname="maxIdle" value="${maxIdle}"></property>
<!-- 連接池最小空閒-->
<propertyname="minIdle" value="${minIdle}"></property>
<!-- 獲取連接最大等待時間-->
<propertyname="maxWait" value="${maxWait}"></property>
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件-->
<beanid="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<propertyname="dataSource" ref="dataSource" />
<!-- 自動掃描mapping.xml文件-->
<propertyname="mapperLocations" value="classpath:com/cjt/mapping/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring會自動查找其下的類-->
<beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">
<propertyname="basePackage" value="com.cjt.dao" />
<propertyname="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- (事務管理)transaction manager, use JtaTransactionManager for global tx-->
<beanid="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<propertyname="dataSource" ref="dataSource" />
</bean>
</beans>
上面的文件都創建在resources文件夾下
5. 數據庫代碼自動生成
1)新建表
首先,我們新建表user_t,字段如下:
2)下載包
下載包有:mybatis-3.2.6.jar、mybatis-generator-core-1.3.3.jar、mysql-connector-java-5.1.39-bin.jar
3)運行-自動生成代碼
新建一個文件夾,下面包括如下文件
generatorConfig.xml是生成代碼的xml文件,內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 數據庫驅動-->
<classPathEntry location="mysql-connector-java-5.1.39-bin.jar"/>
<contextid="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<propertyname="suppressDate" value="true"/>
<!-- 是否去除自動生成的注釋 true:是 : false:否-->
<propertyname="suppressAllComments" value="true"/>
</commentGenerator>
<!--數據庫鏈接URL,用戶名、密碼-->
<jdbcConnectiondriverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password="">
</jdbcConnection>
<javaTypeResolver>
<propertyname="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGeneratortargetPackage="com.cjt.domain" targetProject="src">
<propertyname="enableSubPackages" value="true"/>
<propertyname="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGeneratortargetPackage="com.cjt.mapping" targetProject="src">
<propertyname="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGeneratortype="XMLMAPPER" targetPackage="com.cjt.dao" targetProject="src">
<propertyname="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是數據庫中的表名或視圖名 domainObjectName是實體類名-->
<tabletableName="user_t" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
然後我們用cmd命令進入到新建的文件夾下面,輸入:
java -jar mybatis-generator-core-1.3.3.jar -configfile generatorConfig.xml -overwrite
最後,代碼生成了。
備注:代碼自動生成這裡通過命令行的方式,讀者也可以通過eclipse的插件方式生成。
6. 代碼開始
新建包,如下: (箭頭的都是上面自動生成的代碼)
IUserService.java
public interface IUserService {
public User getUserById(int id);
}
UserServiceImpl.java
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao userDao;
public UserServiceImpl() {
System.out.println("UserServiceImpl");
}
public User getUserById(int id) {
return userDao.selectByPrimaryKey(id);
}
}
UserController.java
@Controller
@RequestMapping("/user")
public class UserController {
public UserController() {
System.out.println("UserController");
}
@Resource
private IUserService userService;
@RequestMapping("/showUser")
public String toIndex(HttpServletRequest request,Model model) {
System.out.println("UserController showUser");
int id = Integer.parseInt(request.getParameter("id"));
User user= userService.getUserById(id);
model.addAttribute("user", user);
return "showUser";
}
}
在WEB-INF下新建一個目錄jsp,下面新建文件showUser.jsp
showUser.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" import="java.util.*,com.cjt.domain.*"%>
<!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>
</head>
<body>
${user.userName}
</body>
</html>
最後,附上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"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<!-- Spring和mybatis的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- 編碼過濾器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 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>
<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>
<!-- 此處可以可以配置成*.do,對應struts的後綴習慣 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
上面,代碼生成完成了。
可以下載項目:見這篇 http://www.linuxidc.com/Linux/2016-08/134156.htm
下載自動生成包:
到Linux公社資源站下載:
------------------------------------------分割線------------------------------------------
免費下載地址在 http://linux.linuxidc.com/
用戶名與密碼都是www.linuxidc.com
具體下載目錄在 /2016年資料/8月/11日/Java框架搭建-Maven、Mybatis、Spring MVC整合搭建/
下載方法見 http://www.linuxidc.com/Linux/2013-07/87684.htm
------------------------------------------分割線------------------------------------------
Spring MVC+Spring3+Hibernate4開發環境搭建 http://www.linuxidc.com/Linux/2013-07/87119.htm
Spring MVC整合Freemarker基於注解方式 http://www.linuxidc.com/Linux/2013-02/79660.htm
基於注解的Spring MVC簡單介紹 http://www.linuxidc.com/Linux/2012-02/54896.htm
Spring MVC 框架搭建及詳解 http://www.linuxidc.com/Linux/2012-01/52740.htm
Spring MVC使用Cron表達式的定時器 http://www.linuxidc.com/Linux/2014-12/110733.htm
簡單的Spring MVC經典案例 http://www.linuxidc.com/Linux/2016-04/129718.htm