IDEA DEMO练习一
一、环境搭建
需要准备的环境:
idea 2017.1
jdk1.7
Maven 3.3.3
请提前将idea与Maven、jdk配置好,本次项目用的都是比较新的,注:配置完ide红线报错没关系!可以run!
步骤:
一》、首先使用idea新建一个Maven webapp项目





二》、搭建目录结构

这里的目录建好之后还需要设置一下,让idea识别目录作用,选择File-Project Structure


三》更改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.chatRobot</groupId> <artifactId>ChatRobot</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>ChatRobot Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- spring版本号 --> <spring.version>4.3.5.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.4.1</mybatis.version> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <!-- java ee --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- 实现slf4j接口并整合 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.2</version> </dependency> <!-- JSON --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.7</version> </dependency> <!-- 数据库 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> <scope>runtime</scope> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </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.3.1</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-jdbc</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-web</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-test</artifactId> <version>${spring.version}</version> </dependency> </dependencies> <build> <finalName>ChatRobot</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <!-- 设置JDK版本 --> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
到此完成基本设置,再看具体代码

MainTreeController.java
package controller; import com.fasterxml.jackson.databind.ObjectMapper; import model.MainTree; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import service.MainTreeService; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Controller @RequestMapping("/tree") public class MainTreeController { @Resource private MainTreeService mainTreeService; @RequestMapping("/showTree.do") public void selectUser(HttpServletRequest request, HttpServletResponse response) throws IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); long id = Long.parseLong(request.getParameter("id")); MainTree mainTree = this.mainTreeService.selectTree(id); ObjectMapper mapper = new ObjectMapper(); response.getWriter().write(mapper.writeValueAsString(mainTree)); response.getWriter().close(); } }
MainTreeService.java
package service; import model.MainTree; public interface MainTreeService { public MainTree selectTree(long id); }
MainTreeServiceImpl.java
package service.impl; import dao.MainTreeDao; import model.MainTree; import org.springframework.stereotype.Service; import service.MainTreeService; import javax.annotation.Resource; @Service("userService") public class MainTreeServiceImpl implements MainTreeService { @Resource private MainTreeDao mainTreeDao; public MainTree selectTree(long id){ return this.mainTreeDao.selectTree(id); } }
MainTreeDao.java
package dao; import model.MainTree; public interface MainTreeDao { MainTree selectTree(long id); }
MainTree.java
package model; import java.math.BigDecimal; import java.util.Date; public class MainTree { Long id; String name; Long left_node_id; Long right_node_id; Long real_node_id; Long batch_id; BigDecimal matrix_bonus; BigDecimal binary_bonus; BigDecimal direct_bonus; Date create_time; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getLeft_node_id() { return left_node_id; } public void setLeft_node_id(Long left_node_id) { this.left_node_id = left_node_id; } public Long getRight_node_id() { return right_node_id; } public void setRight_node_id(Long right_node_id) { this.right_node_id = right_node_id; } public Long getReal_node_id() { return real_node_id; } public void setReal_node_id(Long real_node_id) { this.real_node_id = real_node_id; } public Long getBatch_id() { return batch_id; } public void setBatch_id(Long batch_id) { this.batch_id = batch_id; } public BigDecimal getMatrix_bonus() { return matrix_bonus; } public void setMatrix_bonus(BigDecimal matrix_bonus) { this.matrix_bonus = matrix_bonus; } public BigDecimal getBinary_bonus() { return binary_bonus; } public void setBinary_bonus(BigDecimal binary_bonus) { this.binary_bonus = binary_bonus; } public BigDecimal getDirect_bonus() { return direct_bonus; } public void setDirect_bonus(BigDecimal direct_bonus) { this.direct_bonus = direct_bonus; } public Date getCreate_time() { return create_time; } public void setCreate_time(Date create_time) { this.create_time = create_time; } }
mainTreeDaoTest.java(这里要注意IDEA的测试类首字母要小写,否则在运行测试类的时候报错。)
package com.chatRobot.dao; import dao.MainTreeDao; import model.MainTree; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; // 加载spring配置文件 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring-mybatis.xml"}) public class mainTreeDaoTest { @Autowired private MainTreeDao dao; @Test public void testSelectUser() throws Exception { long id = 1; MainTree user = dao.selectTree(id); System.out.println(user.getName()); } }
MainTreeDao.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"> <!-- 设置为IUserDao接口方法提供sql语句配置 --> <mapper namespace="dao.MainTreeDao"> <select id="selectTree" resultType="MainTree" parameterType="long"> SELECT * FROM txt_main_tree WHERE id = #{id} </select> </mapper>
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver #数据库地址 jdbc.url=jdbc:mysql://127.0.0.1:3306/pjjdb?useUnicode=true&characterEncoding=utf8 #用户名 jdbc.username=root #密码 jdbc.password=root #最大连接数 c3p0.maxPoolSize=30 #最小连接数 c3p0.minPoolSize=10 #关闭连接后不自动commit c3p0.autoCommitOnClose=false #获取连接超时时间 c3p0.checkoutTimeout=10000 #当获取连接失败重试次数 c3p0.acquireRetryAttempts=2
logback.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration debug="true"> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="debug"> <appender-ref ref="STDOUT"/> </root> </configuration>
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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 扫描web相关的bean --> <context:component-scan base-package="controller"/> <!-- 开启SpringMVC注解模式 --> <mvc:annotation-driven/> <!-- 静态资源默认servlet配置 --> <mvc:default-servlet-handler/> <!-- 配置jsp 显示ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
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:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 扫描service包下所有使用注解的类型 --> <context:component-scan base-package="service"/> <!-- 配置数据库相关参数properties的属性:${url} --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 数据库连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/> <property name="minPoolSize" value="${c3p0.minPoolSize}"/> <property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/> <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/> <property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/> </bean> <!-- 配置SqlSessionFactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource"/> <!-- 扫描model包 使用别名 --> <property name="typeAliasesPackage" value="model"/> <!-- 扫描sql配置文件:mapper需要的xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- 给出需要扫描Dao接口包 --> <property name="basePackage" value="dao"/> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置基于注解的声明式事务 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>ChatRobot</display-name> <description>ChatRobot_Alpha_0.0.1</description> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</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> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置DispatcherServlet --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置springMVC需要加载的配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-*.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> <!-- 匹配所有请求,此处也可以配置成 *.do 形式 --> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
index.jsp
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>test</title> </head> <script> function selectUser() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("test").innerHTML = xmlhttp.responseText; } } xmlhttp.open("POST", "tree/showTree.do", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("id=1"); } </script> <body> <p id="test">Hello World!</p> <button type="button" onclick="selectUser()">onclick test</button> </body> </html>
其他文件可以忽略。
运行测试类mainTreeDaoTest.java

因第一次没有把首字母改为小写,报过错误

当改完类首字母,仍然提示错误,因Junit版本过低,要求4.12及以上版本才行,更新如下

重新执行测试文件mainTreeDaoTest.java

下面再试一下通过tomcat来运行项目,发现通过下面的方式选不到tomcat图标,原来是因为settings里的Application Servers没有添加tomcat

先配置tomcat图标,在file -> settings里的Application Servers没有添加tomcat

再重新选择Run -> Edit Configurations,这回可以看到小猫了


点击屏幕右上角的运行

默认浏览器会出现运行结果界面

点击按钮,出现查询结果数据
{"id":1,"name":"A1","left_node_id":1,"right_node_id":2,"real_node_id":null,"batch_id":1,"matrix_bonus":null,"binary_bonus":null,"direct_bonus":null,"create_time":null}

以上为一个简单的查询DB例子。待续
参考文档:
环境搭建:
IDEA主代码参考:https://www.cnblogs.com/hackyo/p/6646051.html
IDEA添加TOMCATA https://www.cnblogs.com/Knowledge-has-no-limit/p/7240585.html
IDEA 中edit configurations加号找不到tomcat server:https://www.cnblogs.com/yuxiaole/p/9537177.html
IDEA JDK配置:https://blog.csdn.net/nobb111/article/details/77116259

浙公网安备 33010602011771号