1 使用idea编辑工具,maven项目构建工具搭建RESTful风格的java项目
2 进行项目配置
2.1 pom文件依赖
<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.</modelVersion>
<groupId>com.huitong</groupId>
<artifactId>friend</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>friend Maven Webapp</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-</project.reporting.outputEncoding>
<!-- spring版本号 -->
<spring.version>4.3..RELEASE</spring.version> <!-- mybatis版本号 -->
<mybatis.version>3.4.</mybatis.version> <!-- mysql驱动版本号 -->
<mysql-driver.version>5.1.</mysql-driver.version> <!-- log4j日志包版本号 -->
<log4j.version>2.7</log4j.version>
<commons-logging.version>1.2</commons-logging.version> <!-- 对象转 jackson 版本号 -->
<jackson.version>2.8.</jackson.version> <!--spring security version-->
<spring.security.version>4.2..RELEASE</spring.security.version> <mysql.user>root</mysql.user>
<mysql.password></mysql.password> </properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency> <!-- 添加jstl依赖 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency> <!-- javaee 7.0 -->
<!-- https://mvnrepository.com/artifact/javax/javaee-api -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency> <!-- ######## spring mvc 依赖包 start ################################-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- ######## spring mvc 依赖包 end ################################--> <!-- ######## spring core 依赖包 start ################################-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- ######## spring core 依赖包 end ################################--> <!-- ######## mybatis core 依赖包 start ################################-->
<!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>5.2</version>
</dependency> <!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- ######## mybatis core 依赖包 end ################################--> <!-- ######## mybatis spring 依赖包 start ################################-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.</version>
</dependency>
<!-- ######## mybatis spring 依赖包 end ################################--> <!-- ######## DBconnector 依赖包 start ################################-->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-driver.version}</version>
</dependency> <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- ######## DBconnector 依赖包 end ################################--> <!-- ######## translation 依赖包 start ################################-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- ######## translation 依赖包 end ################################--> <!-- ######## AOP 依赖包 start ################################-->
<!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- ######## AOP 依赖包 end ################################--> <!-- ######## json 依赖包 start ################################-->
<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>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- ######## json 依赖包 end ################################--> <dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.</version>
</dependency> <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>${commons-logging.version}</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency> <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2..RELEASE</version>
</dependency> </dependencies> <build>
<finalName>friend</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.xml</include>
</includes>
</resource> <resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.properties</include>
</includes>
</resource> <resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*.properties</exclude>
</excludes>
</resource> <resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource> </resources>
</build>
</project>
2.2 数据库配置 spring-db.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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!--数据源配置-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///day11?useSSL=true" />
<property name="user" value="${mysql.user}" />
<property name="password" value="${mysql.password}" />
<property name="acquireIncrement" value="" />
<property name="maxPoolSize" value="" />
<property name="maxIdleTime" value="" />
</bean> <!--SqlSessionFactoryBean 配置-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean> <!-- SqlSessionTemplate 配置 -->
<bean id="sessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="" ref="sqlSessionFactory"/>
</bean> <!-- MapperScannerConfigurer 配置 -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.huitong"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean> <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"/> </beans>
2.3 springMVC配置文件,springMVC.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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <!-- 注解驱动 -->
<mvc:annotation-driven >
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean> </mvc:message-converters>
</mvc:annotation-driven>
<!-- 扫描包 -->
<context:component-scan base-package="com.huitong" />
<!-- 对静态资源文件的访问 不支持访问WEB-INF目录 -->
<mvc:default-servlet-handler /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
</bean> </beans>
2.4 mybatis配置文件
<?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>
<!--任意环境,数据源和 MyBatis 的事务管理器都会被 忽略 。-->
<!--通常这会是 <settings> 或 <typeAliases> 的部分。--> <settings>
<!-- Globally enables or disables any caches configured in any mapper under this configuration -->
<setting name="cacheEnabled" value="false"/>
<!--<setting name="logImpl" value="STDOUT_LOGGING" />-->
</settings>
</configuration>
2.5 spring的配置,将所有配置进行整合
<?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>
<!--任意环境,数据源和 MyBatis 的事务管理器都会被 忽略 。-->
<!--通常这会是 <settings> 或 <typeAliases> 的部分。--> <settings>
<!-- Globally enables or disables any caches configured in any mapper under this configuration -->
<setting name="cacheEnabled" value="false"/>
<!--<setting name="logImpl" value="STDOUT_LOGGING" />-->
</settings>
</configuration>
2.6 web.xml配置文件
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- 指定 spring 的配置文件,不然会报错找不到applicationContext.xml 文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param> <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-</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter> <!--解决表单put请求-->
<filter>
<filter-name>httpPutFormContentFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter> <filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<servlet-name>dispatcherServlet</servlet-name>
</filter-mapping> <filter-mapping>
<filter-name>httpPutFormContentFilter</filter-name>
<servlet-name>dispatcherServlet</servlet-name>
</filter-mapping> <!-- 方便获取ApplicationContext -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</init-param>
<load-on-startup></load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping> </web-app>
至此,所有配置文件已经配置完毕。我的项目结构如下图
3 关键类
3.1 实体类Student
public class Student { private String id;
private String name;
private Integer age;
private String gender;
private Date birthday; public Student() {
} public Student(
String id,
String name,
Integer age,
String gender,
Date birthday) {
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
this.birthday = birthday;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} public String getGender() {
return gender;
} public void setGender(String gender) {
this.gender = gender;
} public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
3.2 StudentDao接口
@Repository
public interface StudentDao {
/**
* 添加学生
* @param student 学生信息
*/
void insert(Student student); /**
* 查询学生信息
* @param id 学生ID
* @return 查询到的学生信息
*/
Student queryStudentById(@Param("id") String id); String getNameById(@Param("id") String id);
}
3.3 StudentDao.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.huitong.adaptor.persistence.mybatis.StudentDao"> <insert id="insert" parameterType="com.huitong.entity.Student">
INSERT INTO student(id, name, age, gender, birthday)
VALUES(#{id},#{name},#{age},#{gender},#{birthday})
</insert> <select id="queryStudentById" parameterType="string" resultType="com.huitong.entity.Student">
SELECT *
FROM student
WHERE id=#{id}
</select> <select id="getNameById" resultType="string">
SELECT NAME
FROM student
WHERE id=#{id}
</select> </mapper>
4 问题小结
4.1 报错找不到applicationContext.xml 配置文件
IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
解决方案:查看博文 关于“Could not open ServletContext resource [/WEB-INF/applicationContext.xml]”解决方案 4.2 报错org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):
解决方案
一般的原因是Mapper interface和xml文件的定义对应不上,需要检查包名,namespace,函数名称等能否对应上,需要比较细致的对比,
按以下步骤一一执行:
1:检查xml文件所在的package名称是否和interface对应的package名称一一对应
2:检查xml文件的namespace是否和xml文件的package名称一一对应
3:检查函数名称能否对应
但是博主在尝试以上方案之后仍然报错,在我查看了发布之后的源代码之后,发现*Mapper.xml文件并没有发布到目标文件中。我是使用maven 进行项目构建。修改pom.xmml文件,
在<build>子项中添加
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.xml</include>
</includes>
</resource> <resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.properties</include>
</includes>
</resource> <resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*.properties</exclude>
</excludes>
</resource> <resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource> </resources>
4.3 在请求中,获取string字符串中文乱码问题
解决方案,修改 springMVC.xml 配置文件,参考博客 SpringMVC源码总结(四)由StringHttpMessageConverter引出的客户端服务器端之间的乱码过程分析
<mvc:annotation-driven >
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean> </mvc:message-converters>
</mvc:annotation-driven>
4.4 处理返回类型是日期类型 Date
解决方案,修改 springMVC.xml 配置文件
<mvc:annotation-driven >
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss"/>
</bean>
</property>
</bean>
</property>
</bean> </mvc:message-converters>
</mvc:annotation-driven>