Spring MVC+Spring+Mybatis+MySQL(IDEA)入门框架搭建
Spring Mybatis demo
0.项目准备
使用Intelli IDEA最终版(个人使用社区版时无法添加本地Tomcat)新建一个Maven项目:File -> new -> project... ->在左侧栏选中Maven -> 设置SDK(即jdk版本)-> 选中“Create from archetype” -> 选中“org.apache.maven.archetypes:maven-archetype-webapp” -> next -> 填写GroupId(类似包名)和ArtifactId(一般是项目名)-> 一路next,最后finish得到新建项目。
1)在新项目基础上再手动添加一些目录结构,最后项目结构应类似:
src-
|main-
|java- (右键“Mark Directory as”设置为源码根目录)
|com-
|jay-
|controller(控制层)
|dao(数据访问层)
|entities(数据实体POJO)
|service(服务层)
|resources-(右键“Mark Directory as”设置为资源根目录)
|mybatis-
|mapping-
|接口映射文件
|mybatis.xml
|mysql.properties
|spring-
|spring-mybatis.xml
|spring-mvc.xml
|log4j.properties
|test-(右键“Mark Directory As”设置为测试根目录)
|UserDaoTest.java
|webapp-
|WEB-INF-
|views-
|errorpage-
|404.jsp等
|page1.jsp
|web.xml
|index.jsp
|pom.xml
2)修改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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jay.spring</groupId>
<artifactId>springmvc</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>springmvc Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<!-- spring版本号 -->
<spring.version>4.0.5.RELEASE</spring.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<!-- junit版本号 -->
<junit.version>4.10</junit.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.1</mybatis.version>
</properties>
<dependencies>
<!-- 添加Spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-context</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-aop</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-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-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!--单元测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</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 -->
<!--spring单元测试依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</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.0</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<!-- javaee-api包 注意和项目使用的JDK版本对应 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<!--<!–j2ee相关包–>-->
<!--<dependency>-->
<!--<groupId>javax.servlet</groupId>-->
<!--<artifactId>javax.servlet-api</artifactId>-->
<!--<version>3.1.0</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>javax.servlet.jsp</groupId>-->
<!--<artifactId>jsp-api</artifactId>-->
<!--<version>2.2</version>-->
<!--</dependency>-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>springmvc</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
1.数据持久层Mybatis+MySQL
1.1 MySQL数据准备
安装好mysql,登录后新建数据库,然后建立user表,这里建立了一个很简单的表。
mysql> desc user;
+---------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| name | varchar(255) | NO | | | |
| address | varchar(255) | NO | | GX | |
+---------+--------------+------+-----+---------+-------+
然后随便插入几条测试数据:
mysql> select * from user;
+----+------+---------+
| id | name | address |
+----+------+---------+
| 1 | bing | BoBai |
| 2 | Jay | BoBai |
| 3 | baba | YuLin |
+----+------+---------+
3 rows in set (0.01 sec)
到这里,mysql里面的数据准备好了,接下来要通过Mybatis来获取。
1.2 Mybatis配置和使用
配置文件在mybatis目录下新建。
1.2.1 新建实体类和访问接口
1)根据数据库的user表,在entities目录下新建一个与之一一对应的Java类User.java:
package com.jay.entities;
public class User {
private Integer id;
private String name;
private String address;
public User(){}
public User(Integer id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
2)建立访问底层数据的接口UserDao,这里为了方便,只定义了一个方法。
package com.jay.dao;
import com.jay.entities.User;
import java.util.List;
public interface UserDao {
List<User> getAllUsers();
}
1.2.2 配置MySQL连接信息
在mybatis目录下新建mysql.properties文件:
mybatis/mysql.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名
username=root
password=root
1.2.3 配置Mybatis信息
1)配置与UserDao对应的Mapper.xml文件
新建文件mybatis/mapping/UserDaoMapper.xml
mybatis/mapping/UserDaoMapper.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.jay.dao.UserDao">
<!--id是接口中的方法名,结果类型如没有在mybatis.xml文件中配置别名,则必须使用全名称(包名+类名) -->
<select id="getAllUsers" resultType="User">
select id,`name`,address from user
</select>
</mapper>
2)配置Mybatis与mysql的连接文件
mybatis/mybatis.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">
<!--没有集成spring时可以用,集成spring后这个文件主要内容都做spring配置文件中完成-->
<configuration>
<!-- 指定数据库连接信息的位置 -->
<properties resource="mybatis/mysql.properties"></properties>
<!--设置类别名,默认引入该包下的所有类,这样在写Mapper文件的时候就可以只写entity的类名,而不用写全名那么麻烦 -->
<typeAliases>
<package name="com.jay.entities"/>
</typeAliases>
<!--配置mysql的链接信息,数据从配置文件里面读取,注意名称要对应-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<!--引入映射文件 -->
<mappers>
<mapper resource="mybatis/mapping/UserDaoMapper.xml" />
</mappers>
</configuration>
3)配置log4j
新建文件resources/log4j.properties
log4j.rootLogger=INFO,Console,Stdout
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.appender.Stdout = org.apache.log4j.DailyRollingFileAppender
log4j.appender.Stdout.File = E://logs/log.log
log4j.appender.Stdout.Append = true
log4j.appender.Stdout.Threshold = DEBUG
log4j.appender.Stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.Stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
1.2.4 测试Mybatis访问Mysql的数据
1)在test目录下新建测试类UserDaoTest.java
import com.jay.dao.UserDao;
import com.jay.entities.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.InputStream;
import java.util.List;
public class UserDaoTest {
private static Logger logger = Logger.getLogger(UserDaoTest.class);
public static void main(String[] args) {
testMybatis();
}
private static void testMybatis(){
System.out.println("hi");
// 获得Mybatis配置文件流
InputStream config = UserDaoTest.class.getClassLoader().getResourceAsStream("mybatis/mybatis.xml");
// 创建sql会话工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);
//获得会话对象
SqlSession session = factory.openSession(true);
try {
//通过MyBatis实现接口UserDAO,返回实例
UserDao userDao = session.getMapper(UserDao.class);
List<User> users = userDao.getAllUsers();
logger.info(users);
users.forEach(user-> logger.info(user.getId()+","+user.getName()+","+user.getAddress()));
} finally {
session.close();
}
}
}
2)运行结果
hi
[User{id=1, name='bing', address='BoBai'}, User{id=2, name='Jay', address='BoBai'}, User{id=3, name='baba', address='YuLin'}]
1,bing,BoBai
2,Jay,BoBai
3,baba,YuLin
Process finished with exit code 0
控制台打印出来的内容和mysql数据里面的信息一致,说明Mybatis已经可以正确获取Mysql里的数据了,接下来在项目目前完成的基础上集成Spring。
2.Spring+Mybatis
2.1 Spring配置
从上面的例子可以看到,如果要访问数据,那么我们就必须先要读取mybatis.xml配置文件,然后生成SqlSessionFactory对象,再获取对应的session才可以访问数据。现在要把这些工作都交给Spring来完成(配置即可),就不用手动读取配置新建对象那么麻烦了。而且原来配置在mybatis.xml文件中的信息,都可以全部移到spring配置文件中来,原来的mybatis.xml文件存在价值不大了。
在spring目录下新建spring-mybatis.xml文件:
spring/spring-mybatis.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 引入mysql jdbc配置文件 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:mybatis/mysql.properties</value>
<!--要是有多个配置文件,只需在这里继续添加即可 -->
</list>
</property>
</bean>
<!-- 配置mysql数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 使用properties来配置 -->
<property name="driverClassName">
<value>${driver}</value>
</property>
<property name="url">
<value>${url}</value>
</property>
<property name="username">
<value>${username}</value>
</property>
<property name="password">
<value>${password}</value>
</property>
</bean>
<!-- 自动扫描了所有的XxxxMapper.xml对应的mapper接口文件,这样就不用一个一个手动配置Mpper的映射了,只要Mapper接口类和Mapper映射文件对应起来就可以了。 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.jay.dao.*" />
</bean>
<!-- 配置Mybatis的文件 ,mapperLocations配置**Mapper.xml文件位置,configLocation配置mybatis-config文件位置-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:mybatis/mapping/*.xml"/>
<property name="configLocation" value="classpath:mybatis/mybatis.xml" />
</bean>
<!-- 自动扫描注解的bean -->
<context:component-scan base-package="com.jay.*" />
<!-- 用eclipse的同学说不用配置该项(未验证),我也认为Mapper文件已经和接口对应起来了也不用配置的,但是IDEA一直报错无法注入UserDao,增加该配置后就ok了。每一个Mapper都需要注入sqlSessionFactory和指定映射接口 -->
<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
<property name="mapperInterface" value="com.jay.dao.UserDao"></property>
</bean>
</beans>
这个时候的mybatis.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">
<!--没有集成spring时可以用,集成spring后这个文件主要内容都做spring配置文件中完成-->
<configuration>
<!--<!– 指定数据库连接信息的位置 –>-->
<!--<properties resource="mybatis/mysql.properties"></properties>-->
<!--设置类别名,默认引入该包下的所有类,这样在写Mapper文件的时候就可以只写entity的类名,而不用写全名那么麻烦 -->
<typeAliases>
<package name="com.jay.entities"/>
</typeAliases>
<!--<!–配置mysql的链接信息,基本数据从配置文件里面读取–>-->
<!--<environments default="development">-->
<!--<environment id="development">-->
<!--<transactionManager type="JDBC" />-->
<!--<dataSource type="POOLED">-->
<!--<property name="driver" value="${driver}" />-->
<!--<property name="url" value="${url}" />-->
<!--<property name="username" value="${username}" />-->
<!--<property name="password" value="${password}" />-->
<!--</dataSource>-->
<!--</environment>-->
<!--</environments>-->
<!--<!–引入映射文件 –>-->
<!--<mappers>-->
<!--<mapper resource="mybatis/mapping/UserDaoMapper.xml" />-->
<!--</mappers>-->
</configuration>
2.2 测试
在UserDaoTest.java类里添加测试方法testSpringMybatis()
import com.jay.dao.UserDao;
import com.jay.entities.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.InputStream;
import java.util.List;
public class UserDaoTest {
private static Logger logger = Logger.getLogger(UserDaoTest.class);
public static void main(String[] args) {
// testMybatis();
testSpringMybatis();
}
private static void testSpringMybatis(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring/spring-mybatis.xml");
SqlSessionFactory factory = (SqlSessionFactory) context.getBean("sqlSessionFactory");
//获得会话对象
SqlSession session = factory.openSession(true);
try {
//通过MyBatis实现接口UserDAO,返回实例
UserDao userDao = session.getMapper(UserDao.class);
List<User> users = userDao.getAllUsers();
System.out.println(users);
users.forEach(user-> logger.info(user.getId()+","+user.getName()+","+user.getAddress()));
} finally {
session.close();
}
}
private static void testMybatis(){
System.out.println("hi");
// 获得环境配置文件流
InputStream config = UserDaoTest.class.getClassLoader().getResourceAsStream("mybatis/mybatis.xml");
// 创建sql会话工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);
//获得会话对象
SqlSession session = factory.openSession(true);
try {
//通过MyBatis实现接口UserDAO,返回实例
UserDao userDao = session.getMapper(UserDao.class);
List<User> users = userDao.getAllUsers();
logger.info(users);
users.forEach(user-> logger.info(user.getId()+","+user.getName()+","+user.getAddress()));
} finally {
session.close();
}
}
}
2.3 运行结果
[User{id=1, name='bing', address='BoBai'}, User{id=2, name='Jay', address='BoBai'}, User{id=3, name='baba', address='YuLin'}]
2017-09-02 12:02:55,259 [main] INFO [UserDaoTest] - 1,bing,BoBai
2017-09-02 12:02:55,259 [main] INFO [UserDaoTest] - 2,Jay,BoBai
2017-09-02 12:02:55,259 [main] INFO [UserDaoTest] - 3,baba,YuLin
Process finished with exit code 0
集成Spring后,可以通过Spring配置正常获取mysql的数据,说明到这都是畅通的。接下来加入Spring MVC模块。
3.加入Spring MVC处理请求
3.1 配置spring-mvc.xml文件
在spring目录下新建spring-mvc.xml文件
spring/spring-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: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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--启用spring的注解annotation -->
<context:annotation-config/>
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.jay.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置注解驱动 可以将request参数与绑定到controller参数上 -->
<mvc:annotation-driven/>
<!-- 添加视图解析器前后缀,这里默认使用.jsp文件-->
<bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/><!--设置JSP文件的目录位置-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
3.2 web.xml配置
web.xml不仅要处理转发请求,还要加载Spring文件和Spring MVC的配置文件,添加上下文监听器、编码过滤等。非常重要的一个文件。
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_3_0.xsd"
version="3.0">
<!--welcome pages-->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 读取spring配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-mybatis.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-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>
<!-- 日志记录 -->
<context-param>
<!-- 日志配置文件路径 -->
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<!--spring上下文监听器,如果没有-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置springmvc DispatcherServlet,转发前端或后台发来的请求-->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!--resources目录下需要新建一个spring文件夹-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/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>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 错误跳转页面 -->
<error-page>
<!-- 404客户端路径不正确 -->
<error-code>404</error-code>
<location>/WEB-INF/views/errorpage/404.jsp</location>
</error-page>
<error-page>
<!-- 客户端没有访问权限,访问被禁止 -->
<error-code>405</error-code>
<location>/WEB-INF/views/errorpage/405.jsp</location>
</error-page>
<error-page>
<!-- 服务器内部错误 -->
<error-code>500</error-code>
<location>/WEB-INF/views/errorpage/500.jsp</location>
</error-page>
</web-app>
3.3 MVC(视图层、控制层、模块服务层)
3.3.1 视图层文件
1)修改webapp目录下的index.jsp
项目启动页面,可以在以后的开发中设置为登录验证页面。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
<h1>登录,首页</h1>
</body>
</html>
2)在WEB-INF/views/目录下添加文件
page1.jsp展示从数据库获取的user数据信息
WEB-INF/views/page1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
<h1>Hello world!</h1>
${user.id}
${user.name}
</body>
</html>
errorpage目录下的是错误跳转页面
WEB-INF/views/errorpage/404.jsp
<%@page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<html>
<body>
<h2>404 err</h2>
</body>
</html>
-----------------------------------------
WEB-INF/views/errorpage/405.jsp
<%@page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<html>
<body>
<h2>405 err</h2>
</body>
</html>
-----------------------------------------
WEB-INF/views/errorpage/500.jsp
<%@page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<html>
<body>
<h2>500 err</h2>
</body>
</html>
-----------------------------------------
3.3.2 控制层
在com.jay.controller包下新建UserController.java。主要有两个方法,getUser()返回user对象信息给page1.jsp处理,然后在前端页面展示数据库的数据信息。方法sayHi验证前后数据传输是否正常。
package com.jay.controller;
import com.jay.entities.User;
import com.jay.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Controller
public class UserController {
private static final Logger logger = Logger.getLogger(UserController.class);
@Resource
private UserService service;
/**
*返回user对象信息给page1.jsp处理,然后在前端页面展示
*/
@RequestMapping("/page1")
public ModelAndView getUser() {
System.out.println("访问page1的后台。。。");
ModelAndView mav = new ModelAndView("page1");
List<User> users = service.getAllUser();
System.out.println(users);
mav.addObject("user", users.get(0));
return mav;
// return "page1"; //跳转到.jsp结尾的对应文件(page1.jsp),此时返回值是String
}
/**
* 直接返回字符串给请求的页面(这里在请求URL增加参数v是验证前后台通信是否正常)
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/say", produces = "text/html;charset=UTF-8")
@ResponseBody
public String sayHi(HttpServletRequest request, HttpServletResponse response) {
String name = request.getParameter("v");
List<User> users = service.getAllUser();
logger.info("{name:jay,context:hi,你好}");
return name+"-{name:jay,context:hi,你好}"+users;
}
}
3.3.3 服务层
在com.jay.service下新建接口和实现类。
访问接口,没有任何注解。
package com.jay.service;
import com.jay.entities.User;
import java.util.List;
public interface UserService {
List<User> getAllUser();
}
接口实现类,注解@Service并制定名称,同时@Scope("prototype")设定每次访问都创建一个新对象,通过@Resource自动注入userDao。通过userDao就可以寻找映射的mybatis文件,从而正常获取数据库的信息。
package com.jay.service.impl;
import com.jay.dao.UserDao;
import com.jay.entities.User;
import com.jay.service.UserService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service("userServiceImpl")
@Scope("prototype")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
@Override
public List<User> getAllUser() {
return userDao.getAllUsers();
}
}
4.测试
给IDEA添加本地Tomcat服务器,然后将本项目发布到Tomcat并启动。
启动后访问项目:
1.访问:http://localhost:8080/springmvc/
页面显示:
登录,首页
2.访问:http://localhost:8080/springmvc/page1
页面显示:
Hello world!
1 bing (数据库获取的信息,这里只提取一条来说明)
3.访问:http://localhost:8080/springmvc/say?v=cainiao
页面显示:
cainiao-{name:jay,context:hi,你好}[User{id=1, name='bing', address='BoBai'}, User{id=2, name='Jay', address='BoBai'}, User{id=3, name='baba', address='YuLin'}]
至此,可以直接从前端URL请求,通过SpringMVC、Spring、Mybatis正常访问MySQL的数据,流程走通。
5.总结
本例子只是一个最简单的demo,只是用来说明框架搭建的过程。
每个环节都有十分丰富的内容需要学习和补充,比如Mybatis部分CURD、动态SQL、事务处理等,Spring部分有日志、事务、权限等AOP切面、并发处理、IO性能等,前端也有Struts等各种框架。
源码地址:
git@github.com:FEFJay/spring_demo.git
参考链接:
http://blog.csdn.net/Evankaka/article/details/48785513
http://wiki.jikexueyuan.com/project/spring/mvc-framework/spring-mvc-hello-world-example.html
其他未列出的链接