← Back to list

Syntax Issues .Spring Boot

Spring Boot, Write code correctly.

Correct Syntax SpringB oot · 2025-12-12 18:30 · 0 claps · 3.1 min read
#correct-syntax #spring-boot #correct-syntax-springboot #4t #tcs-handson
Open on Medium ↗
Wiki topics: PFI · Personal Finance LNG · Linguistics & Language

Syntax Issues .Spring Boot

Spring Boot, Write code correctly.

How can you write code correctly ? the answer is by doing lots of practice.

You can use Spring Boot to create Java applications that can be started by using java -jar or more traditional war deployments.

Our primary goals are:

  • Provide a radically faster and widely accessible getting-started experience for all Spring development.
  • Be opinionated out of the box but get out of the way quickly as requirements start to diverge from the defaults.
  • Provide a range of non-functional features that are common to large classes of projects (such as embedded servers, security, metrics, health checks, and externalized configuration).
@Component
public class AuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private LoginService loginService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        final String authorizationHeader = request.getHeader("Authorization");

        String username = null;
        String jwt = null;

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            username = jwtUtil.getUsernameFromToken(jwt);
        }

         if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.loginService.loadUserByUsername(username);
            if (jwtUtil.validateToken(jwt, userDetails)) {
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities());
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }

        filterChain.doFilter(request, response);
    }
}

  // ✅ extract username
        public String getUsernameFromToken(String token) {
            return getClaimFromToken(token, Claims::getSubject);
        }

        // ✅ extract expiration
        public Date getExpirationDateFromToken(String token) {
            return getClaimFromToken(token, Claims::getExpiration);
        }

        // ✅ generic claims resolver
        public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
            final Claims claims = getAllClaimsFromToken(token);
            return claimsResolver.apply(claims);
        }

        // ✅ get all claims
        private Claims getAllClaimsFromToken(String token) {
            return Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(token)
                    .getBody();
        }

        // ✅ check expiration
        private Boolean isTokenExpired(String token) {
            final Date expiration = getExpirationDateFromToken(token);
            return expiration.before(new Date());
        }

        // ✅ generate token
        public String generateToken(UserDetails userDetails) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("roles", userDetails.getAuthorities());
            return doGenerateToken(claims, userDetails.getUsername());
        }

        // ✅ token builder
        private String doGenerateToken(Map<String, Object> claims, String subject) {
            return Jwts.builder()
                    .setClaims(claims)
                    .setSubject(subject)
                    .setIssuedAt(new Date(System.currentTimeMillis()))
                    .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
                    .signWith(SignatureAlgorithm.HS512, secretKey)
                    .compact();
        }

        // ✅ validate token
        public Boolean validateToken(String token, UserDetails userDetails) {
            final String username = getUsernameFromToken(token);
            return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
        }

 @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
     @Autowired
    UserDetailsService userDetailsService;

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception{
        return configuration.getAuthenticationManager();
    }

    @Bean
    public AuthenticationProvider authenticationProvider(){
        DaoAuthenticationProvider provider =new DaoAuthenticationProvider(userDetailsService);
        provider.setPasswordEncoder(new BCryptPasswordEncoder(12));
        return provider;
    }

    @Autowired
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    @Autowired
    JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer(){
        return (web -> web.ignoring().requestMatchers("/h2-console/**","/login"));
    }

     public SecurityFilterChain securityFilterChain(HttpSecurity https) throws Exception {
        return https.cors(  httpSecurityCorsConfigurer -> httpSecurityCorsConfigurer. disable())
                .csrf( httpSecurityCsrfConfigurer -> httpSecurityCsrfConfigurer.disable())
                .authorizeHttpRequests( authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers("/bidding/update/**").hasAuthority("APPROVER")
                                .requestMatchers("/bidding/delete/**").hasAnyAuthority("BIDDER","APPROVER")
                                .requestMatchers("/bidding/list").hasAnyAuthority("APPROVER","BIDDER").anyRequest().authenticated())
                                .exceptionHandling(exceptionHandlingConfigurer -> exceptionHandlingConfigurer.authenticationEntryPoint(jwtAuthenticationEntryPoint))
                                .sessionManagement(sessionManagementConfigurer -> sessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                                .addFilterBefore(jwtAuthenticationFilter,UsernamePasswordAuthenticationFilter.class).build();
        }
    }
//// EntryPoint --

@Service
public class LoginService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        UserModel user = userRepository.findByEmail(email);
        if (user == null) {
            throw new UsernameNotFoundException("User not found with email: " + email);
        }
        return buildUserForAuthentication(user);
    }

    private UserDetails buildUserForAuthentication(UserModel user) {
        List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority(user.getRole().getRolename()));
        return new org.springframework.security.core.userdetails.User( user.getEmail(), user.getPassword(), authorities );
    }
}

///login controller

    @PostMapping("/login")
    public ResponseEntity<Object> authenticateUser(@RequestBody LoginDTO loginDTO) {
        try {
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginDTO.getEmail(),loginDTO.getPassword())
            );

            UserDetails userDetails = loginService.loadUserByUsername(loginDTO.getEmail());
            String jwt = jwtUtil.generateToken(userDetails);

            Map<String, Object> response = new HashMap<>();
            response.put("jwt", jwt);
            response.put("status", HttpStatus.OK.value());
            return ResponseEntity.ok(response);

        } catch (BadCredentialsException e) {
           return new ResponseEntity<>("Invalid credentials", HttpStatus.BAD_REQUEST);
        }
    }

/// Bidding service

 // ===================== POST BIDDING =====================
    public ResponseEntity<Object> postBidding(BiddingModel biddingModel) {
        try {
            String email = getCurrentUserEmail();
            UserModel user = userService.getUserByEmail(email);

            // Only BIDDER role can post a bid
            if (!"BIDDER".equals(user.getRole().getRolename())) {
                return new ResponseEntity<>("Forbidden", HttpStatus.FORBIDDEN);
            }

            biddingModel.setBidderId(user.getId());
            biddingModel.setDateOfBidding(getCurrentDate());

            biddingRepository.save(biddingModel);
            return new ResponseEntity<>(biddingModel, HttpStatus.CREATED);

        } catch (Exception e) {
            return new ResponseEntity<>("Bad Request", HttpStatus.BAD_REQUEST);
        }
    }

    // ===================== GET BIDDINGS =====================
    public ResponseEntity<Object> getBidding(double bidAmount) {
        List<BiddingModel> results = biddingRepository.findByBidAmountGreaterThan(bidAmount);

        if (results.isEmpty()) {
            return new ResponseEntity<>("No data available", HttpStatus.BAD_REQUEST);
        }

        return new ResponseEntity<>(results, HttpStatus.OK);
    }

    // ===================== UPDATE BIDDING =====================
    public ResponseEntity<Object> updateBidding(int id, BiddingModel model) {
        try {
            BiddingModel bidding = biddingRepository.findById(id).orElse(null);

            if (bidding == null) {
                return new ResponseEntity<>("Bad Request", HttpStatus.BAD_REQUEST);
            }

            String email = getCurrentUserEmail();
            UserModel user = userService.getUserByEmail(email);

            // Only APPROVER can update bidding
            if (!"APPROVER".equals(user.getRole().getRolename())) {
                return new ResponseEntity<>("Forbidden", HttpStatus.FORBIDDEN);
            }

            bidding.setStatus(model.getStatus());
            biddingRepository.save(bidding);

            return new ResponseEntity<>(bidding, HttpStatus.OK);

        } catch (Exception e) {
            return new ResponseEntity<>("Bad Request", HttpStatus.BAD_REQUEST);
        }
    }

    // ===================== DELETE BIDDING =====================
    public ResponseEntity<Object> deleteBidding(int id) {
        try {
            BiddingModel bidding = biddingRepository.findById(id).orElse(null);

            if (bidding == null) {
                return new ResponseEntity<>("Not found", HttpStatus.BAD_REQUEST);
            }

            String email = getCurrentUserEmail();
            UserModel user = userService.getUserByEmail(email);

            // APPROVER or the same BIDDER can delete the bid
            if ("APPROVER".equals(user.getRole().getRolename()) || bidding.getBidderId() == user.getId()) {
                biddingRepository.delete(bidding);
                return new ResponseEntity<>("Deleted successfully", HttpStatus.NO_CONTENT);
            } else {
                return new ResponseEntity<>("You don't have permission", HttpStatus.FORBIDDEN);
            }

        } catch (Exception e) {
            return new ResponseEntity<>("Bad Request", HttpStatus.BAD_REQUEST);
        }
    }

    // ===================== UTILITY METHODS =====================
    private String getCurrentUserEmail() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        }

        return null;
    }

    private String getCurrentDate() {
        return new SimpleDateFormat("dd/MM/yyyy").format(new Date());
    }

These are the some short of example, to correctly use Java SpringBoot.


메타데이터
post_id
47658a7c852c
slug
syntax-issues-spring-boot-47658a7c852c
url
https://medium.com/@CorrectSyntax212/syntax-issues-spring-boot-47658a7c852c
canonical_url
https://medium.com/@CorrectSyntax212/syntax-issues-spring-boot-47658a7c852c
author_url
https://medium.com/@CorrectSyntax212
status
ok
fetched_at
2026-06-23 17:05:31