溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java項目如何實現(xiàn)前后端分離

發(fā)布時間:2020-11-20 15:55:52 來源:億速云 閱讀:1090 作者:Leah 欄目:編程語言

今天就跟大家聊聊有關(guān)Java項目如何實現(xiàn)前后端分離,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

構(gòu)建springboot項目

我的目錄結(jié)構(gòu):(結(jié)果未按標(biāo)準書寫,僅作說明)

Java項目如何實現(xiàn)前后端分離

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

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

devtools:用于修改代碼后自動重啟;

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("密碼錯誤");
    }
    token = Jwts.builder().setSubject(name).claim("roles", "user").setIssuedAt(new Date())
        .signWith(SignatureAlgorithm.HS256, "base64EncodedSecretKey").compact();
    return token;
  }
}

 測試token

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

Java項目如何實現(xiàn)前后端分離

過濾器

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

過濾要保護的url,同時在過濾器里進行token驗證

token驗證:

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);
    }
  }

}

要保護的url:/user下的:

@SpringBootApplication
public class AuthServerApplication {

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

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

UserController

這個是必須經(jīng)過過濾才可以訪問的:

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

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

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

關(guān)鍵測試

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

Java項目如何實現(xiàn)前后端分離

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

Java項目如何實現(xiàn)前后端分離

允許跨域請求

現(xiàn)在來說前端和后端是兩個服務(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");
      }
    };
  }
}

看完上述內(nèi)容,你們對Java項目如何實現(xiàn)前后端分離有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI