React前端和Spring boot后端的交互整合
前后端接口交互整合,可以通过spring boot的thymeleaf模板实现。
首先当然是引入相关依赖,一般在pom.xml
org.springframework.boot
spring-boot-starter-thymeleaf
如果有需要指定版本可以添加对应
UTF-8
UTF-8
1.8
3.0.9.RELEASE
然后在application.properties中进行具体的thymeleaf配置
#这个是配置模板路径的,默认就是templates
spring.thymeleaf.prefix=classpath:/static/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=LEGACYHTML5
#开发时关闭缓存
spring.thymeleaf.cache=false
模板的默认路径是templates,一般把index.html放在templates文件夹下即可,但是默认的资源路径又在static,也就是每次打包后的react前端代码都需要特地把index.html放到templates,所以我干脆把模板路径改为static,这样就可以直接全部代码放在一起,这样做的暂时没有发现什么缺点。
其次thymeleaf缓存会导致修改不能及时显示,所以在开发的时候可以关闭缓存。
另外由于thymeleaf对HTML5的解析非常严格,主要体现在标签必须封闭,所以希望降低解析严格程度,需要配置mode为LEGACYHTML5,并且添加nekohtml依赖
net.sourceforge.nekohtml
nekohtml
1.9.22
接下来进行controller配置,这里注意不能使用RestController,否则会直接返回字符串,而不是页面。
@Controller
public class HtmlController {
@GetMapping(value = "/index")
public String Indexhtml(){
return "index";
}
}
另外权限控制、拦截器配置是不可或缺的。我这里使用的是HandlerInterceptorAdapter,另外比较方便的选择,是使用安全框架,比如Security、Shiro。
@Configuration
public class WebSecurityConfig extends WebMvcConfigurationSupport {
/**
* 登录session key
*/
public final static String SESSION_USERNAME = "username";
public final static String SESSION_ROLE = "role";
@Bean
public SecurityInterceptor getSecurityInterceptor() {
return new SecurityInterceptor();
}
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
// 排除配置
addInterceptor.excludePathPatterns("/**/*.js");
addInterceptor.excludePathPatterns("/**/*.css");
addInterceptor.excludePathPatterns("/**/*.map");
addInterceptor.excludePathPatterns("/**/*.svg");
addInterceptor.excludePathPatterns("/**/*.jpg");
addInterceptor.excludePathPatterns("/manage/login");
addInterceptor.excludePathPatterns("/index");
addInterceptor.excludePathPatterns("/error");
// 拦截配置
addInterceptor.addPathPatterns("/**");
}
private class SecurityInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HttpSession session = request.getSession();
if (session.getAttribute(SESSION_USERNAME) != null && session.getAttribute(SESSION_ROLE) != null) {
return true;
}
// 跳转登录
System.out.println(request.getRequestURI());
String url = "/index";
response.sendRedirect(url);
return false;
}
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/static/");
super.addResourceHandlers(registry);
}
}
这是比较简略的拦截配置,主要需要注意的是排除配置,保证资源不被拦截,这个单双星号的写法让我和我的小伙伴捉摸了好一会。其次是注意静态资源路径映射重写。由于react打包过后,资源一般是生成static文件夹放置大部分静态资源,这样的多重static文件夹结构经过HandlerInterceptorAdapter的处理后,会导致资源路径映射不正确。不希望每次手动修改前端打包后的资源路径的话,后端如上面代码,配置addResourceHandlers,重写映射;
除了HandlerInterceptorAdapter,我这里再简单提供个人对于Security的配置,对应controller和依赖就不展示了
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private RestAuthenticationFailureHandler authenticationFailureHandler;
@Autowired
private RestAuthenticationSuccessHandler successHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();// 关闭csrf:Cross-site request forgery跨站请求伪造(便于测试post请求)
// http.authorizeRequests().anyRequest().authenticated();//所有页面访问都需要先登录
http.formLogin() // 登陆的设置
.failureHandler(authenticationFailureHandler) // failure handler登录失败返回结果
.loginPage("/index") //使用自定义登录页面
.loginProcessingUrl("/login")//登录请求的url default is /login with an HTTP post
.defaultSuccessUrl("/home.html")//登陆成功后默认的登录跳转页面
.permitAll(); // permit all authority登录页面允许所有人访问
http.authorizeRequests().antMatchers("/*.html").hasAnyAuthority("SUPERUSER","USER","NORMAL","CHECKMAN");//拦截指定url,放行指定角色
http.authorizeRequests().antMatchers("/Manage/*").hasAnyAuthority("SUPERUSER");//拦截指定url,放行指定角色
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);//将userdetailsserviceimple设置为验证用户信息的类
}
}
SpringBoot跨域配置
主要用于测试,发布的时候整个文件注释掉就好了
package com.example.newsroom.util;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Accept, Content-Type, Origin");
response.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨域
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
服务器图片资源访问配置
在拦截器配置中配置资源映射,即可通过类似 http://localhost:8080/images/xxx.jpg ,访问图片资源
package com.example.newsroom.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
* 登录配置
*
*/
@Configuration
public class WebSecurityConfig extends WebMvcConfigurationSupport {
/**
* 登录session key
*/
public final static String SESSION_USERNAME = "username";
public final static String SESSION_ROLE = "role";
public final static String SESSION_ID = "id";
@Bean
public SecurityInterceptor getSecurityInterceptor() {
return new SecurityInterceptor();
}
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
// 排除配置
addInterceptor.excludePathPatterns("/");
addInterceptor.excludePathPatterns("/error");
......
addInterceptor.excludePathPatterns("/logout");
addInterceptor.excludePathPatterns("/images/**");
addInterceptor.excludePathPatterns("/static/**");
// 拦截配置
addInterceptor.addPathPatterns("/**");
}
......
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/static/");
registry.addResourceHandler("/images/**").addResourceLocations("file:./file/公告图片/");
super.addResourceHandlers(registry);
}
}