使用IDEA结合MAVEN创建一个Spring Java Web项目
- 前言
如今的Java项目,如果还使用传统的把jar包复制到目录下这种原始的方式,对于依赖管理来说实在是灾难。对某个功能需要引入某种技术包,但是你不确定是否已存在,如果分类好的话还好找,若是杂在一堆不仅头大,还身心俱疲。Maven旨在解决依赖问题,让项目结构变得精简,而Spring解决了项目中Bean的管理以及各种配置文件配置的功能轻松读入等问题,对于Java项目来说确实是福音。对于一个Web项目来说,必然需要数据库的读写,JdbcTemplate是一个Spring实现的Jdbc Support。对于之前必然依赖ORM的项目来说,这个组件表现得十分的轻便以及可伸缩,不需要写Mapping就使用HashMap的可伸缩性,实在是小型团队以及敏捷公司的良伴。加之报错栈十分的简单,一个数据库过程就只会在Dao里写一个sql和加载参数,最后执行,如果出错就只有在sql和参数中排查即可,比起之前在Mybatis里各种翻配置文件的时期,简直就是天堂地狱。
好了,说了这么多优劣,今天来写写要做笔记的项目。Java Web项目 + Maven项目依赖 + Spring + Spring MVC + JdbcTemplate + dbcp2连接池。其实中间三项都是Spring里面含有的。
- 开始
下载一个IDEAIDE,这个IDE比之于Eclipse,一开始会有些不习惯,但是用了一段时间之后就觉得它的各种细节处理很受好评,特别是对Maven项目的支持。
然后新建一个Maven Java 项目,选择Web模板。虽然IDE版本不一样,但是模板之类还有新建模板的步骤都是没怎么变化的。
选择创建按照Web模板,和JDK版本。
这个group id 的官方解释是组织id,我的理解是比如一个项目的组织为taobao,jd这样子,算是项目组的最高id。artifact id官方解释是项目唯一标识,算是在组织之下的唯一项目标志,创建项目之后会发现项目名称是这个artifact id。
之后的一步是选择maven版本,maven仓库之类的,自行斟酌。
在我的环境里,创建完项目之后,结构并不是我想象的那样,查了资料,加上等待maven加载之后,项目的结构变成了我熟悉的那种结构,就是少了java文件夹。创建项目之后,maven会一直下载jar包,等它加载完成才会变成熟悉的maven结构。
这里在配置的时候注意,classpath是java目录下,如果在src/main下面如果没有java可以自己建一个(我就是没有这个文件夹)。
接下来,项目加载完成了,需要导入依赖包了,编辑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>TestProject</groupId> <artifactId>test1</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>test1 Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- spring版本号 --> <spring.version>4.1.1.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.2.6</mybatis.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> <!-- jackson包版本 --> <jackson.version>2.5.0</jackson.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!--单元测试依赖 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <!-- 表示开发的时候引入,发布的时候不会加载此包 --> <scope>test</scope> </dependency> <!--spring单元测试依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <!-- springMVC核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-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>4.0.9.RELEASE</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> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!-- AOP begin --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.7.4</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.4</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.1</version> </dependency> <!-- AOP end --> <!-- Mysql数据库驱动包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </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 --> <!--servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <!-- 映入JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</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-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.1</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.0</version> </dependency> </dependencies> <build> <finalName>test1</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> <!-- 解决Maven项目编译后classes文件中没有.xml问题 --> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build> </project>
待加载完成后,配置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_3_0.xsd" id="WebApp_ID" version="3.0"> <welcome-file-list> <welcome-file>/index.html</welcome-file> </welcome-file-list> <display-name>test1</display-name> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:resources/spring-mvc.xml</param-value> </init-param> </servlet> <!-- 拦截设置 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --> <url-pattern>/</url-pattern> </servlet-mapping> <!--把applicationContext.xml加入到配置文件中--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:resources/applicationContext.xml</param-value> </context-param> <!--spring启动监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--日志配置--> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:resources/log4j.properties</param-value> </context-param> </web-app>
需要配置文件:spring bean配置文件,spring mvc配置文件,jdbc.properties,log4j配置文件。统一写在resource下。
此时路径是 classpath:resource/*.xml。
其他几份配置文件。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd"> <!-- 进行主数据库的事务配置,采用默认策略 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 引入jdbc配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:resources/jdbc.properties</value> </list> </property> </bean> <!-- 配置数据源 使用dbcp连接池--> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="url"> <value>${jdbc.url}</value> </property> <property name="driverClassName" value="${jdbc.driverClass}"/> <property name="username"> <value>${jdbc.username}</value> </property> <property name="password"> <value>${jdbc.password}</value> </property> <!--initialSize: 初始化连接--> <property name="initialSize" value="25"/> <property name="maxTotal" value="20"/> <property name="maxIdle" value="5"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref ="dataSource"/> </bean> <!--Dao Config--> <bean id="demoDao" class="Dao.DemoDao"> <property name="jdbcTemplate" ref ="jdbcTemplate"/> </bean> </beans>
<?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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <description>Spring MVC Configuration</description> <mvc:annotation-driven/> <!-- scan the package and the sub package --> <context:component-scan base-package="controller"/> <!-- don't handle the static resource --> <mvc:default-servlet-handler /> <!-- if you use annotation you must configure following setting --> <mvc:annotation-driven /> <!-- configure the InternalResourceViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="" /> <!-- 后缀 --> <property name="suffix" value="" /> </bean> </beans>
### \u8BBE\u7F6E###
log4j.rootLogger=D,E,CONSOLE
###set spring not output under error rank
log4j.logger.org.springframework=ERROR
###Console print
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] -[ %l ] %m%n
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] -[ %l ] %m%n
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = ${catalina.base}/InvoiceLogs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] -[ %l ] %m%n
jdbc.driverClass = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/Test?useUnicode=true&&characterEncoding=UTF-8 jdbc.username = 账号 jdbc.password = 密码
配置完成之后写个demo然后看看运行正常么。
package controller; import Dao.DemoDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; import java.util.Map; /** * Created by MacBook on 2017/11/5. */ @RequestMapping("/first") @Controller public class FirstController { @Autowired private DemoDao demoDao; @RequestMapping(value="/sayHello",produces="text/html;charset=UTF-8",method = RequestMethod.GET) public @ResponseBody String sayHello(){ return "hello"; } @RequestMapping(value="/testDao",produces="text/html;charset=UTF-8",method = RequestMethod.GET) public @ResponseBody String testDao(){ StringBuilder sb = new StringBuilder(); List<Map<String,Object>> arr = demoDao.getAddressAll(); if(arr != null){ for(Map<String,Object> map : arr){ sb.append("id :"+map.get("id").toString()).append("\t"); sb.append("address :"+map.get("address").toString()).append("\t"); sb.append("remart :"+map.get("remark").toString()).append("\t"); sb.append("\r\n"); } }else { sb.append("no data"); } return sb.toString(); } }
package Dao; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; import java.util.Map; /** * Created by MacBook on 2017/11/5. */ public class DemoDao { private JdbcTemplate jdbcTemplate; //测试获取address信息 public List<Map<String,Object>> getAddressAll(){ String sql = "select * from address"; try{ return jdbcTemplate.queryForList(sql); }catch (Exception e){ e.printStackTrace(); return null; } } public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } }
测试运行正常,到此笔记结束。
对jdbcTemplate的泛型数据处理那是服服帖帖的,数据库返回的数据,要不就是一列要不就是多列要不就是没有。List<Map<String,Object>>为多列数据,Map<String,Object>为一列数据,没有会抛异常。有点近乎于nosql的领域,需要什么拿什么这种感觉。舍弃了繁重的数据封装model层。
- 结尾
本来新建项目是件很简单的事情,但是上周弄了快一个下午,所以特此记录一下。