1、HttpClient遠程介面調用 1)用戶註冊 註冊按鈕 提交表單時,要 表單 js提交表單 2)載入外部資源文件 app.properties 編輯 RestApiServerInfo.java 3)HTTPClient工具遠程調用介面 導入依賴 發送post請求 工具類 遠程介面返回 封裝對 ...
1、HttpClient遠程介面調用
1)用戶註冊
註冊按鈕button
提交表單時,要return false
form
表單
<!-- action="http://localhost:8082/scw-restapi/member/regist" -->
<form class="form-signin" role="form" action="${ctp}/member/regist"
method="post" id="regForm">
...
</form>
js提交表單
$("#submitBtn").click(function() {
var loginType = $("select.form-control").val();
log("註冊類型==============>", loginType)
/* if (loginType == "管理") {
$("#regForm").submit();
} else {
alert("此功能尚未開通");
} */
$("#regForm").submit();
return false
})
2)載入外部資源文件
app.properties
restapi.server.ip=127.0.0.1
restapi.server.port=8082
restapi.server.apppath=scw-restapi
編輯springmvc.xml
<!-- 引入外部配置文件 -->
<context:property-placeholder
location="classpath:other/app.properties" />
RestApiServerInfo.java
@Controller
public class RestApiServerInfo {
// MemberService memberService;
@Value("${restapi.server.ip}")
private String restapiserver;
@Value("${restapi.server.port}")
private String restapiport;
@Value("${restapi.server.apppath}")
private String appPath;
public String getRestApiURL() {
System.out.println("http://" + restapiserver + ":" + restapiport);
return "http://" + restapiserver + ":" + restapiport + "/" + appPath;
}
}
3)HTTPClient工具遠程調用介面
導入依賴
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
發送post請求
public static String httpPostRequest(String url, Map<String, Object> params)
工具類HttpClientUtil.java
package com.atguigu.project;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* @author Nan 2015-11
*/
public class HttpClientUtil {
private static PoolingHttpClientConnectionManager cm;
private static String EMPTY_STR = "";
private static String UTF_8 = "UTF-8";
private static void init() {
if (cm == null) {
cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(50);// 整個連接池最大連接數
cm.setDefaultMaxPerRoute(5);// 每路由最大連接數,預設值是2
}
}
/**
* 通過連接池獲取HttpClient
*
* @return
*/
private static CloseableHttpClient getHttpClient() {
init();
return HttpClients.custom().setConnectionManager(cm).build();
}
/**
* @param url
* @return
*/
public static String httpGetRequest(String url) {
HttpGet httpGet = new HttpGet(url);
return getResult(httpGet);
}
public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setPath(url);
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
ub.setParameters(pairs);
HttpGet httpGet = new HttpGet(ub.build());
return getResult(httpGet);
}
public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params)
throws URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setPath(url);
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
ub.setParameters(pairs);
HttpGet httpGet = new HttpGet(ub.build());
for (Map.Entry<String, Object> param : headers.entrySet()) {
httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
return getResult(httpGet);
}
public static String httpPostRequest(String url) {
HttpPost httpPost = new HttpPost(url);
return getResult(httpPost);
}
public static String httpPostRequest(String url, Map<String, Object> params) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
return getResult(httpPost);
}
public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params)
throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
for (Map.Entry<String, Object> param : headers.entrySet()) {
httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
return getResult(httpPost);
}
private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> param : params.entrySet()) {
pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
}
return pairs;
}
/**
* 處理Http請求
*
* @param request
* @return
*/
private static String getResult(HttpRequestBase request) {
// CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpClient httpClient = getHttpClient();
try {
CloseableHttpResponse response = httpClient.execute(request);
// response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity != null) {
// long len = entity.getContentLength();// -1 表示長度未知
String result = EntityUtils.toString(entity);
response.close();
// httpClient.close();
return result;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return EMPTY_STR;
}
}
遠程介面返回ScwReturn<T>
封裝對象
package com.atguigu.scw.restapi.bean;
import java.util.Map;
public class ScwReturn<T> {
private int code;// 狀態碼 1:表示成功 0:表示失敗
private String msg;// 要給的提示信息
private T content;// 響應的內容;
private Map<String, Object> ext;// 額外的數據
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getContent() {
return content;
}
public void setContent(T content) {
this.content = content;
}
public Map<String, Object> getExt() {
return ext;
}
public void setExt(Map<String, Object> ext) {
this.ext = ext;
}
// 兩個快速的成功失敗方法
public static <T> ScwReturn<T> success(String msg, T content, Map<String, Object> ext) {
ScwReturn<T> t = new ScwReturn<T>();
t.setCode(1);
t.setMsg(msg);
t.setContent(content);
t.setExt(ext);
return t;
}
public static <T> ScwReturn<T> fail(String msg, T content, Map<String, Object> ext) {
ScwReturn<T> t = new ScwReturn<T>();
t.setCode(0);
t.setMsg(msg);
t.setContent(content);
t.setExt(ext);
return t;
}
}
註冊調用遠程介面
發送請求
String response = HttpClientUtil.httpPostRequest(url, params);
遠程介面返回的響應字元串轉java對象
readValue = new ObjectMapper().readValue(response.getBytes(), new TypeReference<ScwReturn<TMemeber>>() {
});
@RequestMapping("/regist")
public String regist(TMemeber memeber, Model model) throws Exception {
// 需要利用http工具去模擬發調用介面的請求
// http://localhost:8082/scw-restapi/member/regist
// <httpclient.version>4.5.3</httpclient.version>
// httpclient使用java代碼來模擬發送請求
// 能收到api調用後產生的json數據;
// 1、可以將產生的json逆向成對象ScwReturn<TMemeber>
// 2、可以直接將json寫給頁面
System.out.println("memeber===========>" + memeber);
// 註冊成功以後可以來到一個頁面;
// 1、應該去發送請求來進行註冊;java代碼發請求
String url = serverInfo.getRestApiURL() + "/member/regist";
System.out.println("url===========>" + url);
// 2、構建請求參數
Map<String, Object> params = new HashMap<String, Object>();
params.put("loginacct", memeber.getLoginacct());
// 密碼是業務邏輯加密的,我們不用管
params.put("userpswd", memeber.getUserpswd());
params.put("email", memeber.getEmail());
// 響應內容;
String response = HttpClientUtil.httpPostRequest(url, params);
// 封裝響應為對象
ScwReturn<TMemeber> readValue = null;
readValue = new ObjectMapper().readValue(response.getBytes(), new TypeReference<ScwReturn<TMemeber>>() {
});
// 判斷,註冊成功!來到登陸頁面
if (readValue.getCode() == 1) {
return "redirect:/login.jsp";
} else {
// 註冊失敗!來到註冊頁面進行回顯
model.addAttribute("msg", "用戶名和郵箱已經被註冊了!");
return "forward:/reg.jsp";
}
}
遠程介面註冊方法
控制層
/**
* ScwReturn<List<TMemeber>>:泛型是content內容的對象的類型
*
* @Description (TODO這裡用一句話描述這個方法的作用)
* @param memeber
* @return
*/
@RequestMapping("/regist")
public ScwReturn<TMemeber> regist(TMemeber memeber) {
// 創建一個空的對象
TMemeber regist = new TMemeber();
Map<String, Object> hashMap = new HashMap<>();
try {
regist = memberService.regist(memeber);
} catch (Exception e) {
// 判斷異常類型來放錯誤
// e.printStackTrace();
hashMap.put("error", "觸犯唯一約束,請保證用戶名和郵箱唯一");
}
regist.setUserpswd("");
if (regist.getId() != null) {
return ScwReturn.success("用戶註冊成功!", regist, null);
} else {
return ScwReturn.fail("用戶註冊失敗!", null, hashMap);
}
}
業務層
帶條件插入
int i = memeberMapper.insertSelective(tMemeber);
@Override
public TMemeber regist(TMemeber tMemeber) {
// TODO Auto-generated method stub
String digest = MD5Util.digest(tMemeber.getUserpswd());
// 加密密碼保存
tMemeber.setUserpswd(digest);
// 初始化用戶名和賬號
tMemeber.setUsername(tMemeber.getLoginacct());
// 實名認證狀態 0:未實名認證 1::實名認證
tMemeber.setAuthstatus("0");
// 真實姓名;實名認證是保存的
tMemeber.setRealname("未實名");
// 0:普通會員 1:月費會員 2:年費會員 3:
tMemeber.setUsertype("0");
// 身份證號,賬戶類型;(實名認證是做的)
// 賬戶類型:直接保存賬戶的全名
int i = memeberMapper.insertSelective(tMemeber);
// 剛纔就是按照這個對象給資料庫插入值,希望獲取到資料庫分配的自增主鍵
return tMemeber;
}
2、實名認證文件上傳
1)上傳用戶資質證件
導入依賴
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
編輯springmvc.xml
文件
<!-- 1、文件上傳需要一個文件上傳解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
</bean>
前臺ajax提交
帶有文件表單,一次提交所有項
var fd = new FormData($("#certForm")[0])
帶有文件表單,提交部分內容
//使用formData(js對象來包裝form表單)
var fd = new FormData();
log($("#ad_name_input").val())
log($("#ad_file_input")[0].files[0])
fd.append("name", $("#ad_name_input").val());
fd.append("ad", $("#ad_file_input")[0].files[0])
processData(預設: true)
預設情況下,通過data選項傳遞進來的數據,如果是一個對象(技術上講只要不是字元串),都會處理轉化成一個查詢字元串,以配合預設內容類型 "application/x-www-form-urlencoded"。
contentType
不使用預設的內容類型;(預設: "application/x-www-form-urlencoded") 發送信息至伺服器時內容編碼類型。
//這是一個資質文件上傳的頁面
//發送文件上傳資質文件請求;
var fd = new FormData($("#certForm")[0]);
$.ajax({
url:"http://localhost:8082/scw-restapi/auth/upload",
data:fd,
type:"post",
contentType:false,
dataType:"json",
processData:false,
success:function(result){
//來到郵箱填寫頁面
location.href="${ctp}/auth/apply-2.html"
},
error:function(e){
layer.msg("上傳失敗:"+e);
}
});
控制層
//文件上傳
private String uploadfile(String webPath,MultipartFile file,HttpSession session){
ServletContext context = session.getServletContext();
String realPath = context.getRealPath(webPath);
String name = UUID.randomUUID().toString().replace("-", "").substring(0, 10) +"_file_"+ file.getOriginalFilename();
try {
//webPath不存在的情況下必須創建
File file2 = new File(realPath);
if(!file2.exists()){
//創建目錄
file2.mkdirs();
}
file.transferTo(new File(realPath+"/"+name));
//返回這個圖片在伺服器下的路徑
return webPath+"/"+name;
}catch (Exception e) {
return null;
}
}
@RequestMapping("/upload")
public ScwReturn<Object> upload(HttpSession session,
@RequestParam("file")MultipartFile[] file,
@RequestParam("certid")Integer[] certid,@RequestParam("memberid")Integer memberid){
try {
System.out.println("資質的id"+certid);
List<TMemberCert> certsList= new ArrayList<TMemberCert>();
for (int i=0;i<certid.length;i++) {
TMemberCert cert = new TMemberCert();
MultipartFile multipartFile = file[i];
String uploadfile = uploadfile("/certsimg", multipartFile, session);
cert.setCertid(certid[i]);
cert.setMemberid(memberid);
cert.setIconpath(uploadfile);
certsList.add(cert);
}
//調用業務邏輯進行保存;/刪除原有資質,保存新的資質
certService.insertCerts(certsList);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e);
return ScwReturn.fail("資質保存失敗!", null, null);
}
return ScwReturn.success("保存成功!", null, null);
}
2)批量插入用戶資質證件描述信息
業務層
CertService.java
public void insertCerts(List<TMemberCert> certsList);
CertServiceImpl.java
@Override
public void insertCerts(List<TMemberCert> certsList) {
// TODO Auto-generated method stub
TMemberCertExample example = new TMemberCertExample();
Criteria criteria = example.createCriteria();
criteria.andMemberidEqualTo(certsList.get(0).getMemberid());
//先刪除
memberCertMapper.deleteByExample(example);
//後保存
certMapper.insertBatch(certsList);
}
dao層
TCertMapper.java
void insertBatch(@Param("certs")List<TMemberCert> certsList);
TCertMapper.xml
<!-- void insertBatch(@Param("certs")List<TMemberCert> certsList); -->
<insert id="insertBatch">
INSERT INTO t_member_cert(memberid,certid,iconpath)
VALUES
<foreach collection="certs" item="c" separator=",">
(#{c.memberid},#{c.certid},#{c.iconpath})
</foreach>
</insert>