There are two main solutions for combining springboot and vue on the network:
1. [Not recommended] Use script tags directly to introduce vue and some commonly used components in html. This method is the same as in the previous traditional development, but you can use vue's two-way data binding very happily. This method is only suitable for ordinary full-stack development.
2. [Recommended] Use vue official scaffolding to create a separate front-end engineering project, so as to achieve complete independent development and deployment from the back-end, and deploy a pure restful service separately from the back-end, while the front-end directly uses nginx for deployment. This is called a complete front-end and back-end separation architecture development model, but there are many problems with API permissions that need to be solved in the separation, including the deployment of vue router routing that requires rewrite rules to be configured in nginx. This kind of architecture that is completely separated from the front and back ends is also currently adopted by Internet companies. Backend servers no longer need to deal with static resources, and can also reduce some pressure on the backend server.
1. Why do front-end and back-end separation and merge
In traditional industries, many are dominated by project ideas, rather than products. A project will be sold to many customers and deployed to the customer's local computer room. In some traditional industries, the technology of deploying and implementing personnel cannot be compared with the operation and maintenance teams of Internet companies, and due to various uncertain environments, it cannot be automatically constructed, containerized deployment, etc. Therefore, in this case, try to minimize the service software requirements during deployment and try to produce as few packages as possible. In response to this situation, the front-end independent development is implemented in development. The entire development method is the same as the second method mentioned above. However, when the back-end springboot is packaged and released, the front-end construction output is entered together. In the end, just deploy the springboot project, no need to install the nginx server.
2. Key operations of integration of springboot and vue
In fact, in this article, the front-end separation of front-end development, after the front-end development is completed, the files in the static built in the build are copied to the static of the resource of springboot, and the index.html is directly copied to the static of the resource of springboot. Here is an example diagram:
vue front-end project
springboot project:
The above is the easiest way to merge, but if it is an engineering-level project development, manual merge is not recommended, and the front-end code is not recommended to be built and submitted to the springboot resource. The good way should be to keep the front-end and back-end completely independent development code, and the project code does not affect each other. With the help of construction tools like Jenkins, the front-end construction is triggered and the automation script is written when building springboot, copy the resources built by the front-end webpack to springboot and then package it in jar. Finally, I get a springboot project that completely contains the front-end and back-end.
3. Core issues of integration
After the above integration, two relatively big problems will arise:
1. The static resources cannot be accessed normally.
2. The path of the vue router route cannot be resolved normally.
To solve the first problem, we must re-specify springboot's static resource processing prefix, code:
@Configurationpublic class SpringWebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); super.addResourceHandlers(registry); }}The way to solve the second problem is to rewrite the path of the vue route and leave it to the router for processing, rather than springboot to handle it itself. When rewrite, you can consider adding the route paths uniformly, and then write filtering and intercepting specific suffixes in springboot to do the route processing of request forwarding and handing it to vue. like:
const router = new VueRouter({ mode: 'history', base: __dirname, routes: [ { path: '/ui/first.vhtml', component: First }, { path: '/ui/second.vhtml', component: second component } ]})The backend interception to the ones with vhtml are left to the router for processing. This method is completely feasible to package after writing filters to intercept the backend, but there will be problems with the direct access to the path with suffixes developed by the front end.
Another way is to add a prefix such as /ui to the front-end routing path. At this time, the back-end write filter matches the prefix, which will not affect the routing analysis problem of the front-end development separately. The filter reference is as follows:
/** * be used to rewrite vue router * * @author yu on 2017-11-22 19:47:23. */public class RewriteFilter implements Filter { /** * Destination address that needs to be rewrite*/ public static final String REWRITE_TO = "rewriteUrl"; /** * Intercepted url and url wildcards are separated by English semicolons*/ public static final String REWRITE_PATTERNS = "urlPatterns"; private Set<String> urlPatterns = null;//Configure url wildcard private String rewriteTo = null; @Override public void init(FilterConfig cfg) throws ServletException { //Initialize intercept configuration rewriteTo = cfg.getInitParameter(REWRITE_TO); String exceptUrlString = cfg.getInitParameter(REWRITE_PATTERNS); if (StringUtil.isNotEmpty(exceptUrlString)) { urlPatterns = Collections.unmodifiableSet( new HashSet<>(Arrays.asList(exceptUrlString.split(";", 0)))); } else { urlPatterns = Collections.emptySet(); } } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; String servletPath = request.getServletPath(); String context = request.getContextPath(); //Matched path rewrite if (isMatches(urlPatterns, servletPath)) { req.getRequestDispatcher(context+"/"+rewriteTo).forward(req, resp); }else{ chain.doFilter(req, resp); } } @Override public void destroy() { } /** * Match returns true, mismatch returns false * @param patterns Regular expression or wildcard * @param url Requested url * @return */ private boolean isMatches(Set<String> patterns, String url) { if(null == patterns){ return false; } for (String str : patterns) { if (str.endsWith("/*")) { String name = str.substring(0, str.length() - 2); if (url.contains(name)) { return true; } } else { Pattern pattern = Pattern.compile(str); if (pattern.matcher(url).matches()) { return true; } } return false; }}Filter registration:
@SpringBootApplicationpublic class SpringBootMainApplication { public static void main(String[] args) { SpringApplication.run(SpringBootMainApplication.class, args); } @Bean public EmbeddedServletContainerCustomizer containerCustomizer() { return (container -> { ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/errors/401.html"); ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/errors/404.html"); ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/errors/500.html"); container.addErrorPages(error401Page, error404Page, error500Page); }); } @Bean public FilterRegistrationBean testFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new RewriteFilter());//Register rewrite filter registration.addUrlPatterns("/*"); registration.addInitParameter(RewriteFilter.REWRITE_TO,"/index.html"); registration.addInitParameter(RewriteFilter.REWRITE_PATTERNS, "/ui/*"); registration.setName("rewriteFilter"); registration.setOrder(1); return registration; }}At this time, springboot can hand over the front-end routing resources to the route for processing. At this point, the entire front-end and back-end separation and merge solution is completed. This method can also be easily separated from the front and back ends when conditions are available in the later stage.
Summarize
The above is the front-end separation and merge plan of spring boot+vue introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!