1.實現用户模塊跳轉
1.1 需求説明
説明:當用户點擊登錄/註冊按鈕時 需要跳轉到指定的頁面中.
url地址1.:http://www.jt.com/user/regist...
url地址2: http://www.jt.com/user/login....
1.2 編輯UserController
`package com.jt.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Controller //需要進行頁面跳轉
@RequestMapping("/user")
public class UserController {
/**
* 實現用户模塊頁面跳轉
* url1: http://www.jt.com/user/login.html 頁面:login.jsp
* url2: http://www.jt.com/user/register.html 頁面:register.jsp
* 要求:實現通用頁面跳轉
* restFul方式: 1.動態獲取url中的參數,之後實現通用的跳轉.
*/
@RequestMapping("/{moduleName}")
public String module(@PathVariable String moduleName){
return moduleName;
}
}`
1.3 頁面效果展現
2 JT-SSO項目創建
2.1 創建項目
2.2 添加繼承/依賴/插件
`<?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 不寫也沒有關係-->
<packaging>jar</packaging>
<parent>
<artifactId>jt</artifactId>
<groupId>com.jt</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<!--2.添加依賴信息-->
<dependencies>
<!--依賴實質依賴的是jar包文件-->
<dependency>
<groupId>com.jt</groupId>
<artifactId>jt-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<!--3.添加插件-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>`
2.3 編輯User的POJO對象
`@TableName("tb_user")
@Data
@Accessors(chain = true)
public class User extends BasePojo{
@TableId(type = IdType.AUTO)//設定主鍵自增
private Long id; //用户ID號
private String username; //用户名
private String password; //密碼 需要md5加密
private String phone; //電話號碼
private String email; //暫時使用電話代替郵箱
}`
2.4 測試JT-SSO項目
用户通過sso.jt.com/findUserAll 獲取user表中的信息 json返回
代碼結構如下:
2.4.1 編輯UserController
`package com.jt.controller;
import com.jt.pojo.User;
import com.jt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserService userService;
/**
* 完成測試按鈕
* 1.url地址 :findUserAll
* 2.參數信息: null
* 3.返回值結果: List<User>
*
*/
@RequestMapping("/findUserAll")
public List<User> findUserAll(){
return userService.findUserAll();
}
}`
2.4.2 編輯UserService
`package com.jt.service;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Override
public List<User> findUserAll() {
return userMapper.selectList(null);
}
}`
2.4.3 修改nginx配置
- 跨域實現(重要)
============
3.1 跨域訪問測試
3.1.1 同域測試
分析:
1.瀏覽器地址: http://manage.jt.com/test.html
2.ajax請求地址: http://manage.jt.com/test.json
結論:
當瀏覽器地址與ajax請求的地址(協議://域名:端口)相同時可以實現正常的業務調用.
`<script type="text/javascript" src="http://manage.jt.com/js/jquery-easyui-1.4.1/jquery.min.js"></script>
<!--引入類庫之後,執行js代碼-->
<script type="text/javascript">
<!--讓整個頁面加載完成之後執行js-->
$(function(){
$.get("http://manage.jt.com/test.json",function(data){
alert(data.name);
})
})
</script>`
3.1.2 跨域測試
分析:
1.瀏覽器地址: http://www.jt.com/test.html
2.ajax請求地址: http://manage.jt.com/test.json
結論:
如果請求地址(協議://域名:端口)不相同則導致請求調用失敗
3.2 瀏覽器-同源策略説明
説明: 瀏覽器規定 發起ajax時如果請求協議/域名/端口號如果3者有一個與當前的瀏覽器的地址不相同時,則違反了同源策略的規定.則瀏覽器不予解析返回值.
跨域問題: 違反同源策略的規定就是跨域請求.
3.3 跨域1-JSONP
3.3.1 JSONP跨域原理
- 利用javascrpit中的src屬性實現跨域請求.
- 自定義回調函數 function callback(xxxx);
- 將返回值結果進行特殊的格式封裝 callback(json);
- 由於利用src屬性進行調用 所以只能支持get請求類型.
封裝返回值:
`hello({"id":"1","name":"tom"})`
頁面js編輯
`<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>測試JSON跨域問題</title>
<script type="text/javascript">
/*JS是解釋執行的語言 */
/*定義回調函數 */
function hello(data){
alert(data.name);
}
</script>
<!--該json一直保存到瀏覽器中等待調用,但是沒有函數名稱無法調用 -->
<script type="text/javascript" src="http://manage.jt.com/test.json"></script>
<script type="text/javascript" src="http://manage.jt.com/js/jquery-easyui-1.4.1/jquery.min.js"></script>
</head>
<body>
<h1>JS跨域問題</h1>
</body>
</html>`
3.3.2 JSONP
JSONP(JSON with Padding)是JSON的一種“使用模式”,可用於解決主流瀏覽器的跨域數據訪問的問題。由於同源策略,一般來説位於 server1.example.com 的網頁無法與不是 server1.example.com的服務器溝通,而 HTML 的
3.3.3 JSONP優化
`<!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串
console.log(data);
}
});
})
</script>
</head>
<body>
<h1>JSON跨域請求測試</h1>
</body>
</html>`
3.3.4 編輯後端Controller
`package com.jt.web.controller;
import com.jt.pojo.ItemDesc;
import com.jt.util.ObjectMapperUtil;
import jdk.nashorn.internal.runtime.regexp.JoniRegExp;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class JSONPController {
/**
* 實現JSONP跨域請求
* url地址: http://manage.jt.com/web/testJSONP?callback=xxxxxx
* 參數: 暫時沒有可以不接
* 返回值: callback(JSON);
*/
@RequestMapping("/web/testJSONP")
public String testJSONP(String callback){
ItemDesc itemDesc = new ItemDesc();
itemDesc.setItemId(1000L).setItemDesc("JSONP測試!!!");
String json = ObjectMapperUtil.toJSON(itemDesc);
return callback+"("+json+")";
}
}`
3.3.5 控制枱輸出
3.3.6 JSONPObject説明
`@RequestMapping("/web/testJSONP")
public JSONPObject testJSONP(String callback){
ItemDesc itemDesc = new ItemDesc();
itemDesc.setItemId(1000L).setItemDesc("JSONP測試!!!");
return new JSONPObject(callback, itemDesc);
}`
3.4 cors跨域方式
3.4.1 cors調用原理
3.4.2 實現cors調用
`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;
@Configuration //標識我是一個配置類
public class CorsConfig implements WebMvcConfigurer {
//在後端 配置cors允許訪問的策略
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET","POST") //定義允許跨域的請求類型
.allowedOrigins("*") //任意網址都可以訪問
.allowCredentials(true) //是否允許攜帶cookie
.maxAge(1800); //設定請求長鏈接超時時間.
}
}`
3.4.3 cors調用響應頭解析
3.4.4 cors跨域測試
JSON數據格式
3.5 關於跨域的總結
1.jsonp
jsonp本質利用javaScript中的src屬性的get請求實現的跨域.
返回值必須經過特殊的格式封裝.
2.cors
添加在響應頭中信息.指定哪些服務器允許訪問.
4 實現用户數據校驗
4.1 業務需求
當用户在註冊時,如果輸入用户名,則應該向jt-sso單點登錄系統發起請求,校驗用户數據是否存在.
如果存在則提示用户.
4.2 業務接口文檔説明
4.3 前端JS分析
1.url分析
2.檢索JS代碼
- JS分析
`$.ajax({
url : "http://sso.jt.com/user/check/"+escape(pin)+"/1?r=" + Math.random(),
dataType : "jsonp",
success : function(data) {
checkpin = data.data?"1":"0";
if(data.status == 200){
if (!data.data) {
validateSettings.succeed.run(option);
namestate = true;
}else {
validateSettings.error.run(option, "該用户名已佔用!");
namestate = false;
}
}else{
validateSettings.error.run(option, "服務器正忙,請稍後!");
namestate = false;
}
}
});`
4.4 編輯JT-SSO UserController
`/**
* 業務説明: jt-web服務器獲取jt-sso數據 JSONP跨域請求
* url地址: http://sso.jt.com/user/check/{param}/{type}
* 參數: param: 需要校驗的數據 type:校驗的類型
* 返回值: SysResult對象
* 真實的返回值: callback(SysResult的JSON)
*/
@RequestMapping("/check/{param}/{type}")
public JSONPObject checkUser(@PathVariable String param,
@PathVariable Integer type,
String callback){
//true 表示數據存在 false 表示數據可以使用
boolean flag = userService.checkUser(param,type);
SysResult.success(flag);
return new JSONPObject(callback, SysResult.success(flag));
}`
4.5 編輯JT-SSO UserService
`/**
* 判斷依據: 根據用户名查詢 如果結果>0 用户已存在.
* @param param
* @param type
* @return
*/
@Override
public boolean checkUser(String param, Integer type) {
//1.需要將type類型轉化為 具體字段信息 1=username 2=phone 3=email
String column = columnMap.get(type);
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq(column, param);
Integer count = userMapper.selectCount(queryWrapper);
return count > 0 ? true :false;
}`