Spring MVC 环境搭建(maven+SpringMVC+mybatis+Freemarker)
一、准备工作
1.Eclipse Java EE IDE(4.4.1)
2.JDK
3.Tomcat
4.Maven maven安装指南
二、构建工程
1.file->new->Project
2.next
3. next
4.next
5.finish
工程目录如下
三、完善项目
首先,完善目录,增加重要的source Folder,这个不是简单的Floder,这些文件夹是会参与编译的。
增加src/main/java,src/test/resources,src/test/java目录。让目录变成标准的maven结构
说明:src/test/resources 通过添加source Folder 添加
src/main/java,src/test/java 通过Navigator中 new folder 添加
window->show view->Navigator
标准目录为:
四、工程属性设置
1.工程右键->Properties->Deployment Assembly
修改为
五、SpringMVC工程搭建(MyBatis+Freemarker)
1.完善工程目录结构
在src/main/java文件夹中,新建包
com.operate.command(存放传入的参数javabean),
com.operate.dto(存放数据库取出的数据的javabean),
com.operate.dao(存放spring与mybatis连接接口),
com.operate.persistence(存放中间持续的javabean),
com.operate.service(service接口),
com.operate.service.impl(service接口的实现),
com.operate.controller(存放控制层controller)
在src/main/resource文件夹中,新建包
conf(存放配置文件),
mapper(mybatis的mapper文件)
在src/test/java文件夹中,新建包
com.operate.test(存放测试文件)
在WEB-INF文件夹下新建ftl文件夹(存放freemarker文件)
这样项目结构基本完成了,如下图:
2.引入依赖包
打开maven的pom文件,对本次开发所需使用的架包依次导入(maven项目管理的优势)
查找依赖结构有个不错的网站,http://search.maven.org/ 只要输入包名即可查找引来关系
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.sheyou</groupId>
<artifactId>operate</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>operate Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<!-- spring版本号 -->
<spring.version>4.1.6.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.8</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
<scope>test</scope>
</dependency>
<!-- spring jar -->
<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-context-support</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-aop</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-jdbc</artifactId>
<version>${spring.version}</version>
</dependency> <!-- spring mvc jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency> <!-- mybatis 包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!--mybatis spring 插件 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!--sqlserver驱动包-->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>3.0</version>
</dependency>
<!-- mysql驱动包 -->
<
dependency
>
<
groupId
>mysql</
groupId
>
<
artifactId
>mysql-connector-java</
artifactId
>
<
version
>5.1.29</
version
>
</
dependency
>
<!-- 导入java ee jar 包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency> <!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency> <!-- 格式化对象,方便输出日志 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</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 --> <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1</version>
</dependency> <!-- 阿里巴巴数据源包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
</dependencies>
<build>
<finalName>operate</finalName>
</build>
</project>
3.配置数据库连接属性
conf/ jdbc.properties(jdbc配置文件)
SQLServver
url=jdbc:sqlserver://localhost:1433;DatabaseName=user
user=root
password=root
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
MySQL
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydays?useUnicode=true&characterEncoding=utf-8
user=root
password=root
conf/spring-mybatis.xml(spring与mybatis连接属性)
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
destroy-method="close" >
<property name="driverClassName">
<value>${driver}</value>
</property>
<property name="url">
<value>${url}</value>
</property>
<property name="username">
<value>${user}</value>
</property>
<property name="password">
<value>${password}</value>
</property>
<!-- 连接池最大使用连接数 -->
<property name="maxActive">
<value>20</value>
</property>
<!-- 初始化连接大小 -->
<property name="initialSize">
<value>1</value>
</property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait">
<value>60000</value>
</property>
<!-- 连接池最大空闲 -->
<property name="maxIdle">
<value>20</value>
</property>
<!-- 连接池最小空闲 -->
<property name="minIdle">
<value>3</value>
</property>
<!-- 自动清除无用连接 -->
<property name="removeAbandoned">
<value>true</value>
</property>
<!-- 清除无用连接的等待时间 -->
<property name="removeAbandonedTimeout">
<value>180</value>
</property>
<!-- 连接属性 -->
<property name="connectionProperties">
<value>clientEncoding=UTF-8</value>
</property>
</bean> <!-- mybatis文件配置,扫描所有mapper文件 -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="classpath:conf/mybatis-config.xml"
p:mapperLocations="classpath:mapper/*.xml"/><!-- configLocation为mybatis属性 mapperLocations为所有mapper--> <!-- spring与mybatis整合配置,扫描所有dao BasePackage dao包-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
p:basePackage="com.operate.dao"
p:sqlSessionFactoryBeanName="sqlSessionFactory"/> <!-- 对数据源进行事务管理 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
</beans>
4.java代码编写
com.operate.dto/User.java
package com.operate.dto; public class User {
private String name;
private String photo;
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
com.operate.dao/UserDao.java
package com.operate.dao; import com.operate.dto.User; public interface UserDao {
public User getUser();
}
com.operate.service/UserService.java
package com.operate.service; import com.operate.dto.User; public interface UserService {
public User getUser();
}
com.operate.service.impl/UserServiceImpl.java
package com.operate.service.impl; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.operate.dao.UserDao;
import com.operate.dto.User;
import com.operate.service.UserService; @Service
public class UserServiceImple implements UserService { @Autowired
private UserDao userDAO; @Override
public User getUser() {
// TODO Auto-generated method stub
return userDAO.getUser();
} }
5.mybatis配置
conf/mybatis-config.xml(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>
<typeAliases>
<typeAlias type="com.operate.dto.User" alias="UserInfo"/>
</typeAliases>
<!-- 映射map -->
<mappers>
</mappers>
</configuration>
mapper/sql-map-User.xml(mybatis的实现)
<?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.operate.dao.UserDao">
<select id="getUser" resultType="UserInfo">
SELECT
*
from Member
where name='11111111'
</select>
</mapper>
这样就基本完成了获取用户的功能!
6.junit测试功能
package com.operate.test; import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.operate.dto.User;
import com.operate.service.UserService; public class UserTest {
private UserService userService;
@Before
public void before(){
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:conf/spring.xml"
,"classpath:conf/spring-mybatis.xml"});
userService = (UserService) context.getBean("userServiceImpl");//注意userServiceImpl 首字母要小写
} @Test
public void getUser(){
User user = userService.getUser();
System.out.println(user.getName()+":"+user.getPhoto());
}
}
测试结果:
7.SpringMVC搭建
Web.XML
<?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_2_5.xsd"
version="2.5" >
<display-name>Sheyou-Operate</display-name>
<!-- 加载其他配置文件至Spring应用上下文中 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- 指定多个Spring配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:conf/spring.xml;
classpath:conf/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>*.html</url-pattern>
</filter-mapping> <!-- Spring view分发器 -->
<!-- servlet-name 决定了初始化的名字:name-servlet.xml -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/conf/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<error-page>
<error-code>400</error-code>
<location>/error/400.jsp</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/error/403.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/error/404.jsp</location>
</error-page>
<error-page>
<error-code>405</error-code>
<location>/error/405.jsp</location>
</error-page>
<error-page>
<error-code>406</error-code>
<location>/error/406.jsp</location>
</error-page>
<error-page>
<error-code>412</error-code>
<location>/error/412.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/500.jsp</location>
</error-page>
<error-page>
<error-code>501</error-code>
<location>/error/501.jsp</location>
</error-page>
<error-page>
<error-code>502</error-code>
<location>/error/502.jsp</location>
</error-page>
<error-page>
<error-code>503</error-code>
<location>/error/503.jsp</location>
</error-page>
</web-app>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <mvc:annotation-driven/> <context:component-scan base-package="com.operate.controller" /> <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean> --> <bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<!--<property name="prefix" value="/WEB-INF/view/" /> -->
<property name="suffix">
<value>.ftl</value>
</property>
<property name="contentType" value="text/html;charset=UTF-8"></property>
</bean>
<!-- freemarker的配置 -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/view/ftl/" />
<property name="defaultEncoding" value="utf-8" />
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">10</prop>
<prop key="locale">zh_CN</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="number_format">#.####</prop>
</props>
</property>
</bean> <!-- 静态资源 -->
<!-- 图片 -->
<mvc:resources mapping="/images/**" location="/images/"
cache-period="31556926" />
<!-- js -->
<mvc:resources mapping="/js/**" location="/js/"
cache-period="31556926" />
<!-- css -->
<mvc:resources mapping="/css/**" location="/css/"
cache-period="31556926" />
<!-- <mvc:resources location="/qrcode/" mapping="//**" /> -->
<!-- 文件上传解析器 id 必须为multipartResolver -->
<!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<!-- <property name="maxUploadSize" value="10485760"/> -->
</bean> <!--定义异常处理页面--> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.sql.SQLException">exception</prop>
<prop key="java.io.IOException">exception</prop>
<prop key="java.lang.IOException">exception</prop>
<prop key="Open Declaration com.google.zxing.WriterException">exception</prop>
<prop key="java.lang.NullPointerException">exception</prop>
</props>
</property>
</bean> </beans>
spring.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" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
"> <!-- 引入属性文件 -->
<context:property-placeholder location="classpath:conf/jdbc.properties" />
<!-- 自动扫描(自动注入) -->
<context:component-scan base-package="com.operate.service" /> </beans>
8.log4j日志记录
1 ### set log levels ###
2 #log4j.rootLogger = debug , stdout , D , E
3 log4j.rootLogger = debug , stdout , D
4
5 ### output to the console ###
6 log4j.appender.stdout = org.apache.log4j.ConsoleAppender
7 log4j.appender.stdout.Target = System.out
8 log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
9 #log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%n
10 log4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n
11
12 ### Output to the log file ###
13 log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
14 log4j.appender.D.File = ../../WEB-INF/logs/log.log
15 log4j.appender.D.Append = true
16 log4j.appender.D.Threshold = DEBUG
17 log4j.appender.D.layout = org.apache.log4j.PatternLayout
18 log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
19
20 ### Save exception information to separate file ###
21 log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
22 log4j.appender.D.File = ../../WEB-INF/logs/error.log
23 log4j.appender.D.Append = true
24 log4j.appender.D.Threshold = ERROR
25 log4j.appender.D.layout = org.apache.log4j.PatternLayout
26 log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
9.测试
WEB-INF/view/ftl/index.ftl(测试文件)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>欢迎你!!!${result}</h1>
</body>
</html>
com.operate/controller/IndexComtroller.java(controller层控制)
package com.operate.controller; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import com.operate.dto.User;
import com.operate.service.UserService; @Controller
public class IndexController {
@Resource(name = "userService")
private UserService userService; @RequestMapping("/index.html")
ModelAndView index(HttpServletRequest request,HttpServletResponse response)
{
User user = userService.getUser();
return new ModelAndView("index")
.addObject("result", user.getName());
}
}
userServiceImpl.class 修改
package com.operate.service.impl; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.operate.dao.UserDao;
import com.operate.dto.User;
import com.operate.service.UserService; @Service("userService")
public class UserServiceImpl implements UserService { @Autowired
private UserDao userDao; @Override
public User getUser() {
// TODO Auto-generated method stub
return userDao.getUser();
} }
部署到tomcat中
浏览器中输入http://localhost:8080/operate/index.html