<?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> <artifactId>jt-web</artifactId> <!--使用模板打jar包 不使用模板打war包--> <packaging>war</packaging> <!--父級工程--> <parent> <artifactId>jt2007</artifactId> <groupId>com.jt</groupId> <version>1.0-SNAPSHOT</version> </parent> <!--添加依賴項--> <dependencies> <dependency> <groupId>com.jt</groupId> <artifactId>jt-common</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> <!--添加maven插件--> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
說明:將課前資料中的文件src目錄導入到jt-web中javascript
說明:jt-web服務器啓動時會加載數據源的自動化配置,可是web服務器沒有配置數據源,因此報錯.
啓動類上添加數據源啓動.html
需求: 要求用戶經過http://www.jt.com 訪問localhost:8092服務器.前端
#配置前臺服務器 server { listen 80; server_name www.jt.com; location / { proxy_pass http://localhost:8092; } }
鍵入地址:chrome://net-internals/#hsts:
修改完成以後,先清空緩存以後重啓瀏覽器java
問題1: 京東的商品有不少,若是都採用靜態頁面的形式爲用戶展示數據,若是有100萬的商品,那麼就須要100萬個商品的xxx.html頁面. 問:京東是這麼作的嗎???
實現規則:
應該動態獲取商品的ID號.以後查詢數據庫,而後調整指定的頁面,將數據進行填充便可.jquery
問題2: 爲何京東採用.html結尾的請求展示商品呢?
答案: 採用.html結尾的頁面,更加容易被搜索引擎收錄,提升網站的曝光率.nginx
工做原理核心: 倒排索引機制. 根據關鍵字檢索文章的位置.web
僞靜態是相對真實靜態來說的,一般咱們爲了加強搜索引擎的友好面,都將文章內容生成靜態頁面,可是有的朋友爲了實時的顯示一些信息。或者還想運用動態腳本解決一些問題。不能用靜態的方式來展現網站內容。可是這就損失了對搜索引擎的友好面。怎麼樣在二者之間找個中間方法呢,這就產生了僞靜態技術。僞靜態技術是指展現出來的是以html一類的靜態頁面形式,但實際上是用ASP一類的動態腳原本處理的。ajax
說明: 因爲京東商城的商品展示時經過spring
url:https://item.jd.com/10021377498920.html,京東的訪問是根據.html進行攔截,以後經過restFul結構動態獲取商品的ID號,以後查詢數據庫進行的回顯.因此須要對後綴進行攔截.有了以下的配置.chrome
package com.jt.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MvcConfigurer implements WebMvcConfigurer{ //開啓匹配後綴型配置 @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.setUseSuffixPatternMatch(true); } }
URL地址小結:
通常條件下:Controller只攔截前綴類型的請求. 若是須要攔截後綴類型的請求須要單獨配置.
url1: http://www.jt.com/user/login.html 跳轉頁面 login.jsp
url2: http://www.jt.com/user/register.html 跳轉頁面 register.jsp
需求: 可否利用一個Controller方法.實現通用頁面的跳轉?
package com.jt.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/user") public class UserController { /** * 實現用戶登陸/註冊頁面的跳轉 * url1:http://www.jt.com/user/register.html * url2:http://www.jt.com/user/login.html */ @RequestMapping("/{moduleName}") public String module(@PathVariable String moduleName){ return moduleName; } }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>測試JSON跨域問題</title> <script type="text/javascript" src="http://manage.jt.com/js/jquery-easyui-1.4.1/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $.get("http://manage.jt.com/test.json",function(data){ alert(data.name); }) }) </script> </head> <body> <h1>JSON跨域請求測試</h1> </body> </html>
{"id":"1","name":"tom"}
瀏覽器URL地址: http://manage.jt.com/test.html
頁面AjaxURl地址: http://manage.jt.com/test.json
發現:協議:域名:端口都相同時,請求能夠正常執行
規定: 若是瀏覽器的地址與Ajax的請求地址 協議名稱://域名地址:端口號 若是都相同則知足同源策略.瀏覽器能夠正常的解析返回值. 若是三者之間有一個不一樣,則違反了同源策略.瀏覽器不會解析返回值.
因爲業務須要,一般A服務器中的數據可能來源於B服務器. 當瀏覽器經過網址解析頁面時,若是頁面內部發起ajax請求.若是瀏覽器的訪問地址與Ajax訪問地址不知足同源策略時,則稱之爲跨域請求.
跨域要素:
1.瀏覽器
2.解析ajax
3.違反了同源策略
JSONP(JSON with Padding)是JSON的一種「使用模式」,可用於解決主流瀏覽器的跨域數據訪問的問題。因爲同源策略,通常來講位於 server1.example.com 的網頁沒法與不是 server1.example.com的服務器溝通,而 HTML 的
1.利用javaScript中的src屬性能夠跨域的訪問.
<script type="text/javascript" src="http://manage.jt.com/test.json"></script>
2.提早準備一個回調函數 callback()
/*定義回調函數 */ function hello(data){ alert(data.name); }
3.將返回值結果進行特殊的格式封裝. callback(JSON數據)
hello({"id":"1","name":"tom"})
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JSONP測試</title> <script type="text/javascript" src="http://manage.jt.com/js/jquery-easyui-1.4.1/jquery.min.js"></script> <script type="text/javascript"> $(function(){ //讓頁面加載完成以後再次執行 alert("測試訪問開始!!!!!") $.ajax({ url:"http://manage.jt.com/web/testJSONP", type:"get", //jsonp只能支持get請求 dataType:"jsonp", //dataType表示返回值類型 jsonp: "callback", //指定參數名稱 jsonpCallback: "hello", //指定回調函數名稱 success:function (data){ //data通過jQuery封裝返回就是json串 alert(data.id); alert(data.name); //轉化爲字符串使用 //var obj = eval("("+data+")"); //alert(obj.name); } }); }) </script> </head> <body> <h1>JSON跨域請求測試</h1> </body> </html>
毫秒數做用: 因爲瀏覽器進行業務請求時可能有緩存操做,因此添加毫秒數,避免瀏覽器將結果緩存.致使業務異常.
package com.jt.web; import com.fasterxml.jackson.databind.util.JSONPObject; import com.jt.pojo.ItemDesc; import com.jt.util.ObjectMapperUtil; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class WebJSONPController { /** * 完成JSONP跨域訪問 * url地址: http://manage.jt.com/web/testJSONP?callback=hello&_=1605584709377 * 參數: callback 回調函數的名稱 * 返回值: callback(json) */ @RequestMapping("/web/testJSONP") public JSONPObject testJSONP(String callback){ ItemDesc itemDesc = new ItemDesc(); itemDesc.setItemId(1000L).setItemDesc("JSONP遠程調用!!!"); JSONPObject jsonpObject = new JSONPObject(callback, itemDesc); return jsonpObject; } }
由於出於安全的考慮, 瀏覽器不容許Ajax調用當前源以外的資源. 即瀏覽器的同源策略.
CORS須要瀏覽器和服務器同時支持。目前,全部主流瀏覽器都支持該功能,IE瀏覽器不能低於IE10。在瀏覽器端, 整個CORS通訊過程都是瀏覽器自動完成,在請求之中添加響應頭信息,若是服務器容許執行跨域訪問.,則瀏覽器的同源策略放行.
說明: 由www.jt.com/test.html訪問頁面,以後內部由ajax發起請求. 獲得如圖的信息.信息中顯示,幾乎全部的瀏覽器都兼容CORS的方式,可是因爲服務器不容許跨域,因此請求被拒.
因爲跨域需求其餘的服務器也會須要跨域.因此在jt-common中添加跨域的配置
package com.jt.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 完成CORS跨域配置: 實現思路在請求的響應頭中添加訪問信息. */ @Configuration public class CORSConfig implements WebMvcConfigurer{//web項目的全局配置的接口. /** * 參數介紹: * 1.addMapping() 哪些請求能夠進行跨域操做 * addMapping("/**") 表示全部訪問後端的服務器的請求都容許跨域 * addMapping("/addUser/**") 表示部分請求能夠跨域 * /* 只能攔截一級目錄 * /** 能夠攔截多級目錄 * * 2.allowedOrigins("*") 容許哪些網站跨域 * 3.allowCredentials(true) 請求跨域時是否容許攜帶Cookie/Session相關 * @param registry */ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowCredentials(true); //.maxAge(); 默認30分鐘 是否容許跨域請求 30分鐘以內不會再次驗證 //.allowedMethods() 容許請求類型 } }
1.什麼叫跨域 瀏覽器解析Ajax時,發起url請求違反了同源策略時,稱之爲跨域.
2.何時用跨域 通常A服務器須要從B服務器中獲取數據時,能夠採用跨域的方式.
3.什麼是JSONP JSONP是JSON的一種使用模式 利用javaScript中的src屬性進行跨域請求.(2.自定義回調函數,3.將返回值進行特殊格式封裝)
4.什麼是CORS CORS是當前實現跨域的主流方式,如今全部的主流瀏覽器都支持,須要在服務器端配置是否容許跨域的配置. 只要配置了(在響應頭中添加容許跨域的標識),則同源策略不生效,則能夠實現跨域.
<?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> <artifactId>jt-sso</artifactId> <!--默認打包就是jar包--> <parent> <artifactId>jt2007</artifactId> <groupId>com.jt</groupId> <version>1.0-SNAPSHOT</version> </parent> <!--3.依賴工具API--> <dependencies> <dependency> <groupId>com.jt</groupId> <artifactId>jt-common</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> <!--4.添加maven插件--> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
@TableName("tb_user") @Data @Accessors(chain = true) public class User extends BasePojo{ @TableId(type = IdType.AUTO) private Long id; //主鍵自增 private String username; private String password; //密碼 private String phone; //電話號碼 private String email; //郵箱地址 暫時使用電話號碼代替 }
修改以後,重啓nginx便可
package com.jt.controller; import com.fasterxml.jackson.databind.util.JSONPObject; import com.jt.pojo.User; import com.jt.service.UserService; import com.jt.vo.SysResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; /** * 業務需求: 查詢全部用戶信息 * url: sso.jt.com localhost:8093 /findAll * 返回值: List<User> */ @RequestMapping("/findAll") public List<User> findAll(){ return userService.findAll(); } /** * 需求:實現用戶信息校驗 * 校驗步驟: 須要接收用戶的請求,以後利用RestFul獲取數據, * 實現數據庫校驗,按照JSONP的方式返回數據. * url地址: http://sso.jt.com/user/check/admin123/1?r=0.8&callback=jsonp16 * 參數: restFul方式獲取 * 返回值: JSONPObject */ @RequestMapping("/check/{param}/{type}") public JSONPObject checkUser(@PathVariable String param, @PathVariable Integer type, String callback){ //只須要校驗數據庫中是否有結果 boolean flag = userService.checkUser(param,type); SysResult sysResult = SysResult.success(flag); return new JSONPObject(callback, sysResult); } }
package com.jt.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.jt.mapper.UserMapper; import com.jt.pojo.User; import com.jt.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; private static Map<Integer,String> paramMap = new HashMap<>(); static { paramMap.put(1, "username"); paramMap.put(2, "phone"); paramMap.put(3, "email"); } @Override public List<User> findAll() { return userMapper.selectList(null); } /** * 校驗數據庫中是否有數據 * Sql:select count(*) from tb_user where username="admin123"; * 要求:返回數據true用戶已存在,false用戶不存在,能夠 * @param param * @param type * @return */ @Override public boolean checkUser(String param, Integer type) { //String column = type==1?"username":(type==2?"phone":"email"); //很差,優化成paramMap集合 String column = paramMap.get(type); QueryWrapper<User> queryWrapper=new QueryWrapper<>(); queryWrapper.eq(column, param); int count = userMapper.selectCount(queryWrapper); return count>0?true:false; } }
package com.jt.aop; import com.fasterxml.jackson.databind.util.JSONPObject; import com.jt.vo.SysResult; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest; @RestControllerAdvice //定義全局異常處理 public class SystemException { //遇到運行時異常時方法執行. //JSONP報錯 返回值 callback(JSON) 若是請求參數中包含callback參數,則標識爲跨域請求 @ExceptionHandler({RuntimeException.class}) public Object fail(Exception e, HttpServletRequest request){ e.printStackTrace(); //輸出異常信息. String callback = request.getParameter("callback"); if(StringUtils.isEmpty(callback)){ //若是參數爲空表示 不是跨域請求. return SysResult.fail(); }else{ //有callback參數,表示是跨域請求. SysResult sysResult = SysResult.fail(); return new JSONPObject(callback,sysResult); } } }
HTTP 協議多是如今 Internet 上使用得最多、最重要的協議了,愈來愈多的 Java 應用程序須要直接經過 HTTP 協議來訪問網絡資源。雖然在 JDK 的 java net包中已經提供了訪問 HTTP 協議的基本功能,可是對於大部分應用程序來講,JDK 庫自己提供的功能還不夠豐富和靈活。HttpClient 是 Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,而且它支持 HTTP 協議最新的版本和建議。HttpClient 已經應用在不少的項目中,好比 Apache Jakarta 上很著名的另外兩個開源項目 Cactus 和 HTMLUnit 都使用了 HttpClient。如今HttpClient最新版本爲 HttpClient 4.5 .6(2015-09-11)
<!--添加httpClient jar包 --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency>
package com.jt.test; import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.io.IOException; //@SpringBootTest //從spring容器中獲取bean對象,以後完成測試業務. public class TestHttpClient { /** * 1.實例化HttpClient對象 * 2.定義遠程訪問的url地址 * 3.定義請求類型的對象 * 4.發起http請求,獲取響應的結果 * 5.對返回值結果進行校驗.獲取真實的數據信息. * */ @Test public void testGet() throws IOException { HttpClient httpClient = HttpClients.createDefault(); String url = "http://www.baidu.com"; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); //常見結果狀態 200 404 406參數異常 500後端服務器異常 504超時 502訪問的網址不存在 //獲取狀態碼 int status = httpResponse.getStatusLine().getStatusCode(); if(status == 200){ //獲取響應結果 HttpEntity entity = httpResponse.getEntity(); String result = EntityUtils.toString(entity,"UTF-8"); System.out.println(result); } } }
用戶經過http://www.jt.com/user/testHt...
JT-WEB服務器 訪問JT-SSO時的請求http://sso.jt.com/user/testHt...
/** * 需求: 獲取userList集合 並將其中的郵箱信息改成電話號碼 * url: http://www.jt.com/user/testHttpClient * 返回值:List<User> */ @RequestMapping("/testHttpClient") @ResponseBody public List<User> testHttpClient(){ return userService.testHttpClient(); }
package com.jt.service; import com.jt.pojo.User; import com.jt.util.ObjectMapperUtil; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; @Service public class UserServiceImpl implements UserService{ @Override public List<User> testHttpClient() { List userList = new ArrayList<>(); //由jt-web服務器去連接jt-sso的服務器 String url = "http://sso.jt.com/user/testHttpClient"; HttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); try { HttpResponse httpResponse =httpClient.execute(httpGet); if(httpResponse.getStatusLine().getStatusCode() == 200){ HttpEntity httpEntity = httpResponse.getEntity(); String result = EntityUtils.toString(httpEntity, "UTF-8"); userList = ObjectMapperUtil.toObject(result, userList.getClass()); /* for (LinkedHashMap<String,Object> map : userList){ User userTemp = new User(); userTemp.setId( Long.parseLong(map.get("id")+"")); userTemp.setUsername((String)map.get("username")); userTemp.setPassword((String)map.get("password")); userTemp.setPhone((String)map.get("phone")); userTemp.setEmail((String)map.get("phone")); userList2.add(userTemp); }*/ } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } return userList; } }
/** * http://sso.jt.com/user/testHttpClient * 返回List<User> */ @RequestMapping("testHttpClient") public List<User> testHttpClient(){ return userService.findAll(); }
@Override public List<User> findAll() { return userMapper.selectList(null); }