zoukankan      html  css  js  c++  java
  • Maven + SSM环境搭建

    Maven + SSM

    之前Maven+SSM都是照着搭建的,自己想写点什么的时候发现搭建的过程不清楚。

    于是花了时间边整理思路边搭建,并把搭建过程记录下来。

    视频看来终觉浅,还是需要自己动手实践,捋顺思路记忆才会深刻。

    构建Maven相关工程和模块

    • 首先创建一个父工程,选择Maven Project选项。

    • 勾选上Create a simple project,然后点击next

    • 注意父工程打包方式为pom

    • 点击finish,父工程创建完成。

    • 将鼠标移动到之前创建好的demo-parent,点击鼠标右键,选择Maven->New Maven Module Project.

      (也可直接创建Maven Module然后指定parent。)

    • 模块名为demo-dao,Parent Project为demo-parent.

    • 注意打包方式为jar,点击finish即可,demo-dao模块就创建完成了。

    • 按照相同的方法创建Service模块,注意打包方式也为jar。

    • 接下来创建demo-web

    • 此处注意打包方式为war

    • 创建完demo-web后会发现,报错这时因为打包为war,因为标准的web程序结构,

      而我们目录结构的webapp下缺少WEB-INF文件夹和web.xml文件。

    • 接下来我们创建一个WEB-INF文件夹,然后在其中创建一个空的web.xml文件。

    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_2_5.xsd" version="2.5">
      <display-name>demo-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>
    </web-app>
    
    • 接下来创建demo-pojo,存放所有pojo. (也要选择create a simple project)

    • 打包方式同样为jar

    依赖项

    • 首先编辑demo-parent中的pom.xml

    pom.xml

    <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/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.demo</groupId>
      <artifactId>demo-parent</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>pom</packaging>
      <modules>
      	<module>demo-dao</module>
      	<module>demo-service</module>
      	<module>demo-web</module>
      	<module>demo-pojo</module>
      </modules>
      
        <!-- 集中定义依赖版本号 -->
    	<properties>
    		<junit.version>4.12</junit.version>
    		<spring.version>4.2.4.RELEASE</spring.version>
    		<pagehelper.version>4.0.0</pagehelper.version>
    		<servlet-api.version>2.5</servlet-api.version>	
    		<mybatis.version>3.2.8</mybatis.version>
    		<mybatis.spring.version>1.2.2</mybatis.spring.version>
    		<mybatis.paginator.version>1.2.15</mybatis.paginator.version>
    		<mysql.version>8.0.11</mysql.version>		
    		<druid.version>1.0.15</druid.version>		
    	</properties>
    	
    	<dependencyManagement>
    		<dependencies>	
    			<!-- Spring -->
    			<dependency>
            		<groupId>org.springframework</groupId>
            		<artifactId>spring-core</artifactId>
            		<version>${spring.version}</version>       
        		</dependency>
    			<dependency>
    				<groupId>org.springframework</groupId>
    				<artifactId>spring-context</artifactId>
    				<version>${spring.version}</version>
    			</dependency>
    			<dependency>
    				<groupId>org.springframework</groupId>
    				<artifactId>spring-beans</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-jdbc</artifactId>
    				<version>${spring.version}</version>
    			</dependency>
    			<dependency>
    				<groupId>org.springframework</groupId>
    				<artifactId>spring-aspects</artifactId>
    				<version>${spring.version}</version>
    			</dependency>
    			<dependency>
    				<groupId>org.springframework</groupId>
    				<artifactId>spring-jms</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>
    			<dependency>
            		<groupId>org.springframework</groupId>
            		<artifactId>spring-tx</artifactId>    
            		<version>${spring.version}</version> 
        		</dependency>
        		<dependency>
            		<groupId>org.springframework</groupId>
            		<artifactId>spring-web</artifactId>
            		<version>${spring.version}</version> 
        		</dependency>
    				
    		  	<!-- Mybatis -->
    			<dependency>
    				<groupId>org.mybatis</groupId>
    				<artifactId>mybatis</artifactId>
    				<version>${mybatis.version}</version>
    			</dependency>
    			<dependency>
    				<groupId>org.mybatis</groupId>
    				<artifactId>mybatis-spring</artifactId>
    				<version>${mybatis.spring.version}</version>
    			</dependency>
    			<dependency>
    				<groupId>com.github.miemiedev</groupId>
    				<artifactId>mybatis-paginator</artifactId>
    				<version>${mybatis.paginator.version}</version>
    			</dependency>		
    			<!-- MySql -->
    			<dependency>
    				<groupId>mysql</groupId>
    				<artifactId>mysql-connector-java</artifactId>
    				<version>${mysql.version}</version>
    			</dependency>
    			<!-- 连接池 -->
    			<dependency>
    				<groupId>com.alibaba</groupId>
    				<artifactId>druid</artifactId>
    				<version>${druid.version}</version>
    			</dependency>		
    			<dependency>
    			    <groupId>org.csource.fastdfs</groupId>
    			    <artifactId>fastdfs</artifactId>
    			    <version>1.2</version>
    			</dependency>
    	</dependencies>
    	</dependencyManagement>
    	
    	<build>
    		<plugins>			
    			<!-- java编译插件 -->
    			<plugin>
    				<groupId>org.apache.maven.plugins</groupId>
    				<artifactId>maven-compiler-plugin</artifactId>
    				<version>3.2</version>
    				<configuration>
    					<source>1.8</source>
    					<target>1.8</target>
    					<encoding>UTF-8</encoding>
    				</configuration>
    			</plugin>
    		</plugins>
    	</build>
    </project>
    

    Dao

    • 在demo-dao下面的src/main/java和src/main/resoures下创建com.demo.mapper包。

    • 编辑demo-dao的pom.xml
    <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/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <parent>
        <groupId>com.demo</groupId>
        <artifactId>demo-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
      </parent>
      <artifactId>demo-dao</artifactId>
      
       <dependencies>
      	<dependency>
    	    <groupId>com.github.pagehelper</groupId>
    	    <artifactId>pagehelper</artifactId>
    	    <version>4.0.0</version>
    	</dependency>	
      	 <!-- Mybatis -->
    	<dependency>
    		<groupId>org.mybatis</groupId>
    		<artifactId>mybatis</artifactId>			
    	</dependency>
    		<dependency>
    		<groupId>org.mybatis</groupId>
    		<artifactId>mybatis-spring</artifactId>					
    	</dependency>
    	<dependency>
    		<groupId>com.github.miemiedev</groupId>
    		<artifactId>mybatis-paginator</artifactId>			
    	</dependency>		
    	<!-- MySql -->
    	<dependency>
    	    <groupId>mysql</groupId>
    	    <artifactId>mysql-connector-java</artifactId>	   
    	</dependency>
    	<!-- 连接池 -->
    	<dependency>
    		<groupId>com.alibaba</groupId>
    		<artifactId>druid</artifactId>		
    	</dependency>		
    	<!-- Spring依赖 -->
        <!-- 1.Spring核心依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>       
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>      
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>       
        </dependency>
    	<!-- 2.Spring dao依赖 -->
    	<!-- spring-jdbc包括了一些如jdbcTemplate的工具类 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>        
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>     
        </dependency>
        <!-- 3.Spring web依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <!-- 4.Spring test依赖:方便做单元测试和集成测试 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
        <!-- junit -->
        <dependency>
    	    <groupId>junit</groupId>
    	    <artifactId>junit</artifactId>
    	    <scope>test</scope>
    	</dependency>
    	<!-- 依赖deme-pojo -->
    	<dependency>
    		<groupId>com.demo</groupId>
    		<artifactId>demo-pojo</artifactId>
    		<version>0.0.1-SNAPSHOT</version>
    	</dependency>
      </dependencies>
    </project>
    

    dao需要使用到pojo所以要依赖pojo.

    • 在数据库中创建一个名为demo的数据库,并创建一张tb_user表

    CREATE TABLE `tb_user` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `name` varchar(255) DEFAULT NULL,
      `password` varchar(255) DEFAULT NULL,
      `createtime` datetime DEFAULT NULL,
      `verification` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT '0' COMMENT '0代表未验证,1代表已验证。',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
    
    • 接下来创建pojo类,在demo-pojo下创建一个com.demo.pojo包,并根据表结构创建User类。
    package com.demo.pojo;
    
    import java.util.Date;
    
    /**
     * @author 依风
     *	
     */
    public class User {
    	//id主键自增,故无set方法,且不传入构造器。
    	private Integer id;
    	//用户名及密码
    	private String userName;
    	private String password;
    	//创建时间
    	private Date createTime;
    	//是否验证,未验证为"0",验证为"1"
    	private String verification;
    	
    	public User() {
    		super();
    		// TODO Auto-generated constructor stub
    	}
    
    	public User(String userName, String password, Date createTime, String verification) {
    		super();
    		this.userName = userName;
    		this.password = password;
    		this.createTime = createTime;
    		this.verification = verification;
    	}
    
    	public Integer getId() {
    		return id;
    	}
    
    	public String getUserName() {
    		return userName;
    	}
    
    	public void setUserName(String userName) {
    		this.userName = userName;
    	}
    
    	public String getPassword() {
    		return password;
    	}
    
    	public void setPassword(String password) {
    		this.password = password;
    	}
    
    	public Date getCreateTime() {
    		return createTime;
    	}
    
    	public void setCreateTime(Date createTime) {
    		this.createTime = createTime;
    	}
    
    	public String getVerification() {
    		return verification;
    	}
    
    	public void setVerification(String verification) {
    		this.verification = verification;
    	}
    }
    
    
    • 接下来我们在demo-dao中编辑接口与文件和对应的xml文件。

      结构如下图所示:

    TbUserMapper.java

    package com.demo.mapper;
    
    import com.demo.pojo.User;
    
    /**
     * @author 依风
     * tb_user表的dao操作
     */
    public interface TbUserMapper {
    	
    	/** 向tb_user表中插入一条记录
    	 * @param user 插入记录
    	 * @return 受影响的行数
    	 */
    	int insertUser(User user);
    }
    
    

    TbUserMapper.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">
    
    <!-- 注意此处是包名+接口名,xml文件名和接口文件名要一致 -->    
    <mapper namespace = "com.demo.mapper.TbUserMapper" >
        <!-- 根据ID查询客户信息 -->
        <!-- id要和接口文件中的方法名一致 -->
        <insert id = "insertUser" parameterType = "com.demo.pojo.User" >
            INSERT INTO tb_user(name,password,createtime,verification) 
            VALUES (#{userName}, #{password}, #{createTime},#{verification}) 
            <!-- 注意参数名要和类中参数名保持一致,否则可能无法获取参数-->
        </insert>
    </mapper>
    
    • 接下来我们要在demo-dao中创建几个文件夹,并创建对应文件:

    db.properties存放数据库的驱动信息,连接地址,用户名密码等。

    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/demo?characterEncoding=utf-8
    jdbc.username=xxxx
    jdbc.password=xxxx
    

    此处注意jdbc.driver=com.mysql.cj.jdbc.Driver,不同版本的写法不一致,较老版本没有cj。

    用户名和密码填写自己的密码就可以了。

    paalicationContext-dao.xml配置srping与数据库的相关信息。

    <?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.2.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/util http://www.springframework.org/schema/util/spring-util.xsd">
    
    	<!-- 数据库连接池 -->
    	<!-- 加载配置文件 -->
    	<context:property-placeholder location="classpath*:properties/*.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>
    	<!-- 基于MapperScannerConfigurer,会自动扫描指定包下的接口文件和映射文件 -->
    	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    		<property name="basePackage" value="com.demo.mapper" />
    	</bean>
    </beans>
    

    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>
    	<plugins>
    		<!-- com.github.pagehelper 为 PageHelper 类所在包名 -->
    		<plugin interceptor="com.github.pagehelper.PageHelper">
    			<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL 六种数据库-->
    			<property name="dialect" value="mysql"/>
    		</plugin>
    	</plugins>
    </configuration>
    
    • 接下来我们测试下dao有没有问题

      在demo-dao中的src/test/java下创建一个com.demo.dao.test.并创建一个类DaoTest.java

    DaoTest.java

    package com.demo.dao.test;
    
    import java.util.Date;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import com.demo.mapper.TbUserMapper;
    import com.demo.pojo.User;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    //加载classpath路径下(即src/main/resource目录下)
    //srping文件夹中所有已application开头的文件,*代表任意字符。
    @ContextConfiguration(locations="classpath:spring/application*.xml")
    public class DaoTest {
    	
    	@Autowired
    	private TbUserMapper tbUserMapper;
    	
    	@Test
    	public void insertUserTest() {
    		tbUserMapper.insertUser(new User("hcf","123",new Date(),"0"));
    	}
    	
    }
    

    @ContextConfiguration(locations="classpath:spring/application*.xml")加载指定的xml文件,xml文件中主要有

    配置数据源,将接口文件和映射文件匹配起来。由于该模块打包方法为jar,所以测试是需要加载xml文件。

    如果是war,则在tomcat中启动,并在web.xml中配置加载指定文件即可(tomcat会自动加载web.xml)。

    然后将鼠标点击insertUserTest方法名,鼠标右键选择Run as->JUnit Test即可。

    不出意外应该运行成功的,如果不成功根据错误信息找下bug。

    运行成功后数据库中就会出现一条记录。

    Service

    Dao没有问题后,我们来构建Service.

    首先编辑demo-service中的pom.xml

    <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/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <parent>
        <groupId>com.demo</groupId>
        <artifactId>demo-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
      </parent>
      <artifactId>demo-service</artifactId>
      
      <dependencies>
      	<!-- Spring依赖 -->
        <!-- 1.Spring核心依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>       
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>        
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>       
        </dependency>
    	<!-- 2.Spring dao依赖 -->
    	<!-- spring-jdbc包括了一些如jdbcTemplate的工具类 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>       
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>        
        </dependency>
        <!-- 3.Spring web依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>       
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>      
        </dependency>
        <!-- 4.Spring test依赖:方便做单元测试和集成测试 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>       
        </dependency>
        <!-- junit -->
        <dependency>
    		<groupId>junit</groupId>
    		<artifactId>junit</artifactId>
    	</dependency>
        <!-- dao  -->
      	<dependency>
      		<groupId>com.demo</groupId>
      		<artifactId>demo-dao</artifactId>
      		<version>0.0.1-SNAPSHOT</version>
      	</dependency>
      </dependencies>
    </project>
    

    上面主要就是Spring相关依赖,注意一点Service需要引用Dao,所以需要依赖Dao。

    • 接下来我们在demo-service下创建一个com.demo.service包,并编写UserService类。

    UserService.java

    package com.demo.service;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.demo.mapper.TbUserMapper;
    import com.demo.pojo.User;
    
    @Service
    public class UserService {
    	
    	@Autowired
    	private TbUserMapper tbUserMapper;
    	
        //插入一条数据
    	public void insert(User user) {
    		tbUserMapper.insertUser(user);
    	}
    }
    
    • 接下来我们需要在src/main/resources目录下创建一个spring文件夹。

      在里面需要有两个文件。

    一个是applicationContext-dao.xml,一个是applicationContext.xml

    applicationContext-dao.xml与demo-dao中的applicationContext-dao.xml相同,直接复制即可。

    我们来看下applicationContext.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:dubbo="http://code.alibabatech.com/schema/dubbo" 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.xsd
            http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:component-scan base-package="com.demo.*"></context:component-scan>
    </beans>
    

    可以看大家里面只有一个包扫描配置,扫描所有以com.demo开头的包,*代表任意。

    配置这个主要是位置扫描指定包中的注解,例如扫描UserServcie.java中的@Autowired,@Service注解。

    • 接下来测试下Service

    在src/test/java中创建一个com.demo.service.test包,然后创建UserServiceTest.java类。

    package com.demo.service.test;
    
    import java.util.Date;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import com.demo.pojo.User;
    import com.demo.service.UserService;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations="classpath:spring/application*.xml")
    public class UserServiceTest {
    	
    	@Autowired
    	private UserService userService;
    	
    	@Test
    	public void insertUser() {
    		userService.insert(new User("hcf","321",new Date(),"0"));
    	}
    }
    

    注意看locations="classpath:spring/application*.xml",Service调用Dao,所以Dao也需要加载,加载完的Dao

    被Service中的@Autowired注入到Servcie中,Service再调用Dao。Dao并不会自己自动加载,需要外部指定加载。

    然后将鼠标放在方法名上,右击Run as->JUnit Test.

    然后运行成功,数据库中又会多一条记录。

    Controller

    Dao和Servcie完成后就剩下最后的Conttroller了。Controller需要引用Servcie,而Servcie会引用Dao,Controller也会间接引用Dao。

    首先来看demo-web中的pom.xml

    <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/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <parent>
        <groupId>com.demo</groupId>
        <artifactId>demo-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
      </parent>
      <artifactId>controller</artifactId>
      <packaging>war</packaging>
      
      <dependencies>
      	<!-- Spring依赖 -->
        <!-- 1.Spring核心依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
    	<!-- 2.Spring dao依赖 -->
    	<!-- spring-jdbc包括了一些如jdbcTemplate的工具类 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </dependency>
        <!-- 3.Spring web依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <!-- 4.Spring test依赖:方便做单元测试和集成测试 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
        
        <dependency>
    		<groupId>org.springframework</groupId>
    		<artifactId>spring-context</artifactId>
    	</dependency>
    	<dependency>
    		<groupId>org.springframework</groupId>
    		<artifactId>spring-beans</artifactId>
    	</dependency>
    	<dependency>
    		<groupId>org.springframework</groupId>
    		<artifactId>spring-webmvc</artifactId>
    	</dependency>
    	<dependency>
    		<groupId>org.springframework</groupId>
    		<artifactId>spring-jdbc</artifactId>
    	</dependency>
    	<dependency>
    		<groupId>org.springframework</groupId>
    		<artifactId>spring-aspects</artifactId>
    	</dependency>
    	
    	<dependency>
    		<groupId>org.springframework</groupId>
    		<artifactId>spring-context-support</artifactId>
    	</dependency>
    	<dependency>
    		<groupId>org.springframework</groupId>
    		<artifactId>spring-test</artifactId>
    	</dependency>
    		
    	<dependency>
    		<groupId>junit</groupId>
    		<artifactId>junit</artifactId>
    	</dependency>
    	<dependency>
    		<groupId>com.alibaba</groupId>
    		<artifactId>fastjson</artifactId>
    		<version>1.2.28</version>
    	</dependency>
    	<dependency>
    		<groupId>javassist</groupId>
    		<artifactId>javassist</artifactId>
    		<version>3.11.0.GA</version>
    	</dependency>
    	<dependency>
    	    <groupId>commons-codec</groupId>
    	    <artifactId>commons-codec</artifactId>
    	    <version>1.10</version>
    	</dependency>
    	<dependency>
    		<groupId>javax.servlet</groupId>
    		<artifactId>servlet-api</artifactId>
    		<version>2.5</version>		
    		<scope>provided</scope>
    	</dependency>
    
    	<dependency>
    		<groupId>com.demo</groupId>
    		<artifactId>demo-service</artifactId>
    		<version>0.0.1-SNAPSHOT</version>
    	</dependency>
      </dependencies>
      
      <build>  
    	  <plugins>
    	      <plugin>
    				<groupId>org.apache.tomcat.maven</groupId>
    				<artifactId>tomcat7-maven-plugin</artifactId>
    				<version>2.2</version>
    				<configuration>
    					<!-- 指定端口 -->
    					<port>8080</port>
    					<!-- 请求路径 -->
    					<path>/</path>
    				</configuration>
    	  	  </plugin>
    	  </plugins>  
        </build>
    </project>
    

    pom.xml中最后配置一个tomcat插件,后续运行这个插件即可,就相当于将web程序运行在tomcat中了。

    • 在src/main/java下创建一个com.demo.controller的包,然后创建UserController类。

    UserController

    package com.demo.controller;
    
    import java.util.Date;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.demo.pojo.User;
    import com.demo.service.UserService;
    
    /** 用户注册,登录控制类
     * @author 依风
     *
     */
    //Controller+ReponseBody = RestController
    @RestController
    public class UserController {
    	@Autowired
    	private UserService userServcie;
    	
    	@RequestMapping("/insertUser")
    	public String insertUser() {
    		userServcie.insert(new User("controller","321",new Date(),"0"));
    		return "insert success";
    	}
    }
    
    

    然后我们在src/main/resources下创建两个文件夹,srping和config

    config下的application.properties是一个空文件夹,有就可以暂时不需要,只是先将基本的架子搭好。

    spring文件夹下的applicationContext-dao.xml和applicationContext.xml和demo-servcie中的一样,直接复制即可。

    我们看下applicationContext-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:dubbo="http://code.alibabatech.com/schema/dubbo" 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.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
       
        <!-- 扫描包下注解 -->
        <context:component-scan base-package="com.demo.*"></context:component-scan>
        <!-- 加载配置文件-->
        <context:property-placeholder location="classpath:config/application.properties" />
    	
        <!--fastjson-->
    	<mvc:annotation-driven>
    	  <mvc:message-converters register-defaults="true">
    	    <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">  
    	      <property name="supportedMediaTypes" value="application/json"/>
    	      <property name="features">
    	        <array>
    	          <value>WriteMapNullValue</value>
    	          <value>WriteDateUseDateFormat</value>
    	        </array>
    	      </property>
    	    </bean>
    	  </mvc:message-converters>
    	</mvc:annotation-driven>
    </beans>
    

    这里面主要配置了fastjson,它将controller类返回的数据转换为json字符串。

    我们来看下demo-web中WEB-INF目录下的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_2_5.xsd" version="2.5">
      <welcome-file-list>
        <welcome-file></welcome-file>
      </welcome-file-list>
      
      <!-- 过滤器统一编码 -->
      <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>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <!-- 加载src/main/resources下srping文件夹中所有application开头的xml文件 -->
          <param-value>classpath:spring/application*.xml</param-value>
        </init-param>
      </servlet>
      <!-- 拦截所有.do结尾的请求 -->
      <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
      </servlet-mapping>
    </web-app>
    

    当tomcat启动时会加载web.xml,而在web.xml中配置了Spring MVC拦截请求进行处理交由前端控制器(DispatcherServlet)处理,同时会加载指定的配置文件。

    鼠标右击demo-web,Run as -> Maven build。

    然后弹出如下页面,并在Goals栏输入tomcat7:run

    这样就调用了demo-web下pom.xml中配置的tomca插件,此时demo-web就运行在tomcat中了。

    然后我们来测试下,在地址栏输入http://localhost:8080/insertUser.do

  • 相关阅读:
    sql语句清除mssql日志
    常用的一些webshell木马官方后门
    32个触发事件XSS语句的总结
    XSS的高级利用部分总结 -蠕虫
    IIS7 Appcmd.exe 使用
    PHP Execute Command Bypass Disable_functions
    仿5173游戏交易平台系统SQL注入(可直接脱裤)+Getshell
    win95+ie3-win10+ie11 浏览器执行漏洞
    SQL 、NoSQL数据库教程
    Pytorch快速入门及在线体验
  • 原文地址:https://www.cnblogs.com/huang-changfan/p/11517302.html
Copyright © 2011-2022 走看看