STS创建springmvc +mybatis项目
STS创建springmvc +mybatis项目
江上湖人 发表于6个月前
STS创建springmvc +mybatis项目
  • 发表于 6个月前
  • 阅读 38
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 十分钟定制你的第一个小程序>>>   

 

一 项目创建

选择 Spring Legacy  Project next 选择spring mvc project

创建完成项目项目就可以在浏览器上访问(http://localhost:18080/web/)

二 项目结构

   

 我们来看看 web.xml里面的内容

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

上面的配置文件加载了两个配置文件

servlet-context.xml  root-context.xml

maven 项目建议我们将项目中的相关配置文件放到 src\java\resource下面

这里我们改变下项目结构

这样 web.xml中加载配置文件的路径变成从classPath加载

classPath:root-context.xml  classPath:servlet-context.xml

模板创建的项目使用的Spring 是 3.1.1.RELEASE版本 我们换下高点的版本(4.1.4.RELEASE)

servlet-context.xml 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="com.test.web" />
	
	
	
</beans:beans>

<!------------------------------------------------------------------->
这里的	<resources mapping="/resources/**" location="/resources/" />
resource 配置了静态资源的影视 匹配resource 的请求 会映射到 webapp下面的resource 文件

<context:component-scan base-package="com.test.web" /> 
扫描com.test.web下面的注解

org.springframework.web.servlet.view.InternalResourceViewResolver
配置了请求返回的页面返回到 webapp/WEB-INF/views下面对应的JSP 文件

最上面的XML头文件是spring命名空间  等下我会改下这个头文件

项目怎么启动的

  我们在浏览器输入http://localhost:18080/web/ 就能访问到首页了

  这里我们要注意到两个配置 

  web.xml 中servlet的配置是这样的 

	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

这表示项目会拦截一切请求

src/main/java下面有一个controller拦截了 "/"请求

这样一个基本的spring +springmvc 项目我们就搭起来了

 

三 加入mybatis

  上面我们只是实现了拦截请求  ,我们现在加入数据访问层 

 这里我们将mybatis 教由spring 管理 

 pom.xml 要引入相关包

 <!--mybatis-->
 <dependency>  
     <groupId>org.mybatis</groupId>  
     <artifactId>mybatis</artifactId>  
      <version>${mybatis.version}</version>  
  </dependency>  
<!--mybatis整合-->
 <dependency>  
     <groupId>org.mybatis</groupId>  
     <artifactId>mybatis-spring</artifactId>  
     <version>1.2.2</version>  
  </dependency> 
<!-- 高性能连接池 配置数据源-->
 <groupId>com.zaxxer</groupId>  
      <artifactId>HikariCP</artifactId>  
       <version>2.4.7</version>  
 </dependency> 
<!--MySQL连接工具-->
 <dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.34</version>
 </dependency>	

  在 root-context.xml 加入相关配置实现相关功能

  1 引入 数据源配置文件

  2 配置数据源

  3 配置 自动扫描mybatis XML映射文件 dao接口类 事物代理

 接下来我们用mybatis自动生成工具生成 相关文件

<?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="D:\Util\maven\maven-dependcies\mysql\mysql-connector-java\5.1.35\mysql-connector-java-5.1.35.jar"/>

  <context id="context1" >
    <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/shop" userId="root" password="root" />
    <javaModelGenerator targetPackage="com.test.enty" targetProject="web" />
    <sqlMapGenerator targetPackage="com.test.dao.mysql" targetProject="web" />
    <javaClientGenerator targetPackage="com.test.dao" targetProject="web" type="XMLMAPPER" />
    <table schema="shop" tableName="course_info" domainObjectName="coureInfo" enableCountByExample="false" enableDeleteByExample="false"
            enableSelectByExample="false" enableUpdateByExample="false"
            selectByExampleQueryId="false">
   
    </table>
  </context>
</generatorConfiguration>

怎样使用mybatis自动生成插件请参考https://my.oschina.net/u/1377006/blog/824173

现在我么在 HomeController测试下mybatis

public class HomeController {
	@Autowired
	private testMapper mapper;
	@Autowired
	private coureInfoMapper courseMapper;
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		coureInfo t = courseMapper.selectByPrimaryKey(1);
		System.out.println(t.getCname());
		
		
		return "home";
	}
	
}

在控制台中打印出结果

四 返回json 数据

   Spring MVC 要返回json数据的话 需要在方法上加上 @ResponseBody注解

	@RequestMapping(value = "/", method = RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		coureInfo t = courseMapper.selectByPrimaryKey(1);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("data", t);
		System.out.println(t.getCname());
		return map;
	}

当然要在pom.xml中加入相关json解析包

现在附上相关配置文件

jdbc.properties

#application all config

#jdbc c3p0
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/shop?useUnicode=true&amp;characterEncoding=utf-8
jdbc.username = root
jdbc.password = root

root-context.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:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    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 http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
 
    <context:component-scan base-package="com.test.*" />

		<!-- spring后处理器 将后面可以通过${name}的方式引用property中的健 -->
		<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

		<property name="locations">
			<list>
				<!-- 如果有多个属性文件,一并列在这里 -->
				<value>classPath:jdbc.properties</value>
				<!-- <value>xxx.properties</value> -->
			</list>
		</property>
	</bean>

	<!-- 数据源-->
	<bean id = "dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">  
        <property name="driverClassName" value="${jdbc.driver}" />  
        <property name="jdbcUrl" value="${jdbc.url}" />  
        <property name="username" value="${jdbc.username}" />  
        <property name="password" value="${jdbc.password}" />  
        <property name="maximumPoolSize" value="100" />  
        <property name="minimumIdle" value="10" />  
        <property name="connectionTestQuery" value="select 1" />  
        <property name="dataSourceProperties">  
            <props>  
                <prop key="cachePrepStmts">true</prop>  
                <prop key="prepStmtCacheSize">250</prop>  
                <prop key="prepStmtCacheSqlLimit">2048</prop>  
                <prop key="useServerPrepStmts">true</prop>  
            </props>  
        </property>  
    </bean>  
	 <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 自动扫描mapping.xml文件    -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- 错误写法 这里路径分割符用点号是错的  前面要加上classpath -->
        <property name="mapperLocations" value="classpath*:com/test/dao/mysql/*.xml"></property>  
    </bean>  
  
    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.test.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>  
 
    	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
	<!-- 配置 Annotation 驱动,定义事务   启用事务注解   这种方式需在事务方法使用注解-->
	
			<mvc:annotation-driven>
		
	    <!-- 返回json数据,@response使用 -->
		<mvc:message-converters register-defaults="true">
			<bean
				class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>text/html;charset=UTF-8</value>
						<value>application/json;charset=UTF-8</value>
					</list>
				</property>

			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>

</beans>

servlet-context.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:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    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 http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        ">

	<!-- DispatcherServlet Context: defines this servlet's request-processing 
		infrastructure -->

	<!-- Enables the Spring MVC @Controller programming model -->


	<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
		up static resources in the ${webappRoot}/resources directory -->


	<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
		in the /WEB-INF/views directory -->
	   <aop:aspectj-autoproxy />
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		 <!-- value 前面都加上访问路径 http://localhost:18080/mybatis/+webapp -->
		<property name="prefix" value="/WEB-INF/views/" />
	<!-- 	<property name="prefix" value="/pages/" />  -->
		<property name="suffix" value=".jsp" />
	</bean>
	<mvc:annotation-driven />
	
	<mvc:resources location="/WEB-INF/resources/js/" mapping="/js/**"></mvc:resources>
	<mvc:resources location="/WEB-INF/resources/" mapping="/resource/**"></mvc:resources>
	<mvc:resources location="/WEB-INF/resources/img/" mapping="/img/**"></mvc:resources>
	<mvc:resources location="/WEB-INF/resources/css/" mapping="/css/**"></mvc:resources>
	<mvc:resources location="/pages/" mapping="/pages/**"></mvc:resources>

	<!-- 在servletContext.xml中只需要扫描所有带@Controller注解的类, 在applicationContext中可以扫描所有其他带有注解的类(也可以过滤掉带@Controller注解的类) -->
	<context:component-scan base-package="com.test.web*" />



</beans>

pom.xml

<?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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.test</groupId>
	<artifactId>web</artifactId>
	<name>web</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.7</java-version>
		<org.springframework-version>4.1.4.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
		 <mybatis.version>3.2.2</mybatis.version>  
		 	<jackson.version>2.5.0</jackson.version>
	</properties>
	<dependencies>
		<!-- Spring -->
	<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
	
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
				</dependency>
		     		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
	
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
	
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${org.springframework-version}</version>
			<scope>test</scope>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
	<version>${org.springframework-version}</version>
</dependency>
		
	 
    <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis</artifactId>  
            <version>${mybatis.version}</version>  
        </dependency>  

     
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis-spring</artifactId>  
            <version>1.2.2</version>  
        </dependency> 
         
		<dependency>
			<groupId>com.mchange</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.5-pre10</version>
		</dependency>
		<dependency>  
		<!-- 高性能连接池 -->
      <groupId>com.zaxxer</groupId>  
        <artifactId>HikariCP</artifactId>  
         <version>2.4.7</version>  
       </dependency> 
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.34</version>
		</dependency>	
	
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>
		  <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>${org.aspectj-version}</version>
            </dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
			<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>${jackson.version}</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>${jackson.version}</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
        <dependency>
        <groupId>dom4j</groupId>
         <artifactId>dom4j</artifactId>
         <version>1.6.1</version>
         </dependency>
		
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>        
	</dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

标签: Spring MyBatis
共有 人打赏支持
粉丝 3
博文 25
码字总数 18450
×
江上湖人
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: