Maven搭建SSM框架測試HTTP 介面
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.xsd"> <mvc:default-servlet-handler/> <!-- Controller包(自動注入) --> <context:component-scan base-package="com.http.controller"/> <!-- FastJson注入 --> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <!-- 避免IE執行AJAX時,返回JSON出現下載檔案 --> <!-- FastJson --> <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <!-- 這裡順序不能反,一定先寫text/html,不然ie下出現下載提示 --> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> <property name="features"> <array value-type="com.alibaba.fastjson.serializer.SerializerFeature"> <!-- 避免迴圈引用 --> <value>DisableCircularReferenceDetect</value> <!-- 是否輸出值為null的欄位 --> <value>WriteMapNullValue</value> <!-- 數值欄位如果為null,輸出為0,而非null --> <value>WriteNullNumberAsZero</value> <!-- 字元型別欄位如果為null,輸出為"",而非null --> <value>WriteNullStringAsEmpty</value> <!-- List欄位如果為null,輸出為[],而非null --> <value>WriteNullListAsEmpty</value> <!-- Boolean欄位如果為null,輸出為false,而非null --> <value>WriteNullBooleanAsFalse</value> <!-- 設定日期封裝json格式:yyyy-MM-dd HH:mm:ss --> <value>WriteDateUseDateFormat</value> </array> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 靜態資源配置 --> <mvc:resources mapping="/resources/**" location="/resources/"/> <!-- 對模型檢視名稱的解析,即在模型檢視名稱新增前後綴 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 上傳限制 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 上傳檔案大小限制為31M,31*1024*1024 --> <property name="maxUploadSize" value="32505856"/> </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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 配置資料來源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc_url}"/> <property name="username" value="${jdbc_username}"/> <property name="password" value="${jdbc_password}"/> <!-- 初始化連線大小 --> <property name="initialSize" value="0"/> <!-- 連線池最大使用連線數量 --> <property name="maxActive" value="20"/> <!-- 連線池最大空閒 --> <property name="maxIdle" value="20"/> <!-- 連線池最小空閒 --> <property name="minIdle" value="0"/> <!-- 獲取連線最大等待時間 --> <property name="maxWait" value="60000"/> <property name="validationQuery" value="${validationQuery}"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="testWhileIdle" value="true"/> <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <!-- 配置一個連線在池中最小生存的時間,單位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000"/> <!-- 開啟removeAbandoned功能 --> <property name="removeAbandoned" value="true"/> <!-- 1800秒,也就是30分鐘 --> <property name="removeAbandonedTimeout" value="1800"/> <!-- 關閉abanded連線時輸出錯誤日誌 --> <property name="logAbandoned" value="true"/> <!-- 監控資料庫 --> <property name="filters" value="mergeStat"/> </bean> <!-- Spring整合Mybatis --> <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 自動掃描Mapping.xml檔案 --> <property name="mapperLocations" value="classpath:com/http/mapper/*Mapper.xml"/> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/> <property name="typeAliasesPackage" value="com.http.model"/> <property name="plugins"> <array> <!-- 分頁外掛配置 --> <bean id="paginationInterceptor" class="com.baomidou.mybatisplus.plugins.PaginationInterceptor"> </bean> </array> </property> <!-- 全域性配置注入 --> <property name="globalConfig" ref="globalConfig" /> </bean> <bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration"> <!-- AUTO->`0`("資料庫ID自增") INPUT->`1`(使用者輸入ID") ID_WORKER->`2`("全域性唯一ID") UUID->`3`("全域性唯一ID") --> <property name="idType" value="2" /> <!-- MYSQL->`mysql` ORACLE->`oracle` DB2->`db2` H2->`h2` HSQL->`hsql` SQLITE->`sqlite` POSTGRE->`postgresql` SQLSERVER2005->`sqlserver2005` SQLSERVER->`sqlserver` --> <!-- Oracle需要新增該項 --> <!-- <property name="dbType" value="oracle" /> --> <!-- 全域性表為下劃線命名設定 true --> <!-- <property name="dbColumnUnderline" value="true" /> --> <!-- <property name="metaObjectHandler"> <bean class="com.baomidou.springmvc.common.MyMetaObjectHandler" /> </property> --> </bean> <!-- MyBatis 動態掃描 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.http.dao"/> </bean> <!-- 配置事務管理 --> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 事務管理 屬性 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="append*" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="modify*" propagation="REQUIRED"/> <tx:method name="edit*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="remove*" propagation="REQUIRED"/> <tx:method name="repair" propagation="REQUIRED"/> <tx:method name="get*" propagation="REQUIRED" read-only="true"/> <tx:method name="find*" propagation="REQUIRED" read-only="true"/> <tx:method name="load*" propagation="REQUIRED" read-only="true"/> <tx:method name="search*" propagation="REQUIRED" read-only="true"/> <tx:method name="datagrid*" propagation="REQUIRED" read-only="true"/> <tx:method name="*" propagation="REQUIRED" read-only="true"/> </tx:attributes> </tx:advice> <!-- 配置切面事務傳播 --> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.http.service..*.*(..))"/> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice"/> </aop:config> </beans>
mybatis-config.xml檔案
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-- | plugins在配置檔案中的位置必須符合要求,否則會報錯,順序如下: | properties?, settings?, | typeAliases?, typeHandlers?, | objectFactory?,objectWrapperFactory?, | plugins?, | environments?, databaseIdProvider?, mappers? |--> <configuration> <!-- | 全域性配置設定 | | 可配置選項 預設值, 描述 | | aggressiveLazyLoading true, 當設定為‘true’的時候,懶載入的物件可能被任何懶屬性全部載入。否則,每個屬性都按需載入。 | multipleResultSetsEnabled true, 允許和不允許單條語句返回多個數據集(取決於驅動需求) | useColumnLabel true, 使用列標籤代替列名稱。不同的驅動器有不同的作法。參考一下驅動器文件,或者用這兩個不同的選項進行測試一下。 | useGeneratedKeys false, 允許JDBC 生成主鍵。需要驅動器支援。如果設為了true,這個設定將強制使用被生成的主鍵,有一些驅動器不相容不過仍然可以執行。 | autoMappingBehavior PARTIAL, 指定MyBatis 是否並且如何來自動對映資料表字段與物件的屬性。PARTIAL將只自動對映簡單的,沒有巢狀的結果。FULL 將自動對映所有複雜的結果。 | defaultExecutorType SIMPLE, 配置和設定執行器,SIMPLE 執行器執行其它語句。REUSE 執行器可能重複使用prepared statements 語句,BATCH執行器可以重複執行語句和批量更新。 | defaultStatementTimeout null, 設定一個時限,以決定讓驅動器等待資料庫迴應的多長時間為超時 | --> <settings> <!-- 這個配置使全域性的對映器啟用或禁用快取 --> <setting name="cacheEnabled" value="true"/> <!-- 全域性啟用或禁用延遲載入。當禁用時,所有關聯物件都會即時載入 --> <setting name="lazyLoadingEnabled" value="true"/> <setting name="multipleResultSetsEnabled" value="true"/> <setting name="useColumnLabel" value="true"/> <setting name="defaultExecutorType" value="REUSE"/> <setting name="defaultStatementTimeout" value="25000"/> </settings> </configuration>
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" xmlns:util="http://www.springframework.org/schema/util"
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/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 引入屬性檔案 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- Service包(自動注入) -->
<context:component-scan base-package="com.http.service"/>
<import resource="classpath:ssm/spring-mybatis.xml"/>
</beans>
web.xml檔案
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
<display-name>HttpAPI</display-name>
<!-- 載入Spring配置檔案 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ssm/spring.xml</param-value>
</context-param>
<!-- 字符集 過濾器 -->
<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>
<!-- Spring監聽器 -->
<listener>
<description>Spring監聽器</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring記憶體溢位監聽器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Spring MVC -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>SpringMVC</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ssm/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Session超時時間 -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
db.properties檔案
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=UTF-8
jdbc_username=root
jdbc_password=root
log4j.properties檔案
log4j.rootLogger=DEBUG,CONSOLE,A
log4j.addivity.org.apache=false
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=DEBUG
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} -%-4r [%t] %-5p %x - %m%n
log4j.appender.CONSOLE.Target=System.out
#log4j.appender.CONSOLE.charset=utf-8
log4j.appender.CONSOLE.encoding=utf-8
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.A=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A.File=${catalina.home}/logs/yo_log/PurePro_
log4j.appender.A.DatePattern=yyyy-MM-dd'.log'
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern=[FH_sys] %d{yyyy-MM-dd HH\:mm\:ss} %5p %c{1}\:%L \: %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
在webapp中添加個index.jsp。路徑對應spring-mvc.xml中配置的檢視解析路徑。Jsp中寫個著名的hello world。
Jsp內容
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
hello world
</body>
</html>
Pom.xml引入相關jar包,pom最下面的build部分如果沒有加的話,會因為JDK版本問題引起Java Resources有個紅叉,修改相應的JDK版本號,在專案上右鍵-->Maven-->Update project...紅叉就沒有了。
<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.http</groupId>
<artifactId>HttpAPI</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.2.5.RELEASE</spring.version>
<junit.version>4.12</junit.version>
<druid.version>1.1.0</druid.version>
<fastjson.version>1.2.8</fastjson.version>
<mybaitsplus.version>2.1-gamma</mybaitsplus.version>
<velocity.version>1.7</velocity.version>
<mysql.version>5.1.38</mysql.version>
<log4j.version>1.2.17</log4j.version>
<slf4j.version>1.7.19</slf4j.version>
<aspectjweaver.version>1.8.8</aspectjweaver.version>
<fileupload.version>1.3.1</fileupload.version>
<servlet.version>2.5</servlet.version>
<jstl.version>1.2</jstl.version>
</properties>
<dependencies>
<!-- JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- AOP -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectjweaver.version}</version>
</dependency>
<!-- FileUpload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${fileupload.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- Mybatis-Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>${mybaitsplus.version}</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>${velocity.version}</version>
</dependency>
<!-- Mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- FastJson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!-- Log -->
<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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
稍微改造下SysUserController,使專案訪問根目錄進入index.jsp。
package com.http.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.stereotype.Controller;
/**
* <p>
* 系統使用者表 前端控制器
* </p>
*
* @author GR·cheng
* @since 2017-11-17
*/
@Controller
@RequestMapping("/")
public class SysUserController {
@RequestMapping("/")
public ModelAndView index(ModelAndView modelAndView) {
modelAndView.setViewName("index");
return modelAndView;
}
}
將專案新增到tomcat伺服器
雙擊伺服器,修改下專案訪問名
儲存並啟動伺服器,在瀏覽器中訪問localhost:8080
然後在controller中寫個簡單的查詢,瀏覽器訪問下
package com.http.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.http.model.SysUser;
import com.http.service.SysUserService;
/**
* <p>
* 系統使用者表 前端控制器
* </p>
*
* @author GR·cheng
* @since 2017-11-17
*/
@Controller
@RequestMapping("/")
public class SysUserController {
@Autowired
private SysUserService userService;
@RequestMapping("/")
public ModelAndView index(ModelAndView modelAndView) {
modelAndView.setViewName("index");
return modelAndView;
}
@RequestMapping("/users")
@ResponseBody
public List<SysUser> users() {
return userService.selectList(null);
}
}
在瀏覽器中訪問下http://localhost:8080/users,看到頁面接收到的JSON資料說明框架一切OK了。
第二部分 使用HTTP工具類測試HTTP介面
1、新建HttpUtil.java,HttpTest.java。
2、controller中寫幾個http測試介面。
package com.http.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.http.common.util.DateUtil;
import com.http.model.SysUser;
import com.http.service.SysUserService;
/**
* <p>
* 系統使用者表 前端控制器
* </p>
*
* @author GR·cheng
* @since 2017-11-17
*/
@Controller
@RequestMapping("/")
public class SysUserController {
@Autowired
private SysUserService userService;
/**
*
*
* @Title: index
* @Description: 專案根目錄訪問index.jsp
* @param: @param modelAndView
* @param: @return
* @return: ModelAndView
* @user: GR·cheng
*
*/
@RequestMapping("/")
public ModelAndView index(ModelAndView modelAndView) {
modelAndView.setViewName("index");
return modelAndView;
}
/**
*
*
* @Title: users
* @Description: 查詢所有users
* @param: @return
* @return: List<SysUser>
* @user: GR·cheng
*
*/
@ResponseBody
@RequestMapping("/users")
public List<SysUser> users() {
List<SysUser> users = userService.selectList(null);
return users;
}
/**
*
*
* @Title: getParams
* @Description: get方法提交
* @param: @param id
* @param: @param name
* @param: @param age
* @param: @param ctime
* @param: @return
* @return: SysUser
* @user: GR·cheng
*
*/
@ResponseBody
@RequestMapping(value = "/API/getParams",method = RequestMethod.GET)
public static SysUser getParams(Long id,String name,Integer age,String ctime) {
SysUser user = new SysUser();
user.setId(id);
user.setName(name);
user.setAge(age);
user.setCtime(DateUtil.stringToDate(ctime,DateUtil.DATE_TEMPLATE_COMPLETE));
return user;
}
/**
*
*
* @Title: postParams
* @Description: post方法提交
* @param: @param id
* @param: @param name
* @param: @param age
* @param: @param ctime
* @param: @return
* @return: SysUser
* @user: GR·cheng
*
*/
@ResponseBody
@RequestMapping(value = "/API/postParams",method = RequestMethod.POST)
public static SysUser postParams(Long id,String name,Integer age,String ctime) {
SysUser user = new SysUser();
user.setId(id);
user.setName(name);
user.setAge(age);
user.setCtime(DateUtil.stringToDate(ctime,DateUtil.DATE_TEMPLATE_COMPLETE));
return user;
}
/**
*
*
* @Title: postJson
* @Description: post方法提交json資料
* @param: @param param
* @param: @return
* @return: SysUser
* @user: GR·cheng
*
*/
@ResponseBody
@RequestMapping(value = "/API/postJson",method = RequestMethod.POST)
public static SysUser postJson(@RequestBody String param) {
SysUser user = JSON.parseObject(param, SysUser.class);
return user;
}
}
3、編寫http工具類HttpUtil
package com.http.common.util;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class HttpUtil {
/**
*
*
* @Title: getParams
* @Description: HTTP GET 請求
* @param: @param uri 請求地址
* @param: @param params 引數串
* @param: @return
* @return: String
* @user: GR·cheng
*
*/
public static String getParams(String uri, String params) {
String result = "";
BufferedReader reader = null;
StringBuffer url = new StringBuffer();
try {
url.append(uri);
url.append("?");
url.append(params);// get的引數 xx=xx&yy=yy
URL realUrl = new URL(url.toString());
// 開啟和URL之間的連線
URLConnection connection = realUrl.openConnection();
// 設定通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("Content-Type","text/html; charset=utf-8");
connection.setRequestProperty("Charset", "UTF-8");
connection.connect();
// 定義 BufferedReader輸入流來讀取URL的響應
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
result = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
*
*
* @Title: postParams
* @Description: HTTP POST 請求
* @param: @param uri 請求地址
* @param: @param params 引數串
* @param: @return
* @return: String
* @user: GR·cheng
*
*/
public static String postParams(String uri, String params) {
URL url = null;
String result = null;
try {
url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
// 傳送POST請求必須設定如下兩行
connection.setDoOutput(true);
connection.setDoInput(true);
// 獲取URLConnection物件對應的輸出流
PrintWriter printWriter = new PrintWriter(
connection.getOutputStream());
// 傳送請求引數
printWriter.write(params);// post的引數 xx=xx&yy=yy
// flush輸出流的緩衝
printWriter.flush();
// 開始獲取資料
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
result = reader.readLine();
reader.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
*
*
* @Title: postJson
* @Description: HTTP POST請求方式提交JSON資料
* @param: @param uri 請求地址
* @param: @param object JSONObject
* @param: @return
* @param: @throws IOException
* @return: String
* @user: GR·cheng
*
*/
public static String postJson(String uri, JSONObject object) {
String result = null;
try {
// 建立url資源
URL url = new URL(uri);
// 建立http連線
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// 設定允許輸出
connection.setDoOutput(true);
// 設定允許輸入
connection.setDoInput(true);
// 設定傳遞方式POST
connection.setRequestMethod("POST");
// 設定不用快取
connection.setUseCaches(false);
// 設定本次連線是否自動處理重定向
connection.setInstanceFollowRedirects(true);
// 設定文字型別
connection.setRequestProperty("Content-Type",
"application/json;charset=UTF-8");
// 設定維持長連線
connection.setRequestProperty("Connection", "Keep-Alive");
// 設定文字字符集
connection.setRequestProperty("Charset", "UTF-8");
// 轉換為位元組陣列
byte[] json = (JSON.toJSONString(object)).getBytes();
// 設定文字長度
connection.setRequestProperty("Content-Length",
String.valueOf(json.length));
// 開始連線請求
connection.connect();
DataOutputStream out = new DataOutputStream(
connection.getOutputStream());
out.write(json);
out.flush();
out.close();
int code = connection.getResponseCode();
if (HttpURLConnection.HTTP_OK == code) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
result = reader.readLine();
reader.close();
}
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
4、寫個測試類測試下
package com.http.test;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.http.common.util.DateUtil;
import com.http.common.util.HttpUtil;
import com.http.model.SysUser;
public class HttpTest {
private static String getParams = "http://localhost:8080/API/getParams";
private static String postParams = "http://localhost:8080/API/postParams";
private static String postJson = "http://localhost:8080/API/postJson";
public static void main(String[] args) {
testGetParams();
testPostParams();
testPostJson();
}
public static void testGetParams() {
StringBuffer param = new StringBuffer();
try {
param.append("id=784972358981328902&name=");
param.append(URLEncoder.encode("奈文摩爾","UTF-8"));
param.append("&age=20");
param.append("&ctime=");
param.append(URLEncoder.encode("2017-11-11 11:11:11","UTF-8"));//get提交的引數是在url中的,帶有空格的引數必須轉譯
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String result = HttpUtil.getParams(getParams, param.toString());
System.out.println(result);
}
public static void testPostParams() {
StringBuffer param = new StringBuffer();
try {
param.append("id=784972358981328902&name=");
param.append(URLEncoder.encode("奈文摩爾","UTF-8"));
param.append("&age=20");
param.append("&ctime=2017-11-11 11:11:11");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String result = HttpUtil.postParams(postParams, param.toString());
System.out.println(result);
}
public static void testPostJson() {
SysUser user = new SysUser();
user.setId(784972358981328902L);
user.setName("奈文摩爾");
user.setAge(20);
user.setCtime(DateUtil.stringToDate("2017-11-11 11:11:11",DateUtil.DATE_TEMPLATE_COMPLETE));
JSONObject jsonObject = (JSONObject) JSON.toJSON(user);
String result = HttpUtil.postJson(postJson, jsonObject);
System.out.println(result);
}
}
5、啟動專案,執行下HttpTest中的main函式
結果返回都正確,一切OK。
相關推薦
Maven搭建SSM框架測試HTTP 介面
spring-mvc.xml檔案<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.
maven搭建ssm框架問題總結
error odi more 3.6 env 但是 exception finish ant 1. Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.6.0:compile (de
Maven搭建SSM框架(Spring+SpringMVC+MyBatis)
核心 suffix clas you info org 好項目 package span 一、概述: Spring是一個輕量級開發框架,好比一個大工廠(容器),可以將所有對象的創建和依賴關系交給spring管理。 SpringMVC是一個基於mvc的web框架。sp
Maven搭建SSM框架(xml版)
接下來講解基於Maven工具、以XML為配置檔案的SSM框架的環境搭建。 搭建環境: 1.maven3.5.3; 2.IDEA2018.2.3; 1.首先建立一個Maven專案,選擇webapp,如下圖,然後填寫專案GroupID和專案名稱即建立完畢; &
1112_超詳細圖文教程_用SpringBoot+Maven搭建SSM框架
【超詳細圖文教程】用SpringBoot+Maven搭建SSM框架 2017年10月09日 11:31:51 零薄獄 閱讀數:10386 標籤: Spring SpringMVC intellij idea SpringBoot SSM 更多 個人分類: Spring 專案用Inte
Maven專案搭建(二):Maven搭建SSM框架
上一章給大家講解了如何使用Maven搭建web專案。 這次給大家介紹一下怎麼使用Maven搭建SSM框架專案。 首先我們來看一下pom.xml的屬性介紹:
Maven項目搭建(二):Maven搭建SSM框架
mod ring 交互 插件 license plugin res myba put 上一章給大家講解了如何使用Maven搭建web項目。 這次給大家介紹一下怎麽使用Maven搭建SSM框架項目。 首先我們來看一下pom.xml的屬性介紹:
IDEA使用 maven 搭建 SSM 框架
文章目錄 pom 檔案的編寫 專案結構 SSM 配置檔案的編寫 web.xml 的配置 總結 公司有個小的內部使用的軟體,讓開發,自己選擇使用 SSM ;因為之前自己學過,本以為一切水
從零開始Eclipse/Maven搭建SSM框架做web應用(超詳細+100%可用+避坑版)
目前SSM框架(Spring+SpringMVC+Mybatis)依然是市場主流,如何搭建一個實用的SSM框架是很多同學都想學習的技能。但網路上的大多數教程要麼不完整,要麼還遺留了很多坑,即使嚴格按教程來也很難得到我們想要的結果。所以我就想自己寫一篇搭建攻略,即使零基礎的同學,按我的攻略步驟
eclipse+maven搭建SSM框架
目錄 maven下載及配置 下載後解壓放在D:\A\maven路徑下 在環境變數中,新增系統變數名:a.MAVEN_HOME,變數值:D:\A\Java\maven
基於idea+maven搭建SSM框架,自帶逆向工程
前面一篇搭建的是一個簡單的web框架點選開啟連結 今天搭建的是基於maven的pom檔案來進行框架的搭建,畢竟現在還手動架包的真的不多了。 今天搭建的這個框架如果你需要用到逆向功能你需要一個架包:點選下載 直接解壓到D盤下就可以了,
在IntelliJ IDEA上使用Maven搭建SSM框架(三)
<%@page contentType="text/html; charset=UTF-8" language="java" %> <%-- 引入jstl--%> <%@include file="common/tag.jsp" %> <!DOCTYPE html&g
Java maven搭建SSM框架主要配置檔案
web.xml配置 <?xml version="1.0" encoding="utf-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http:
IDEA使用maven搭建SSM框架整合專案(超級詳細,值得一看)
[TOC](IDEA使用maven搭建SSM框架整合專案(超級詳細,值得一看)) ## **溫馨提示** ***此篇文章篇幅較長,相信我看了這篇文章你一定會擼起碼來行雲流水,事半功倍,無懈可擊,請耐心閱讀。
從零搭建SSM框架(五)使用Maven實現Tomcat熱部署
SSM框架 技術分享 pre root mil p地址 註意 eight -1 配置tomcat 第一步:需要修改tomcat的conf/tomcat-users.xml配置文件。添加用戶名、密碼、權限。 <role rolename="manager-gui
在maven工程中搭建SSM框架的錯誤總結
clip build etime 代碼 class ati timezone 項目 mysql 第一次搭建Maven工程走了很多彎路,現在總算把項目搭起來並且能正常運行了。故總結一下教訓 1.在建立Maven工程前,先確定成功下載安裝了Maven。 命令行用 mvn -v
Spring+Mybatis+SpringMVC+Maven+MySql(SSM框架)搭建例項
這篇文章我們來實現使用maven構建工具來搭建Spring+Mybatis+SpringMVC+MySql的框架搭建例項。工程下載 使用maven當然得配置有關環境了,不會配置的請看我前幾篇文章,都有配置maven環境的列子! MySQL建立表sql語句: /* Navicat M
基於maven的SSM框架搭建+sqlserver資料庫
其實關於框架的搭建我在上面這篇部落格已經介紹了,但是它是基於mysql資料庫的,今天我們看看基於sqlserver資料庫該怎麼連線。 其實基於MySQL和sqlserver框架的搭建流程都是一樣的,具體可以看上面的網址。兩者的區別主要有兩部分: pom.xml檔案中的
maven模組化搭建SSM框架
本文是使用idea進行環境搭建的. 1.idea新建一個空白專案(作為專案的資料夾),然後next,->取名字->確定,本文中取名為pro_ssm. 2.在彈窗中選擇project,選擇jdk版本,然後OK. 3.選擇file->new-&
maven工程搭建ssm框架詳細開發流程
一.開啟eclipse建立maven工程 這裡不多說了 二.在pom.xml里加入jar包 注意不同版本之間的jar包可能會有衝突,也不要全都加最新版本的jar包,到時解決起來很麻煩 直接點選官網搜尋jar包名下載相應jar包 基本所需的jar包給大家發出來