跪拜 Guibai
← Back to the summary

Front-end to Java full-stack in 2 days: AI-assisted Demo delivery with all the pitfalls

The boss drops one sentence: "Next week I want to see something that runs." You're a front-end developer, you've only heard of Java, never touched Spring source code. What do you do?

My colleague went through this transition twice, completely. Let me state the conclusion first: Don't finish learning Java before you start building. Use AI to run a minimal viable loop first, then fill in the edges. This article explains the full process—tech selection, code, pitfalls—all from hands-on experience, suitable for front-end developers wanting to switch to full-stack. Bookmark it for reference.

1. First, think clearly: you're migrating your mental model, not learning syntax from zero

The biggest misconception in front-end-to-backend transition is thinking you "don't know how to write Java." Actually, you already have HTTP, JSON, componentization, state management, and build tools. What you truly lack are only two things: Java ecosystem syntax and its layering conventions.

So the strategy is clear:

Map your existing front-end mental model onto the Spring ecosystem, let AI do the translating, and you guard the boundaries.

This mapping table was the most effective lever in my colleague's transition:

Front-end concept you know Java equivalent One-line translation
app.js entry Application.java Startup file
Express / Koa routes @RestController Where requests are handled
Middleware Filter / Interceptor / AOP Request pipeline
npm install pom.xml + Maven Install dependencies
node_modules ~/.m2 local repository Dependency cache
package.json scripts mvn spring-boot:run Startup command
TS interface record DTO + Bean Validation Type constraints
Vue components Controller Receive requests, return responses
Composable / Store action Service Business logic
API request layer Repository / Mapper Fetch data
axios interceptors HandlerInterceptor / Filter Both are "aspects"
provide / inject Constructor injection Java's dependency injection
Props validation / form rules @NotBlank @Size Backend as single source of truth
Vite proxy Nginx reverse proxy same-origin Avoid CORS during integration

In one sentence: You're not learning backend from scratch; you're learning "Java's Express + ORM".

But three things can't be mapped and must be relearned:

These three determine whether your Demo will crash on real business, and the pitfall section will revisit them.

2. Tech selection: the only criterion is "minimal boilerplate"

The biggest pitfall in front-end-to-backend transition is "spending half an hour on environment setup and installing a bunch of dependencies," so all selections focus on out-of-the-box, zero extra installation:

Layer Choice Core reason
Backend framework Spring Boot 3.2.x + Java 17 LTS Most mature scaffold in the Java ecosystem, high-quality AI generation, searchable when problems arise
Persistence layer Spring Data JPA or MyBatis-Plus Both can work with zero handwritten SQL, detailed comparison below
Database H2 in-memory No MySQL installation needed, embedded startup, built-in /h2-console visual console
API documentation springdoc-openapi Automatically generates /v3/api-docs, can also feed types to front-end
Front-end Vue3 + Vite + TS + Pinia + Element Plus All familiar territory, don't spend a minute on UI
Contract OpenAPI → openapi-typescript Backend schema generates TS types directly, eliminates type drift
Auth Spring Security + JWT Standard for front-end/back-end separation (can defer in Demo phase)
AI assistance Cursor / Copilot / 通义灵码 Full-cycle code generation, debugging, interface type generation

Two points need separate expansion.

① Boot 3's package name is jakarta.*, not javax.*. This is the first pitfall beginners hit: old tutorials online all use javax.validation, which won't compile in Boot 3 projects. I'll hard-code this into the prompt template below.

② How to choose between JPA and MyBatis-Plus? First look at the comparison:

Dimension Spring Data JPA MyBatis-Plus
CRUD Inherit JpaRepository, free Inherit BaseMapper, free
Query style Method name generates SQL (findByNameContaining) LambdaQueryWrapper condition builder
SQL control Weak; Hibernate writes it Strong; every SQL is visible
Pagination Built-in Pageable, out-of-box Requires manually registering pagination plugin
Front-end friendliness Higher; zero SQL throughout Medium; closer to domestic business
Use case Demo, simple CRUD Domestic business projects, complex queries

My advice: Use JPA for Demo to run fast, switch to MyBatis-Plus when closer to real projects. Code for both is given below.

Environment checklist:

Tool Version suggestion Notes
JDK 17 LTS Officially specified by Spring Boot 3, most stable ecosystem
Maven 3.8+ The npm of the Java world
Node.js 18+ Vite requirement
IDE IntelliJ IDEA Community Free, excellent Spring Boot support

⚠️ Front-end developers first configuring the Java environment: 90% of pitfalls are in JAVA_HOME. Point it to the JDK root directory, then add %JAVA_HOME%\bin to Path. Don't just cram the full path of java.exe in.

If Maven dependencies download slowly, switch to Aliyun mirror; for version conflicts, use mvn dependency:tree to print the dependency tree and dump it to AI for analysis—ten times faster than struggling yourself.

If you're also on the transition path, you can follow me; I'll keep updating the front-end-to-full-stack pitfall series later.

3. 30-minute roadmap: run the minimal viable loop first

Many people's first reaction is "learn first, then do," but the boss won't wait. My pace is like this:

image.png

Key points:

My actual time allocation feeling: backend 1 day to get login + full CRUD + pagination working, front-end half day to wrap Element Plus template, final half day integration—a 1.5~2 day MVP. If you only need the minimal CRUD loop (0~5 min Initializr create project, 5~15 min write three-layer code, 15~25 min write page, 25~30 min integration), really 30 minutes.

Overall architecture looks like this:

image.png

Full lifecycle of a "create" request:

image.png

Demo acceptance criteria only three:

  1. Page can complete a full create → query → update loop;
  2. Token can be automatically carried through interceptor, backend can validate;
  3. After git clone on another machine, one command to start front-end, one command to start back-end, no dependence on local global environment.

Achieve these three and you've crossed the line from "front-end looking at backend" to "front-end writing backend."

Scaffolding also has tricks: don't manually configure Maven. Directly use Spring Initializr (start.spring.io), check Web, JPA, Validation, H2, Lombok to generate skeleton; or use full-stack scaffolds like yc-studio-cli: npm install -g yc-studio-cli then one command yc-studio-cli init my-demo -t fullstack generates both front-end and back-end directories, with login auth, JWT, API docs pre-configured. Your goal isn't to understand every line, but to get it running first—the moment you see the page fetching backend data, confidence outweighs everything.

4. Back-end triple: unified response, global exception, layering

Skeleton ready, now enter the core of the backend. First look at the directory structure (front-end/back-end separation, each runs independently, avoids file mixing):

fullstack-demo/
├─ backend/
│  ├─ controller/UserController.java
│  ├─ service/UserService.java
│  ├─ repository/UserRepository.java
│  ├─ entity/User.java
│  ├─ dto/UserCreateReq.java
│  ├─ vo/UserVO.java
│  ├─ config/MybatisPlusConfig.java
│  └─ common/R.java
└─ frontend/
   ├─ vite.config.ts
   ├─ src/api/http.ts
   ├─ src/api/user.ts
   └─ src/views/UserList.vue

4.1 Dependencies and configuration

pom.xml core dependencies (persistence layer choose one of two, comments clarify):

<properties>
    <java.version>17</java.version>
</properties>

<dependencies>
    <!-- Minimal triple: Web + Validation + JPA -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <!-- H2 in-memory: Demo no database installation, runtime only -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>

    <!-- When choosing MyBatis-Plus, replace JPA: Boot3 must use spring-boot3-specific starter -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
        <version>3.5.5</version>
    </dependency>

    <!-- Auth-related; can skip in Demo phase -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <!-- jjwt: 0.12.x API changed significantly, must lock version -->
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt-api</artifactId>
        <version>0.12.5</version>
    </dependency>
</dependencies>

application.yml:

server:
  port: 8080

spring:
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:demo_db   # In-memory mode, clears on restart, switch to MySQL in production
    username: sa
    password:
  h2:
    console:
      enabled: true            # Built-in database console, visit /h2-console for visual data
      path: /h2-console
  jpa:
    hibernate:
      ddl-auto: update         # Auto-create tables on startup, auto-sync entity changes
    show-sql: true             # Print SQL, integration debugging tool
    open-in-view: false        # Turn off view-layer lazy loading, avoid hidden N+1 and connection occupation

💡 open-in-view: false deserves a separate mention: Spring Boot defaults to on, view layer will trigger lazy loading, hiding N+1 queries and database connection occupation issues. Mentioning this in an interview at least shows you're not a pure AI black-box player.

4.2 Unified response body: key to avoiding integration arguments

Front-end's biggest fear is each interface returning a different structure, making interceptors ugly. So R<T> is the highest-priority common module:

// Java 17 record: immutable, zero boilerplate, built-in traceId for front-end/back-end log correlation
public record R<T>(int code, String msg, T data, String traceId) {

    public static <T> R<T> ok(T data) {
        return new R<>(200, "ok", data, MDC.get("traceId"));
    }

    public static <T> R<T> fail(int code, String msg) {
        return new R<>(code, msg, null, MDC.get("traceId"));
    }
}

💡 The highlight is traceId: include it in front-end error toasts, and when debugging you can directly grab logs by this ID—no more "which request were you talking about?"

If you don't like records, Lombok @Data version works too: code, message, data fields with two static success/fail methods. Same idea entirely.

4.3 Global exception handling: say goodbye to try-catch hell

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // Business exception: custom BusinessException carries code and msg
    @ExceptionHandler(BusinessException.class)
    public R<Void> handleBiz(BusinessException e) {
        log.warn("业务异常: {}", e.getMessage());
        return R.fail(e.getCode(), e.getMessage());
    }

    // Parameter validation exception: aggregate field errors, front-end can render directly, don't throw a pile of 500
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Map<String, String>> handleValid(MethodArgumentNotValidException e) {
        Map<String, String> errors = e.getBindingResult().getFieldErrors().stream()
                .collect(Collectors.toMap(
                        FieldError::getField,
                        f -> f.getDefaultMessage() == null ? "非法输入" : f.getDefaultMessage(),
                        (a, b) -> a));
        return new R<>(400, "参数不合法", errors, MDC.get("traceId"));
    }

    // Fallback: log for debugging, but don't expose stack trace to outside
    @ExceptionHandler(Exception.class)
    public R<Void> handle(Exception e) {
        log.error("未处理异常", e);
        return R.fail(500, "服务开小差了");
    }
}

All three details come from real pitfalls: validation errors should be aggregated into a format front-end can render; unknown exceptions should be logged with log.error but not expose stack trace externally; business exceptions go through custom BusinessException, with unified exit.

4.4 DTO / VO: Entity should never go out directly

// Input DTO: record + Bean Validation, validation rules written here
public record UserCreateReq(
        @NotBlank(message = "姓名不能为空") @Size(max = 32) String name,
        @Email(message = "邮箱格式不对") String email) {}

// Output VO: only expose fields front-end needs
public record UserVO(Long id, String name, String email, LocalDateTime createdAt) {}

// Pagination wrapper
public record PageResult<T>(List<T> records, long total) {}

Why not return Entity directly? Three reasons: field coupling, circular reference risk, exposing internal structure—password, salt are all lying in Entity.

Also a principle: backend validation is the single source of truth. Front-end validation only serves as UX-level hints; otherwise front-end passes, backend returns 400, and both sides blame each other.

4.5 Service: transactions only on this layer

@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;

    @Transactional   // Transactions only on Service public methods, not Controller
    public UserVO create(UserCreateReq req) {
        User user = new User();
        BeanUtils.copyProperties(req, user);   // Property copy, such boilerplate code can be given to AI
        return toVO(userRepository.save(user));
    }

    @Transactional(readOnly = true)   // Read-only transaction for queries, leaves room for optimization
    public Page<UserVO> page(Pageable pageable) {
        return userRepository.findAll(pageable).map(this::toVO);
    }

    @Transactional
    public UserVO update(Long id, UserCreateReq req) {
        // Resource not found, directly throw 404, Spring auto-converts to HTTP status
        User user = userRepository.findById(id)
                .orElseThrow(() -> new ResponseStatusException(
                        HttpStatus.NOT_FOUND, "用户不存在"));
        user.setName(req.name());
        user.setEmail(req.email());
        return toVO(userRepository.save(user));
    }

    @Transactional
    public void delete(Long id) {
        userRepository.deleteById(id);
    }

    // Entity doesn't leave Service layer, transform to VO before returning
    private UserVO toVO(User u) {
        return new UserVO(u.getId(), u.getName(), u.getEmail(), u.getCreatedAt());
    }
}

⚠️ High-frequency pitfall: @Transactional relies on proxy; calling a method from within the same class bypasses the proxy, and the transaction silently fails. Especially with multi-table operations; split methods into two Services if needed.

4.6 Controller: only does "translation," no business logic

@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor   // Lombok generates constructor injection, bye to @Autowired field injection
public class UserController {

    private final UserService userService;

    @GetMapping
    public R<Page<UserVO>> list(
            @PageableDefault(size = 10, sort = "id", direction = Sort.Direction.DESC)
            Pageable pageable) {
        return R.ok(userService.page(pageable));
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)   // Create success returns 201, more RESTful
    public R<UserVO> create(@Valid @RequestBody UserCreateReq req) {
        return R.ok(userService.create(req));
    }

    @DeleteMapping("/{id}")
    public R<Void> delete(@PathVariable Long id) {
        userService.delete(id);
        return R.ok(null);
    }
}

Translating for front-end developers: constructor injection is type-checked inject, classes annotated with @Service are auto-scanned, auto-created, and auto-injected wherever needed by Spring on startup—no manual new. @PageableDefault provides default pagination and sorting; if you want a single object to hold all query parameters, use @ModelAttribute plus a record UserQuery(long current, long size, String name).

With layers explained, next is the question many struggle with: JPA or MyBatis-Plus?

5. Data layer advanced: both schools' code

JPA school: zero SQL, most front-end friendly

Entity class:

@Data
@Entity
@Table(name = "t_user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;
    private LocalDateTime createdAt;
}

Data access layer, one interface solves it:

// Inherit JpaRepository, get full CRUD automatically, zero implementation code
public interface UserRepository extends JpaRepository<User, Long> {
    // Method name is query semantics: auto-generate where name like %?%
    List<User> findByNameContaining(String name);
}

JPA auto-creates tables, auto-generates CRUD, and method names like findByNameContaining translate directly to SQL—never touching the database, very friendly for front-end developers who haven't written SQL.

MyBatis-Plus school: mainstream choice for domestic business

Entities have richer annotations, optimistic lock and logical delete are all annotation-based:

@Data
@TableName("sys_user")
public class SysUser {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String username;
    private String password;     // Sensitive field, never enters VO
    @Version
    private Integer version;     // Optimistic lock version number
    @TableLogic
    private Integer deleted;     // Logical delete marker
    private LocalDateTime createTime;
}

Pagination plugin must be manually registered—this is a common beginner disaster. If not registered, selectPage returns total always 0, and SQL log has no LIMIT:

@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        var interceptor = new MybatisPlusInterceptor();
        // Note order: pagination first, optimistic lock after
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

LambdaQueryWrapper is MP's signature feature: field names are checked at compile time, refactoring won't break, and conditions can be dynamically assembled:

// If kw is empty, no like condition is added automatically; one line handles "optional search"
public List<UserVO> search(String kw) {
    return userMapper.selectList(Wrappers.<User>lambdaQuery()
                    .like(StringUtils.hasText(kw), User::getName, kw)
                    .orderByDesc(User::getId))
            .stream().map(this::toVO).toList();
}

Pagination interface looks like this:

@GetMapping
public R<IPage<Task>> page(@RequestParam(defaultValue = "1") long current,
                           @RequestParam(defaultValue = "10") long size,
                           @RequestParam(required = false) String keyword) {
    var wrapper = new LambdaQueryWrapper<Task>()
            .like(keyword != null, Task::getTitle, keyword)
            .orderByDesc(Task::getCreateTime);
    return R.ok(taskService.page(new Page<>(current, size), wrapper));
}

⚠️ Boot 3 users: MyBatis-Plus requires the dedicated mybatis-plus-spring-boot3-starter. Using the old starter will fail at startup with ClassNotFound: javax.servlet.* due to jakarta package names.

Backend done, now our home turf — front-end.

6. Front-end home turf: proxy, interceptors, type contracts

6.1 Vite proxy kills cross-origin

Cross-origin is the first blocker in front-end/back-end separation. First clarify the principle:

Cross-origin is a browser same-origin policy restriction; servers have no such concept. So the proxy idea is to let the Vite dev server "pretend same-origin" and forward for you, bypassing browser checks from the root.

// vite.config.ts
export default defineConfig({
  plugins: [vue()],
  server: {
    port: 5173,
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true
        // If backend interface doesn't have /api prefix, add this line to remove prefix
        // rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
})

image.png

Scheme comparison by scenario, bookmark recommended:

Scenario Solution Notes
Dev integration Vite server.proxy Same-origin simplest, avoids Cookie/Credentials cross-origin traps
Demo quick demo Controller @CrossOrigin One-line annotation, but don't scatter it on every Controller
Production deployment Nginx reverse proxy same-origin Unified front-end/back-end entry, eliminates CORS entirely
Production must cross-origin Backend global CORS config Whitelist origins, never use *

Production-ready global CORS config:

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(List.of("http://localhost:5173"));  // Whitelist, don't write *
    config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", config);
    return source;
}

⚠️ Pitfall I've stepped on: Vite's proxy config is loaded at startup, no hot reload. After changing vite.config.ts, you must restart the dev server—this cost me at least half an hour.

6.2 Axios encapsulation: interceptors do all the dirty work

// src/api/http.ts
import axios from 'axios'
import { ElMessage } from 'element-plus'

const request = axios.create({
  baseURL: '/api',      // Key: relative path, let Vite proxy handle, don't hardcode absolute address
  timeout: 10000
})

// Request interceptor: automatically add token
request.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
})

// Response interceptor: strip R<T> wrapper, components get clean data
request.interceptors.response.use(
  res => {
    const r = res.data
    if (r.code !== 200) {
      ElMessage.error(`${r.msg}(traceId: ${r.traceId})`)  // Use traceId when debugging
      return Promise.reject(r)
    }
    return r.data
  },
  err => {
    if (err.response?.status === 401) {
      // Token expired: clear login state, redirect to login page
      useUserStore().logout()
      router.push('/login')
    } else {
      ElMessage.error('网络异常')
    }
    return Promise.reject(err)
  }
)

export default request

Several points worth noting: baseURL uses relative path so proxy handles it (of course you can use import.meta.env.VITE_API_URL to point directly at backend, but proxy is more recommended); request interceptor adds token; response interceptor unwraps R<T> and handles 401, business components write one line none.

Demo without axios, native fetch wrapper suffices:

async function request<T>(url: string, options?: RequestInit): Promise<T> {
  const res = await fetch(url, {
    headers: { 'Content-Type': 'application/json' },
    ...options
  })
  if (!res.ok) {
    const body = await res.json().catch(() => null)
    throw new Error(body?.message ?? `请求失败:${res.status}`)
  }
  return res.json() as Promise<T>
}

6.3 Type contracts: the "dimension reduction strike" for front-end transition

This is the most worth-learning trick in the whole article: don't handwrite front-end interface types, auto-generate from backend OpenAPI.

Add springdoc-openapi dependency, run it to get /v3/api-docs, then one command:

npx openapi-typescript http://localhost:8080/v3/api-docs -o src/api/schema.d.ts
// src/api/user.ts —— types zero handwritten
import type { components } from './schema'
type UserVO = components['schemas']['UserVO']
type UserCreateReq = components['schemas']['UserCreateReq']

export const userApi = {
  list: (params?: { page: number; size: number }) =>
    request.get<UserVO[]>('/users', { params }),
  add:  (dto: UserCreateReq) => request.post<UserVO>('/users', dto)
}

💡 Highlight: backend changes email to mail, front-end throws at compile time, not silently white-screening at runtime. This uproots front-end/back-end type drift, the ultimate solution for "integration without arguments."

6.4 Page: converge request states into composable

// useUsers.ts: request states converge into composable, page only template

export function useUsers() {
  const rows = ref<UserVO[]>([])
  const loading = ref(false)
  const kw = ref('')

  const reload = async () => {
    loading.value = true
    try {
      rows.value = await userApi.list({ page: 1, size: 10 })
    } finally {
      loading.value = false   // Converge loading regardless of result
    }
  }

  const add = async (dto: UserCreateReq) => {
    await userApi.add(dto)
    await reload()
  }

  onMounted(reload)
  watchDebounced(kw, reload, { debounce: 300 })   // Search debounce
  return { rows, loading, kw, add, reload }
}

Page template (Element Plus table, pagination, delete confirm—all in one):

<template>
  <div style="padding: 24px; max-width: 860px; margin: 0 auto">
    <el-input v-model="kw" placeholder="搜索姓名..." clearable style="width: 240px" />

    <el-table :data="rows" v-loading="loading" stripe style="margin-top: 12px">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button size="small" type="danger" @click="handleDelete(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="page.current"
      :page-size="page.size"
      :total="total"
      @current-change="reload"
    />
  </div>
</template>

<script setup lang="ts">
const handleDelete = async (id: number) => {
  await ElMessageBox.confirm('确定删除?', '警告')
  await userApi.remove(id)
  reload()
}
</script>

One more UX highlight—optimistic update:

async function toggle(task: Task) {
  task.done = !task.done          // Update UI first, better experience
  try {
    await toggleTask(task.id)
  } catch {
    task.done = !task.done        // Roll back on failure
    await loadTasks()
  }
}

Update UI first, send request silently, roll back on failure—far better than waiting with a spinner. Such interaction details are the natural advantage of front-end to full-stack transition.

7. Auth hard nut: JWT + Spring Security pitfalls real record

Demo phase can keep it simple: use HandlerInterceptor to validate JWT, switch to full Spring Security after it works. If you go straight to Security, these pitfalls I've stepped on for you.

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthFilter;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(AbstractHttpConfigurer::disable)   // JWT is stateless, no CSRF needed
            .authorizeHttpRequests(auth -> auth
                // Allow OPTIONS preflight requests—the #1 culprit for CORS 401!
                .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .requestMatchers("/api/auth/**").permitAll()
                .anyRequest().authenticated()
            )
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

JWT filter only does three things, boundaries locked, never stuff business logic in:

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtService jwtService;
    private final UserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        final String authHeader = request.getHeader("Authorization");
        // ① No Bearer token: pass through, let Security handle
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }
        // ② Verify signature + extract username
        final String jwt = authHeader.substring(7);
        final String username = jwtService.extractUsername(jwt);
        // ③ Put into SecurityContext
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            var userDetails = userService.loadUserByUsername(username);
            var authToken = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authToken);
        }
        filterChain.doFilter(request, response);
    }
}

Pitfall checklist, every item is blood and tears:

8. AI-assisted programming: let AI be the worker, you be the architect

First my positioning, which is also what interviewers love to hear:

AI is a "boilerplate code translator," not an "architect." I define the five things—contract, layering, validation, exceptions, transactions—and leave all the repetitive CRUD to it.

Look at actual efficiency numbers:

Task Traditional time AI-assisted Improvement
CRUD interface development 4h 0.5h 8x
Front-end component development 3h 1h 3x
Automated test writing 2h 0.25h 8x
Database optimization 6h 1.5h 4x

8.1 Prompt template: give contract, give constraints, don't give free rein

My universal template, copy directly:

You are a senior Java backend engineer, proficient in Spring Boot 3.2 / Java 17 / MyBatis-Plus.
Generate code according to this contract:
POST /api/users, input {name, email}, output R<UserVO>.

Constraints:
1. Use jakarta.validation.*, not javax.*;
2. DTO uses record, don't expose Entity directly;
3. Strict Controller → Service → Mapper three layers, business logic only in Service;
4. Unified return R<T>, don't invent your own Result;
5. Queries use LambdaQueryWrapper, no handwritten SQL concatenation;
6. Transactions only on Service layer;
7. Don't introduce dependencies I didn't mention.

First give file list, then code.

Newbie questions vs expert questions, difference visible at a glance:

Newbie question Expert question
"Help me write a Java interface" "You're Spring Boot 3.2 expert, use JPA + Lombok to write user CRUD: unified response body R, DTO validation + global exception, give application.yml, code can be directly copied and run"
Gets a pile of code that may or may not run Gets complete three-layer architecture with config and constraints

I habitually write project background, tech stack, and layering conventions into Cursor's .cursor/rules or the first message, then request modules separately. For JWT module, I write constraints to five rules: use SecurityFilterChain lambda DSL, filter extends OncePerRequestFilter doing only three things, algorithm explicit HS256, /api/auth/** permitted and session STATELESS, UserDetailsService goes through UserService. Front-end pages too: directly give the component list—which fields el-table shows, el-pagination connects to backend pagination structure, el-dialog for create/edit form—AI assembles quickly and accurately.

8.2 AI three moves: generate, correct, teach

  1. Generate: give sufficient context (tech stack version + data structure + constraints), generate complete three-layer architecture in one shot. Better play: give a field definition, let AI generate both Java entity and front-end TS type simultaneously, the two ends align naturally, field alignment problems disappear;
  2. Correct: Java exception stack traces are very complete; copy the whole thing to AI, 90% of problems solved within 10 seconds. When reading yourself, remember the structured approach: look for Caused By first—that's the root cause;
  3. Teach: let AI explain concepts with "front-end analogies"—"Use Express middleware analogy to explain Spring interceptor"—you get it instantly. For legacy code without docs, paste the function to AI, have it generate flowcharts, input/output examples, and risk points. Practically, understanding a permission mechanism went from days to hours.

8.3 Division of labor: this for AI, this for you

Give to AI You check yourself
CRUD boilerplate, DTO/VO, table templates Interface contracts, error codes, layering conventions
Unit test samples, mock data Transaction boundaries, SQL security, authorization checks
Explain errors, give fix diffs Database indexes and constraints
README, interface docs Architecture trade-offs (whether to cache, whether to split services)
Generate TS types Security-related like encryption, token strategy

Why don't you let AI decide indexes and security? AI doesn't know your real business traffic; a wrong index strategy dies at launch. I once deployed AI-generated encryption code and it had a security vulnerability—blood lesson; don't skip the review step.

When reviewing AI code, I always check four things: Is SQL precompiled? Is transaction added? Is parameter validation present? Is authorization ownership checked?

8.4 Acceptance: don't let AI be the acceptor

AI output must pass two gates:

  1. mvn -q compile—only talk after it compiles; faster than reading code by eye;
  2. curl smoke test—whether the interface works, the terminal says so, not the front-end page.

Three high-frequency hallucinations I always check:

One more advanced play: let AI be the "person reviewing your code from a backend perspective." Some dangerous assumptions in front-end intuition are especially hidden, like using CompletableFuture and directly .join() on Tomcat thread, blocking the request thread. I ask directly: "Help me see if this code blocks on a request thread?" AI may not always be right, but it can highlight the most dangerous assumptions in your intuition.

9. Pitfall collection: 24 real problems in one table

This is the meat of the article. All the pitfalls I've stepped on and readers have asked, all at once:

# Pitfall Typical symptom Solution
1 JAVA_HOME misconfigured java command not found or version messed up Point to JDK root, add %JAVA_HOME%\bin to Path
2 Maven dependencies slow / conflict Full of red text, can't start Switch to Aliyun mirror; mvn dependency:tree to check conflicts
3 Boot 3 package name gap javax.validation won't compile Pin Java 17 + Boot 3, hardcode jakarta.* in prompts
4 MP old starter incompatible ClassNotFound: javax.servlet.* Switch to mybatis-plus-spring-boot3-starter
5 Cross-origin CORS Access-Control-Allow-Origin red text Dev use Vite proxy; production Nginx same-origin or CORS whitelist
6 Vite proxy changes ineffective Config modified but interface still reports error No hot reload, restart dev server
7 Front-end/back-end type drift Backend changes field, page silently white-screens springdoc → openapi-typescript, expose at compile time
8 Validation double-write inconsistency Front-end passes, backend 400 Bean Validation as single source of truth, front-end only hints
9 Error codes written differently Some throw 500 with stack, some return string R + @RestControllerAdvice + traceId throughout
10 Transaction invalidation Data written halfway Only add to Service public methods; self-calls within same class don't go through proxy
11 MP pagination plugin not registered total = 0, SQL has no LIMIT Register PaginationInnerInterceptor, place before optimistic lock
12 Security blocks OPTIONS Login endpoint 401, preflight rejected OPTIONS /** permitAll
13 jjwt 0.12 API change Old tutorial code won't compile verifyWith(key).build().parseSignedClaims(token)
14 Signature algorithm implicit Key changed, old tokens all invalid signWith(key, Jwts.SIG.HS256) explicit
15 401 format conflict Front-end gets 401, not JSON authenticationEntryPoint writes JSON manually, align to R
16 JWT key hardcoded / too short Brute-force cracked or leaked into repo @Value injection + environment variables, ≥ 256 bits, production switch to RS256
17 AI piles logic into Controller One method 200 lines, can't add transaction Define layering conventions before generating, review locks this down
18 Entity returned directly to front-end Password, salt all exposed DTO/VO isolation, sensitive fields never in VO
19 Unauthorized access Front-end passes a userId, you trust it Parse identity from token, don't trust front-end params
20 Exception stack too long Eight hundred lines, can't find direction Look for Caused By first, dump whole thing to AI
21 Async model conflict Using Event Loop thinking for thread pool Don't .join() on request thread; use explicit thread pool for parallel aggregation
22 Token storage confusion How to store, how to send all messy localStorage + axios interceptor, backend unified validation
23 Project structure chaos Front-end and back-end files mixed /frontend + /backend two directories, each runs its own
24 Demo-to-production gap Local H2 fine, can't connect on deployment Flyway for DDL + connection pool + logging chain

When talking about these in interviews, describe symptoms and root causes, don't just memorize terms—that's what convinces interviewers.

When integration errors occur, my muscle-memory troubleshooting order looks like this:

image.png

The biggest mindset shift for front-end transition is from "open F12 to see errors" to "first check backend logs, then database real SQL, finally back to front-end". Once this chain is established, integration efficiency multiplies.

10. From Demo to production: these steps remain

Demo running is just the start. In interviews they often ask "what would you change to go to production," my answer is this list:

  1. Database: H2 to MySQL, configure HikariCP pool, use Flyway to manage DDL versions;
  2. Deployment: front-end dist to Nginx static hosting, backend jar package, same-domain deployment eliminates CORS entirely;
  3. Observability: normalize logging (use log.info / log.error, stop System.out.println), AOP to record interface latency, add actuator monitoring;
  4. Reproducibility: built-in H2 plus schema.sql, configure Maven Wrapper, after git clone one mvn spring-boot:run runs;
  5. Quality: JUnit 5 + Mockito for unit tests, Docker one-click to start both ends.

These are also interview bonus points: OpenAPI contract, Flyway, Docker, logging standards—mention one and the interviewer will think you're serious about this transition.

Extra: five high-frequency follow-ups

Q: What if AI writes something wrong? Lock versions, check compile, curl smoke test, line-by-line diff. AI is scaffolding; acceptance right is mine. After generation, run mvn -q compile first; faster than reading code by eye.

Q: Why use Vite proxy in development instead of backend opening CORS? Proxy is same-origin request, simplest, and avoids Cookie/Credentials cross-origin traps; production uses Nginx or gateway to handle centrally.

Q: Front-end transition, wouldn't NestJS be smoother? Why choose Java? Usually determined by team legacy stack and ops system; selection follows organization. And what I'm migrating is engineering ability—contract, layering, error governance—that set is universal across languages.

Q: How much Java should I learn before starting? Run the loop first, then work on fundamentals. Get Spring MVC, ORM, transactions, REST contract familiar first; JVM, concurrency, distributed—polish these in real business.

Q: What does the interviewer actually want to hear? Not your recitation of "Java has eight primitive types, Spring has IoC AOP," but this phrase: I can quickly build a runnable front-end/back-end loop, know how to do layering, transactions, validation, exceptions, integration, and use AI to improve efficiency without passing risks to the team.

Final words

Compress the whole article into one sentence:

Front-end to full-stack = use Java to replicate your front-end mental model + triple (unified response / DTO validation / global exception) + AI as scaffold, you as acceptor. Run first, run correctly, then run fast.

Three actionable suggestions:

  1. Tonight use Spring Initializr plus H2 to pull up the skeleton, run one CRUD first—don't memorize syntax;
  2. Treat unified response R<T> and global exception as the first common module to write; integration experience immediately improves;
  3. Try openapi-typescript and say goodbye to front-end/back-end type drift.

If useful, like, share, follow—I'll keep updating this front-end-to-full-stack series.

Finally leave an interactive question: When you first touched backend, which pitfall got you the worst—cross-origin, transactions, or that 800-line exception stack? Share in comments, I'll break it down one by one.

Comments

Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.

暴走的菜鸟 1 likes

I hand-coded a simple admin system from 0 to 1, also using Java Spring Boot. (covering face)

Rain的Java大神之路

As long as it runs, haha.