最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解前后端分離之Java后端

 更新時(shí)間:2017年05月24日 10:46:57   作者:root__1024  
這篇文章主要介紹了詳解前后端分離之Java后端,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

前后端分離的思想由來(lái)已久,不妨嘗試一下,從上手開(kāi)始,先把代碼寫(xiě)出來(lái)再究細(xì)節(jié)。

代碼下載:https://github.com/jimolonely/AuthServer

前言

以前服務(wù)端為什么能識(shí)別用戶呢?對(duì),是session,每個(gè)session都存在服務(wù)端,瀏覽器每次請(qǐng)求都帶著sessionId(就是一個(gè)字符串),于是服務(wù)器根據(jù)這個(gè)sessionId就知道是哪個(gè)用戶了。
那么問(wèn)題來(lái)了,用戶很多時(shí),服務(wù)器壓力很大,如果采用分布式存儲(chǔ)session,又可能會(huì)出現(xiàn)不同步問(wèn)題,那么前后端分離就很好的解決了這個(gè)問(wèn)題。

前后端分離思想:
在用戶第一次登錄成功后,服務(wù)端返回一個(gè)token回來(lái),這個(gè)token是根據(jù)userId進(jìn)行加密的,密鑰只有服務(wù)器知道,然后瀏覽器每次請(qǐng)求都把這個(gè)token放在Header里請(qǐng)求,這樣服務(wù)器只需進(jìn)行簡(jiǎn)單的解密就知道是哪個(gè)用戶了。這樣服務(wù)器就能專(zhuān)心處理業(yè)務(wù),用戶多了就加機(jī)器。當(dāng)然,如果非要討論安全性,那又有說(shuō)不完的話題了。

下面通過(guò)SpringBoot框架搭建一個(gè)后臺(tái),進(jìn)行token構(gòu)建。

構(gòu)建springboot項(xiàng)目

我的目錄結(jié)構(gòu):(結(jié)果未按標(biāo)準(zhǔn)書(shū)寫(xiě),僅作說(shuō)明)

1

不管用什么IDE,最后我們只看pom.xml里的依賴(lài):

為了盡可能簡(jiǎn)單,就不連數(shù)據(jù)庫(kù)了,登陸時(shí)用固定的。

devtools:用于修改代碼后自動(dòng)重啟;

jjwt:加密這么麻煩的事情可以用現(xiàn)成的,查看https://github.com/jwtk/jjwt

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- JJWT -->
    <dependency>
      <groupId>io.jsonwebtoken</groupId>
      <artifactId>jjwt</artifactId>
      <version>0.6.0</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

登錄

這里的加密密鑰是:base64EncodedSecretKey

import java.util.Date;

import javax.servlet.ServletException;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

@RestController
@RequestMapping("/")
public class HomeController {

  @PostMapping("/login")
  public String login(@RequestParam("username") String name, @RequestParam("password") String pass)
      throws ServletException {
    String token = "";
    if (!"admin".equals(name)) {
      throw new ServletException("找不到該用戶");
    }
    if (!"1234".equals(pass)) {
      throw new ServletException("密碼錯(cuò)誤");
    }
    token = Jwts.builder().setSubject(name).claim("roles", "user").setIssuedAt(new Date())
        .signWith(SignatureAlgorithm.HS256, "base64EncodedSecretKey").compact();
    return token;
  }
}

 測(cè)試token

現(xiàn)在就可以測(cè)試生成的token了,我們采用postman:

2

過(guò)濾器

這肯定是必須的呀,當(dāng)然,也可以用AOP。

過(guò)濾要保護(hù)的url,同時(shí)在過(guò)濾器里進(jìn)行token驗(yàn)證

token驗(yàn)證:

public class JwtFilter extends GenericFilterBean {

  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String authHeader = request.getHeader("Authorization");
    if ("OPTIONS".equals(request.getMethod())) {
      response.setStatus(HttpServletResponse.SC_OK);
      chain.doFilter(req, res);
    } else {
      if (authHeader == null || !authHeader.startsWith("Bearer ")) {
        throw new ServletException("不合法的Authorization header");
      }
      // 取得token
      String token = authHeader.substring(7);
      try {
        Claims claims = Jwts.parser().setSigningKey("base64EncodedSecretKey").parseClaimsJws(token).getBody();
        request.setAttribute("claims", claims);
      } catch (Exception e) {
        throw new ServletException("Invalid Token");
      }
      chain.doFilter(req, res);
    }
  }

}

要保護(hù)的url:/user下的:

@SpringBootApplication
public class AuthServerApplication {

  @Bean
  public FilterRegistrationBean jwtFilter() {
    FilterRegistrationBean rbean = new FilterRegistrationBean();
    rbean.setFilter(new JwtFilter());
    rbean.addUrlPatterns("/user/*");// 過(guò)濾user下的鏈接
    return rbean;
  }

  public static void main(String[] args) {
    SpringApplication.run(AuthServerApplication.class, args);
  }
}

UserController

這個(gè)是必須經(jīng)過(guò)過(guò)濾才可以訪問(wèn)的:

@RestController
@RequestMapping("/user")
public class UserController {

  @GetMapping("/success")
  public String success() {
    return "恭喜您登錄成功";
  }

  @GetMapping("/getEmail")
  public String getEmail() {
    return "xxxx@qq.com";
  }
}

關(guān)鍵測(cè)試

假設(shè)我們的Authorization錯(cuò)了,肯定是通不過(guò)的:

3

當(dāng)輸入剛才服務(wù)器返回的正確token:

4

允許跨域請(qǐng)求

現(xiàn)在來(lái)說(shuō)前端和后端是兩個(gè)服務(wù)器了,所以需要允許跨域:

@Configuration
public class CorsConfig {

  @Bean
  public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("OPTION");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("POST");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("HEAD");
    config.addAllowedMethod("DELETE");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
  }

  @Bean
  public WebMvcConfigurer mvcConfigurer() {
    return new WebMvcConfigurerAdapter() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("GET", "PUT", "POST", "GET", "OPTIONS");
      }
    };
  }
}

下次是采用VueJS寫(xiě)的前端如何請(qǐng)求。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 詳解mybatis批量插入10萬(wàn)條數(shù)據(jù)的優(yōu)化過(guò)程

    詳解mybatis批量插入10萬(wàn)條數(shù)據(jù)的優(yōu)化過(guò)程

    這篇文章主要介紹了詳解mybatis批量插入10萬(wàn)條數(shù)據(jù)的優(yōu)化過(guò)程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • Spring?Security安全框架之記住我功能

    Spring?Security安全框架之記住我功能

    這篇文章主要介紹了Spring?Security安全框架之記住我,本次就來(lái)探究如何實(shí)現(xiàn)這種自動(dòng)登錄、記住我的功能,通過(guò)實(shí)例代碼圖文相結(jié)合給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-02-02
  • java實(shí)現(xiàn)附件預(yù)覽(openoffice+swftools+flexpaper)實(shí)例

    java實(shí)現(xiàn)附件預(yù)覽(openoffice+swftools+flexpaper)實(shí)例

    本篇文章主要介紹了java實(shí)現(xiàn)附件預(yù)覽(openoffice+swftools+flexpaper)實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。
    2016-10-10
  • SSM框架流程及原理分析

    SSM框架流程及原理分析

    本文給大家分享小編一些心得體會(huì),主要是學(xué)習(xí)SSM框架之后的收獲吧,重點(diǎn)給大家介紹SSM框架流程以及原理分析,通過(guò)圖文實(shí)例相結(jié)合給大家介紹的非常詳細(xì),需要的朋友參考下吧
    2021-06-06
  • Spring Boot 通過(guò)AOP和自定義注解實(shí)現(xiàn)權(quán)限控制的方法

    Spring Boot 通過(guò)AOP和自定義注解實(shí)現(xiàn)權(quán)限控制的方法

    這篇文章主要介紹了Spring Boot 通過(guò)AOP和自定義注解實(shí)現(xiàn)權(quán)限控制,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • RabbitMQ消息單獨(dú)與批量的TTL詳細(xì)介紹

    RabbitMQ消息單獨(dú)與批量的TTL詳細(xì)介紹

    這篇文章主要介紹了RabbitMQ消息單獨(dú)與批量的TTL,TTL全名是Time To Live存活時(shí)間,表示當(dāng)消息由生產(chǎn)端存入MQ當(dāng)中的存活時(shí)間,當(dāng)時(shí)間到達(dá)的時(shí)候還未被消息就會(huì)被自動(dòng)清除,感興趣的同學(xué)可以參考下文
    2023-05-05
  • Java中如何判斷中文字符串長(zhǎng)度

    Java中如何判斷中文字符串長(zhǎng)度

    這篇文章主要介紹了Java中如何判斷中文字符串長(zhǎng)度問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • Spring中的事務(wù)隔離級(jí)別的介紹

    Spring中的事務(wù)隔離級(jí)別的介紹

    今天小編就為大家分享一篇關(guān)于Spring中的事務(wù)隔離級(jí)別的介紹,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-01-01
  • Spring Boot利用@Async異步調(diào)用:ThreadPoolTaskScheduler線程池的優(yōu)雅關(guān)閉詳解

    Spring Boot利用@Async異步調(diào)用:ThreadPoolTaskScheduler線程池的優(yōu)雅關(guān)閉詳解

    這篇文章主要給大家介紹了關(guān)于Spring Boot利用@Async異步調(diào)用:ThreadPoolTaskScheduler線程池的優(yōu)雅關(guān)閉的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2018-05-05
  • 新手初學(xué)Java-Map

    新手初學(xué)Java-Map

    Map簡(jiǎn)介:將鍵映射到值的對(duì)象。一個(gè)映射不能包含重復(fù)的鍵;每個(gè)鍵最多只能映射到一個(gè)值。此接口取代 Dictionary 類(lèi),后者完全是一個(gè)抽象類(lèi),而不是一個(gè)接口
    2021-07-07

最新評(píng)論

烟台市| 桓仁| 青海省| 西乌珠穆沁旗| 长海县| 定州市| 华阴市| 师宗县| 黄山市| 丹凤县| 民县| 澎湖县| 民权县| 孟村| 额济纳旗| 百色市| 佛坪县| 安远县| 聂荣县| 高邮市| 绥阳县| 晋宁县| 囊谦县| 曲阳县| 土默特左旗| 泌阳县| 大关县| 太白县| 华蓥市| 邻水| 保康县| 张家界市| 察雅县| 射洪县| 专栏| 大荔县| 临夏县| 健康| 商南县| 阳朔县| 南昌县|