第一篇文章,直接进入正题。
面向对象:对SpringMvc和Maven有一定了解的同学。
前置条件:IDEA+Tomcat+JDK+Maven,自行安装,建议tomcat9,JDK8.
1、新建maven工程,选择模板
2、填写groupid和artifactid
3、设置本地Maven路径、配置文件和本地库。
4、设置项目名称和项目路径
5、点击finish,等待IDEA编译,途中打开自动导入
6、完成后项目路径结构如下
7、编辑pom.xml文件,添加jar包依赖,导入常规项目jar包,内容如下:
<?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>online.chongwuzhi</groupId>
<artifactId>maven_springmvc_test</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>maven_springmvc_test Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-pool/commons-pool -->
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- https://mvnrepository.com/artifact/com.aliyun.oss/aliyun-sdk-oss -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>11.2.0.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.6.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15 -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15</artifactId>
<version>1.46</version>
</dependency>
</dependencies>
<build>
<finalName>maven_springmvc_test</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.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.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</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>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.*</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
</build>
</project>
8、编辑完成后,IDEA自动下载Jar包,如果本地库或者中心库已有Jar包则不需要下载。下载完成后的Jar包依赖如下:
9、以上完成了Maven的支持和配置,继续添加SpringMvc框架支持,右键项目名称,添加框架支持。
10、如果列表中没有Spring Mvc选项,先删除之前的框架
11、添加完成后出现如下2个文件
12、完善SpringMvc目录结构,在main文件夹下新建java和resources2个文件夹
13、调整刚才2个文件夹的属性,点击工程结构图标(按键为ctrl+alt+shift+s)
14、在java文件中建立项目需要的包,如下:
15、以上完成了Spring的框架支持,下边配置SpringMvc文件,此步骤是本人根据自己的理解和学习所做的改动,简化了xml文件的控制和冗余,如有其他个人理解,可自己设置。
3个文件全文如下:
1,SpringMVC.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" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"> <task:annotation-driven /> <!-- 扫描包 --> <context:component-scan base-package="com"/> <!-- 针对返回的JSON做转码 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" > <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=utf-8</value> <value>text/html;charset=UTF-8</value> <value>text/json;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <!-- 默认的注解映射的支持 --> <mvc:annotation-driven /> <!-- 支持文件上传--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxInMemorySize" value="2048" /> </bean> <!-- 指定spring读取db.properties数据库配置 --> <context:property-placeholder location="classpath:db.properties" /> <bean id="datasource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${jdbc.initialSize}" /> <!-- 连接池最大数量 --> <property name="maxActive" value="${jdbc.maxActive}" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${jdbc.maxIdle}" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="${jdbc.minIdle}" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${jdbc.maxWait}" /> <!-- 设置自动回收超时连接 --> <property name="removeAbandoned" value="true" /> <!-- 自动回收超时时间(以秒数为单位) --> <property name="removeAbandonedTimeout" value="${jdbc.abandTime}" /> <!-- 设置在自动回收超时连接的时候打印连接的超时错误 --> <property name="logAbandoned" value="true" /> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="datasource" /> <!-- 通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务 --> <aop:config proxy-target-class="true"> <aop:pointcut id="serviceMethod" expression=" execution(* com.service.*.*(..))" /> <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" /> </aop:config> <tx:advice id="txAdvice"> <tx:attributes> <tx:method name="*" /> </tx:attributes> </tx:advice> <!-- 注入JDBC --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="datasource"/> </bean></beans>
2,db.properties(链接和)
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc\:oracle\:thin\:@ip\:1521\:orcl
jdbc.username=***
jdbc.password=***
jdbc.initialSize=20
jdbc.maxActive=100
jdbc.maxIdle=10
jdbc.minIdle=5
jdbc.maxWait=5000
jdbc.abandTime=2000
3,log4j.properties
log4j.rootLogger = DEBUG,systemOut,logDailyFile
log4j.logger.org.apache=DEBUG
#输出到控制台
log4j.appender.systemOut = org.apache.log4j.ConsoleAppender
log4j.appender.systemOut.layout = org.apache.log4j.PatternLayout
log4j.appender.systemOut.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n
log4j.appender.systemOut.Threshold = ERROR
log4j.appender.systemOut.ImmediateFlush = TRUE
log4j.appender.systemOut.Target = System.out
#按DatePattern输出到文件
log4j.appender.logDailyFile = org.apache.log4j.DailyRollingFileAppender
log4j.appender.logDailyFile.layout = org.apache.log4j.PatternLayout
log4j.appender.logDailyFile.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n
#指定日志消息的输出最低层次
log4j.appender.logDailyFile.Threshold = DEBUG
#默认值是true,所有的消息都会被立即输出
log4j.appender.logDailyFile.ImmediateFlush = TRUE
#默认值true,将消息追加到指定文件中,false指将消息覆盖指定的文件内容
log4j.appender.logDailyFile.Append = TRUE
log4j.appender.logDailyFile.File = ../logs/prg.log
log4j.appender.logDailyFile.DatePattern = '.'yyyy-MM-dd
log4j.appender.logDailyFile.Encoding = UTF-8
修改web.xml,全文如下:
<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_4_0.xsd" version="4.0"> <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:SpringMVC.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <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> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <!-- log4j --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param></web-app>
16、以上完成了SpringMvc的文件配置和Maven的框架支持,接下来实战测试,配置应用服务器,以tomcat为例(自行安装tomcat),点击添加配置:
17、以上完成了SpringMvhe Maven的基本配置,接下来测试基于前后端分离JSON交互的SpringMvc框架(SpringMvc知识自行学习)。
先测试不传参数的请求,方法内容如下:
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("/test01.do")
@ResponseBody
public Map<String,Object> test01(){
Map<String,Object> map = new HashMap<>();
map.put("code", "1");
map.put("msg", "success");
return map;
}
}
接下来测试传参数的请求,首先新建方法,内容如下:
@RequestMapping("/test02.do")
@ResponseBody
public Map<String,Object> test02(@RequestBody JSONObject js){
String name= js.getString("name");
String age= js.getString("age");
Map<String,Object> map = new HashMap<>();
map.put("code", name);
map.put("msg", age);
return map;
}
继续新建测试方法,如下
private static void main2() {
HttpClient client = HttpClientBuilder.create().build()
;
HttpPost post = new HttpPost("http://localhost:8080/maven_springmvc_test_war_exploded/test/test02.do");
post.addHeader("Content-Type", "application/json;charset=utf-8");
JSONObject request = new JSONObject();
request.put("name","testName测试名称");
request.put("age","testName测试名称");
try{
StringEntity s =new StringEntity(request.toString(),"UTF-8");
s.setContentEncoding("utf-8");
s.setContentType("application/json");
post.setEntity(s);
HttpResponse res = client.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(entity);
System.out.println(result);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
重启tomcat, 运行测试方法main2