工作到現(xiàn)在快要1年半了,一直沒有時間自己從頭搭建個框架,這個周末實在是無聊,真的不想打lol了,(黑色玫瑰開黑的喊我!),正好把之前埋下的坑填完.
你需要以下工具:
IDE : Intellij idea15
jdk : 1.7.0_59
maven : 3.2.2
tomcat : 7.0.54
-
new an empty project,相當于eclipse中的workspace
-
new a maven module,相當于eclipse中的project,選擇maven后一路next,設置自己的名稱即可.
-
在idea中配置maven,在preferences中將maven_home指向本地的安裝路徑即可.至于怎么配置maven_home環(huán)境,左轉百度,右轉google
-
下面放上一張搭建好的工程結構圖
- 以下是所有使用的到的jar包依賴. (pom.xml)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sam</groupId>
<artifactId>spring-mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.1.6.RELEASE</spring.version>
<cxf.version>2.7.15</cxf.version>
<aspectj.version>1.6.8</aspectj.version>
<slf4j-version>1.7.12</slf4j-version>
<thymeleaf.version>2.1.3.RELEASE</thymeleaf.version>
<thymeleaf-layout.version>1.2.5</thymeleaf-layout.version>
<log4j-version>1.2.17</log4j-version>
<mybatis-version>3.3.0</mybatis-version>
<mybatis-spring-version>1.2.3</mybatis-spring-version>
<jackson.version>2.4.3</jackson.version>
<json.version>1.9.13</json.version>
<diamond.version>0.0.18</diamond.version> </properties>
<dependencies>
<!-- 日志配置-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.13</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.1</version>
</dependency>
<!-- 數(shù)據(jù)源配置 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring-version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis-version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<!-- spring用到的包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</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-jdbc</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-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!--測試-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.1.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!-- thymeleaf -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>${thymeleaf.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
<version>${thymeleaf-layout.version}</version>
</dependency>
<!--diamond-->
<dependency>
<groupId>com.github.bingoohuang</groupId>
<artifactId>diamond-sdk</artifactId>
<version>0.0.5</version>
</dependency>
<dependency>
<groupId>com.github.bingoohuang</groupId>
<artifactId>diamond-client</artifactId>
<version>${diamond.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<!--jackson-->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${json.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>${json.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
- 定義一個WebMvcConfig類實現(xiàn)WebMvcConfigurerAdapter
/**
* 繼承web mvc adapter
* 包含通用的配置
* Created by sam on 16/5/26.
*/
public class WebMvcConfig extends WebMvcConfigurerAdapter {
//static resources
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/img/**").addResourceLocations("/img/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
// 配置thymeleaf視圖解析器,
// 保留原有配置
// 加入自定義參數(shù) 如${e.res()}
@Bean
public ThymeleafViewResolver thymeleafViewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setCharacterEncoding("UTF-8");
Map<String, Object> oldStaticVariables = viewResolver.getStaticVariables();
Map<String, Object> staticVariables = Maps.newHashMap(oldStaticVariables);
staticVariables.put("e", new SpringUtils());
viewResolver.setStaticVariables(staticVariables);
return viewResolver;
}
//配置模板引擎
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver());
engine.addDialect(new LayoutDialect());
return engine;
}
//配置模板解析器
@Bean
public TemplateResolver templateResolver() {
ClassLoaderTemplateResolver templateResolver;
templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setTemplateMode("XHTML");
templateResolver.setPrefix("views/");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setSuffix(".html");
templateResolver.setCacheable(false); // true by default
return templateResolver;
}
//定義spring文件上傳編碼
@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setDefaultEncoding("UTF-8");
return multipartResolver;
}
//解析json返回數(shù)據(jù)
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
List<MediaType> mediaTypes = new ArrayList(converter.getSupportedMediaTypes());
converter.setSupportedMediaTypes(mediaTypes);
mediaTypes.addAll(asList(MediaType.TEXT_PLAIN, MediaType.TEXT_HTML, MediaType.TEXT_XML));
converters.add(converter);
}
//配置diamond,如果本地沒有配置diamond可以注釋該段代碼
@Bean
public DiamondSDK diamondSDK() {
Minerable minerable = new Miner().getMiner("poet.diamond", "diamondConfig");
DiamondSDK diamondSDK = new DiamondSDK(
new DiamondSDKConf(
Lists.newArrayList(new DiamondConf(
minerable.getString("diamondIp"),
minerable.getInt("diamondPort"),
minerable.getString("diamondUsername"),
minerable.getString("diamondPassword")))));
return diamondSDK;
}
//快捷定義ViewController
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
}
- 定義實際使用到的spring mvc config
/**
* 實際使用到的配置文件
* 可以將該文件放入不同的工程來辨別使用不同的spring配置,如不同的interceptor
* Created by sam on 16/5/26.
*/
@EnableWebMvc
@Configuration
@EnableAspectJAutoProxy
public class SpringMvcConfig extends WebMvcConfig {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SpringInterceptor());
}
}
- 以下是上面配置中使用到的interceptor
/**
* Created by sam on 16/5/26.
*/
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Component
public class SpringInterceptor extends HandlerInterceptorAdapter {
private Logger logger = LoggerFactory.getLogger(SpringInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.debug("interceptor works --------- return true");
return true;
}
}
- 注冊DispatcherServlet
/**
* 注冊Spring DispatcherServlet
* Created by sam on 16/5/26.
*/
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
//配置掃描根路徑
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RootConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
return new Filter[]{characterEncodingFilter};
}
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
}
}
- 配置上面配置中的RootConfig,包括配置包的掃描路徑,配置mybatis需要的數(shù)據(jù)源等
/**
* 定義掃描的根路徑,數(shù)據(jù)源
* Created by sam on 16/5/26.
*/
@Configuration
@ComponentScan(basePackages = "com.sam")
@MapperScan(basePackages = "com.sam")
public class RootConfig {
private static String diver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/YOUR_INSTANCE_NAME";
private static String user = "YOUR_NAME";
private static String pwd = "YOUR_PASSWORD";
@Bean
public BasicDataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(diver);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(pwd);
return dataSource;
}
@Bean
public DataSourceTransactionManager dataSourceTransactionManager() throws NamingException {
return new DataSourceTransactionManager(dataSource());
}
@Bean
public SqlSessionFactoryBean sqlSessionFactory(ApplicationContext ap) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setTypeAliasesPackage("com.sam");
return sessionFactory;
}
}
- 定義SpringUtils類實現(xiàn)thymeleaf中使用到的自定義參數(shù),這個配置寫在WebMvcConfig中
/**
* 配置thymeleaf自定義參數(shù)的相關方法
* Created by sam on 16/5/26.
*/
public class SpringUtils {
// 可以在html中使用${e.res('/')}
// 將會自動代理到相關靜態(tài)資源下面
public static String res(String relativeResPath) {
Minerable resConfig = new Miner().getMiner("poet.base", "res");
String resVersion = resConfig.getString("version", "1");
String baseResPath = resConfig.getString("prefix");
if (baseResPath == null) throw new RuntimeException("prefix config is NULL.");
return new StringBuilder(removeEnd(baseResPath, "/")).append("/").append(removeStart(relativeResPath, "/")).append("?v=").append(resVersion).toString();
}
}
- 定義helloWorldController來測試下
/**
* Created by sam on 16/5/26.
*/
@Controller
@RequestMapping("/hello")
public class HelloWorldController {
@Autowired
UserDao userDao;
private Logger logger = LoggerFactory.getLogger(HelloWorldController.class);
@RequestMapping("/world")
public String hello(Model model) {
String email = "sam@balabala.com";
String name = userDao.queryUserNameByEmail(email);
User user = userDao.queryUserInfoByEmail(email);
logger.debug("you have been here !");
model.addAttribute("hello", "您好! " + name);
model.addAttribute("world", "everything is " + user.getUserId());
return "sam";
}
@RequestMapping("/test")
public String test(Model model){
logger.debug(">>>>>>>>我就測試下日志 debug <<<<<<<<<");
logger.info(">>>>>>>> 我就測試下日志 info <<<<<<<<<");
model.addAttribute("hello", "您好! test");
model.addAttribute("world", "everything is id");
return "sam";
}
}
- 在resources下建views夾子,sam.html如下
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>my first html</title>
</head>
<body>
<h1 data-th-text="${hello}"></h1>
<h1 data-th-text="${world}"></h1>
</body>
</html>
- UserDao
/**
* Created by sam on 16/5/29.
*/
@Service
public interface UserDao {
@Select("select customer_name from customer where email= #{email}")
String queryUserNameByEmail(@Param("email") String email);
User queryUserInfoByEmail(@Param("email") String email);
}
- User
/**
* Created by sam on 16/5/29.
*/
public class User {
private String userId;
private String userName;
private String email;
//get set toString and so on;
}
- 在你的MySQL中建一個Customer表(customer_id,customer_name,email)即可
- 在resources下建立與dao相同包名的xml文件,在你的MySQL中建一個Customer表,包含customer_id,customer_name,email即可,
<?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.sam.dao.UserDao">
<resultMap id="User" type="com.sam.domain.User">
<id column="customer_id" property="userId" jdbcType="VARCHAR"/>
<result column="customer_name" property="userName" jdbcType="VARCHAR"/>
<result column="email" property="email" jdbcType="VARCHAR"/>
</resultMap>
<select id="queryUserInfoByEmail" resultMap="User" parameterType="java.lang.String">
select customer_id,customer_name,email
from customer
where email= #{email,jdbcType=VARCHAR}
</select>
</mapper>
- Finally ,訪問 http://localhost:8080/YOUR_MODULE_NAME/hello/world 來試一下吧
- 文章的結尾 : 感謝下濤bra,嘟嘟MD兩位童鞋~~~