在eclipse建立spring+springMVC+Mybatis的專案
阿新 • • 發佈:2019-02-18
現在使用maven構建的專案會讓我們省去jar包的匯入和每個工程都匯入數量較多jar包的苦惱,特別是在團隊開發中,我們應該保證我們使用的jar包的版本一致,使用maven之後,我們僅需要保證pom.xml檔案一致。他會自己按<dependency>節點中配置的資訊找到相應的jar包。
下面是自己學習之後構建Spring+SpringMVC+Mybatis的工程構建過程:
1.首先,我們應該確保eclipse中有maven外掛並正常使用;建立一個maven的webapp專案:
可以看見,這裡的jsp檔案有錯誤,這是因為開始時專案中沒有匯入javax.servlet.http.HttpServlet所在包導致的。我們build
path進包即可,在eclipse建立tomcat的服務之後步驟如下
abcd
2.現在一個maven工程建立好了,之後就是pom.xml和spring的配置檔案的編寫了:
pom.xml的程式碼:當然,需要什麼包到http://mvnrepository.com/去搜索得到<dependency>放到pom.xml檔案中即可;
3.spring和Mybatis的配置檔案:<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ys.test001</groupId> <artifactId>Test001</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>Test001 Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> <scope>test</scope> </dependency> <!-- spring-mvc包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.0.RELEASE</version> </dependency> <!-- jsp顯示資料需要的jar包 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--日誌 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.0</version> </dependency> <!--spring4.0以上json和java物件的轉換jackson包 spring4.0以上需要jackson2.6版本 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.6.1</version> </dependency> <!--mybatis的包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <!--mybatis和spring整合包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- 我使用的連線資料的jar包 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.2.0.RELEASE</version> </dependency> <!--spring事務tx包的引用 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.2.0.RELEASE</version> </dependency> <!--資料庫jar包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.18</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.2</version> </dependency> </dependencies> <build> <finalName>Test001</finalName> </build> </project>
為了方便管理,我們在resources檔案加入資料庫連線資訊:db.properties 並建立config/spring 和 config/mybatis資料夾,存放各自的配置檔案:
log4j.properties:
</pre><pre name="code" class="java"># Global logging configuration log4j.rootLogger=DEBUG, stdout # MyBatis logging configuration... log4j.logger.org.mybatis.example.BlogMapper=TRACE # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
我的db.properties檔案資訊:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
spring-dao.xml檔案:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!--配置資料庫連線屬性-->
<!--配置資料庫連線屬性載入db.properties的資料庫連線資訊檔案 這裡配置有很多學問,需要我以後學習-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="30"/>
<property name="maxIdle" value="5"/>
</bean>
<!-- 讓spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入資料庫連線物件-->
<property name="dataSource" ref="dataSource"/>
<!--載入mybatis配置檔案 這裡mybatis配置檔案的工作都在spring中配置了所以mybatis只是配置別名就可以-->
<property name="configLocation" value="classpath:/config/mybatis/mybatisconfig.xml"/>
</bean>
<!-- mapper掃描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 掃描的包,如果要掃描多個,中間用,隔開 -->
<property name="basePackage" value="com.ys.mybatis.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>
spring-mvc.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!--開啟註解 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!--可以訪問靜態檔案 -->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<!--配置掃描包 -->
<context:component-scan base-package="com.ys.controller"></context:component-scan>
<!-- service包 -->
<context:component-scan base-package="com.ys.serviceimpl"></context:component-scan>
<!--配置檢視解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
<span style="white-space:pre"> </span><span style="font-family: Arial, Helvetica, sans-serif;"><!--</span><span style="font-family: Arial, Helvetica, sans-serif;">以後可能需要檔案上傳和攔截器</span><span style="font-family: Arial, Helvetica, sans-serif;">--></span><span style="white-space:pre">
</span>
</beans>
mybatisconfig.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>
<typeAliases>
<!-- 掃描別名 -->
<package name="com.ys.po"/>
</typeAliases>
<!-- 載入我們的Sql語句的xml檔案 -->
<!-- 使用自動掃描器時,mapper.xml檔案如果和mapper.java介面在一個目錄則此處不用定義mappers -->
</configuration>
4.最後是web.xml載入我們上面的配置檔案:
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<!-- 載入spring配置檔案 -->
<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:config/spring/spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 設定url匹配模式 -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 解決post亂碼 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
5.現在是包和mapper.xml和controller和service編寫:
UserInfo.java:
public class UserInfo {
private int id;
private String username;
private String password;<span style="font-family:Arial, Helvetica, sans-serif;"> 省略了get set方法</span>
UserInfoService.java:
public interface UserInfoService {
public UserInfo getInfoById(int id);
}
UserInfoServiceImpl.java:
@Service
public class UserInfoServiceImpl implements UserInfoService {
@Autowired
private MyPoDaoService daoService;
public UserInfo getInfoById(int id) {
// TODO Auto-generated method stub
if(id!=0&&id<3){
return daoService.GetUserInfo(id);
}else{
return null;
}
}<span style="color:#ff0000;">
</span>
MyPoDaoService.java:
package com.ys.mybatis.mapper;
import com.ys.po.UserInfo;
public interface MyPoDaoService {
public UserInfo GetUserInfo(int id);
}
MyPoDaoService.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.ys.mybatis.mapper.MyPoDaoService">
<select id="GetUserInfo" resultType="com.ys.po.UserInfo">
select * from userinfo where id = #{id}
</select>
</mapper>
HelloController.java:
@Controller
public class HelloController {
@Autowired
private UserInfoServiceImpl userInfoSeriverImpl;
@RequestMapping("/hello")
public String sayHello(HttpServletRequest request, HttpServletResponse response){
request.setAttribute("say", "測試sayHello");
UserInfo infoById = userInfoSeriverImpl.getInfoById(1);
if(infoById!=null){
request.setAttribute("infoById", infoById);
System.out.println(infoById.toString());
}
request.setAttribute("say", "test Say Hello");
return "Hello";
}
}
Hello.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>
<h1>say Hello</h1>
<h2>${say}</h2>
<c:if test="${infoById!=null}">
<h1>您好:${infoById.username}</h1>
</c:if>
<c:if test="${infoById==null }">
<h1>對不起,沒有取得使用者名稱</h1>
</c:if>
</body>
</html>
最後的工程結構如下:
資料庫UserInfo表內容:
執行結果: