Spring Boot RESTful Web Services Guide
Spring Boot RESTful Web Services Guide
import [Link];
import [Link];
import [Link];
import [Link].*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table
(
name = "posts", uniqueConstraints = {@UniqueConstraint(columnNames = {"title"})}
)
public class Post {
@Id
@GeneratedValue( strategy = [Link]) )
private Long id;
[Link] = jdbc:mysql://localhost:3306/myblog?
useSSL=false&serverTimezone=UTC
[Link] = root
[Link] = root
# hibernate properties
[Link] = [Link].MySQL5InnoDBDialect
import [Link];
import [Link];
@Data
public class PostDto {
private long id;
private String title;
private String description;
private String content;
}
import [Link];
@Service
public class PostServiceImpl implements PostService {
@Override
public PostDto createPost(PostDto postDto) {
@RestController
@RequestMapping("/api/posts")
public class PostController {
import [Link];
import [Link];
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException{
import [Link];
@RestController
@RequestMapping("/api/posts")
public class PostController {
import [Link];
import [Link];
List<PostDto> getAllPosts();
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Service
public class PostServiceImpl implements PostService {
@Override
public PostDto createPost(PostDto postDto) {
@Override
public List<PostDto> getAllPosts() {
List<Post> posts = [Link]();
return [Link]().map(post -> mapToDTO(post)).collect([Link]());
}
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
@RestController
@RequestMapping("/api/posts")
public class PostController {
// get post by id
@GetMapping("/{id}")
public ResponseEntity<PostDto> getPostById(@PathVariable(name = "id") long id){
return [Link]([Link](id));
}
import [Link];
import [Link];
List<PostDto> getAllPosts();
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Service
public class PostServiceImpl implements PostService {
@Override
public PostDto createPost(PostDto postDto) {
@Override
public List<PostDto> getAllPosts() {
List<Post> posts = [Link]();
return [Link]().map(post -> mapToDTO(post)).collect([Link]());
}
@Override
public PostDto getPostById(long id) {
Post post = [Link](id).orElseThrow(() -> new
ResourceNotFoundException("Post", "id", id));
return mapToDTO(post);
}
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
@RestController
@RequestMapping("/api/posts")
public class PostController {
// get post by id
@GetMapping("/{id}")
public ResponseEntity<PostDto> getPostById(@PathVariable(name = "id") long id){
return [Link]([Link](id));
}
}
Step 17: Update PostService Interface:
import [Link];
import [Link];
List<PostDto> getAllPosts();
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Service
public class PostServiceImpl implements PostService {
@Override
public List<PostDto> getAllPosts() {
List<Post> posts = [Link]();
return [Link]().map(post -> mapToDTO(post)).collect([Link]());
}
@Override
public PostDto getPostById(long id) {
Post post = [Link](id).orElseThrow(() -> new
ResourceNotFoundException("Post", "id", id));
return mapToDTO(post);
}
@Override
public PostDto updatePost(PostDto postDto, long id) {
// get post by id from the database
Post post = [Link](id).orElseThrow(() -> new
ResourceNotFoundException("Post", "id", id));
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
@RestController
@RequestMapping("/api/posts")
public class PostController {
// get post by id
@GetMapping("/{id}")
public ResponseEntity<PostDto> getPostById(@PathVariable(name = "id") long id){
return [Link]([Link](id));
}
import [Link];
import [Link];
List<PostDto> getAllPosts();
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Service
public class PostServiceImpl implements PostService {
@Override
public PostDto createPost(PostDto postDto) {
@Override
public List<PostDto> getAllPosts() {
List<Post> posts = [Link]();
return [Link]().map(post -> mapToDTO(post)).collect([Link]());
}
@Override
public PostDto getPostById(long id) {
Post post = [Link](id).orElseThrow(() -> new
ResourceNotFoundException("Post", "id", id));
return mapToDTO(post);
}
@Override
public PostDto updatePost(PostDto postDto, long id) {
// get post by id from the database
Post post = [Link](id).orElseThrow(() -> new
ResourceNotFoundException("Post", "id", id));
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
@Override
public void deletePostById(long id) {
// get post by id from the database
Post post = [Link](id).orElseThrow(() -> new
ResourceNotFoundException("Post", "id", id));
[Link](post);
}
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
@RestController
@RequestMapping("/api/posts")
public class PostController {
// get post by id
@GetMapping("/{id}")
public ResponseEntity<PostDto> getPostById(@PathVariable(name = "id") long id){
return [Link]([Link](id));
}
[Link](id);
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Service
public class PostServiceImpl implements PostService {
@Override
public PostDto createPost(PostDto postDto) {
@Override
public PostResponse getAllPosts(int pageNo, int pageSize, String sortBy, String
sortDir) {
Sort sort = [Link]([Link]()) ?
[Link](sortBy).ascending()
: [Link](sortBy).descending();
//or we can do this also
// Sort sort=null;
// if([Link]([Link]()){
// Sort=[Link](sortBy).ascending();
// }else{
// sort=[Link](sortBy).descending(); }
return postResponse;
}
@Override
public PostDto getPostById(long id) {
Post post = [Link](id).orElseThrow(() -> new
ResourceNotFoundException("Post", "id", id));
return mapToDTO(post);
}
@Override
public PostDto updatePost(PostDto postDto, long id) {
// get post by id from the database
Post post = [Link](id).orElseThrow(() -> new
ResourceNotFoundException("Post", "id", id));
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
@Override
public void deletePostById(long id) {
// get post by id from the database
Post post = [Link](id).orElseThrow(() -> new
ResourceNotFoundException("Post", "id", id));
[Link](post);
}
import [Link];
import [Link];
import [Link];
import [Link].*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "comments")
public class Comment {
@Id
@GeneratedValue(strategy = [Link])
private long id;
@ManyToOne(fetch = [Link])
@JoinColumn(name = "post_id", nullable = false)
private Post post;
}
import lombok.*;
import [Link].*;
import [Link];
import [Link];
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(
name = "posts", uniqueConstraints = {@UniqueConstraint(columnNames =
{"title"})}
)
public class Post {
@Id
@GeneratedValue(
strategy = [Link]
)
private Long id;
@Data
public class CommentDto {
private long id;
private String name;
private String email;
private String body;
}
import [Link];
@Service
public class CommentServiceImpl implements CommentService {
@Override
public CommentDto createComment(long postId, CommentDto commentDto) {
// comment entity to DB
Comment newComment = [Link](comment);
return mapToDTO(newComment);
}
@RestController
@RequestMapping("/api/")
public class CommentController {
@PostMapping("/posts/{postId}/comments")
public ResponseEntity<CommentDto> createComment(@PathVariable(value =
"postId") long postId,
@RequestBody CommentDto commentDto){
return new ResponseEntity<>([Link](postId,
commentDto), [Link]);
}
}
import [Link];
import [Link];
import [Link];
@Service
public class CommentServiceImpl implements CommentService {
@Override
public CommentDto createComment(long postId, CommentDto commentDto) {
// comment entity to DB
Comment newComment = [Link](comment);
return mapToDTO(newComment);
}
@Override
public List<CommentDto> getCommentsByPostId(long postId) {
// retrieve comments by postId
List<Comment> comments = [Link](postId);
@RestController
@RequestMapping("/api/")
public class CommentController {
@PostMapping("/posts/{postId}/comments")
public ResponseEntity<CommentDto> createComment(@PathVariable(value =
"postId") long postId, @RequestBody CommentDto commentDto){
@GetMapping("/posts/{postId}/comments")
public List<CommentDto> getCommentsByPostId(@PathVariable(value = "postId")
Long postId){
return [Link](postId);
}
}
import [Link];
import [Link];
@Override
public String getMessage() {
return message;
}
}
@Service
public class CommentServiceImpl implements CommentService {
private CommentRepository commentRepository;
private PostRepository postRepository;
private ModelMapper mapper;
public CommentServiceImpl(CommentRepository commentRepository,
PostRepository postRepository, ModelMapper mapper) {
[Link] = commentRepository;
[Link] = postRepository;
[Link] = mapper;
}
@Override
public CommentDto createComment(long postId, CommentDto commentDto) {
// comment entity to DB
Comment newComment = [Link](comment);
return mapToDTO(newComment);
}
@Override
public List<CommentDto> getCommentsByPostId(long postId) {
// retrieve comments by postId
List<Comment> comments = [Link](postId);
// retrieve comment by id
Comment comment = [Link](commentId).orElseThrow(() -
>
new ResourceNotFoundException("Comment", "id", commentId));
if(![Link]().getId().equals([Link]())){
throw new BlogAPIException(HttpStatus.BAD_REQUEST, "Comment does not
belong to post");
}
//or
// if(.getId(),[Link]())){
// throw new BlogAPIException(HttpStatus.BAD_REQUEST,"comment does not
//belong to post");
// }
return mapToDTO(comment);
}
@RestController
@RequestMapping("/api/")
public class CommentController {
@PostMapping("/posts/{postId}/comments")
public ResponseEntity<CommentDto> createComment(@PathVariable(value =
"postId") long postId,
@RequestBody CommentDto commentDto){
return new ResponseEntity<>([Link](postId,
commentDto), [Link]);
}
@GetMapping("/posts/{postId}/comments")
public List<CommentDto> getCommentsByPostId(@PathVariable(value = "postId")
Long postId){
return [Link](postId);
}
@GetMapping("/posts/{postId}/comments/{id}")
public ResponseEntity<CommentDto> getCommentById(@PathVariable(value =
"postId") Long postId, @PathVariable(value = "id") Long commentId){
CommentDto commentDto = [Link](postId,
commentId);
return new ResponseEntity<>(commentDto, [Link]);
}
}
@PutMapping("/posts/{postId}/comments/{id}")
public ResponseEntity<CommentDto> updateComment(@PathVariable(value =
"postId") Long postId,
@PathVariable(value = "id") Long commentId,
@RequestBody CommentDto commentDto){
CommentDto updatedComment = [Link](postId,
commentId, commentDto);
return new ResponseEntity<>(updatedComment, [Link]);
}
import [Link];
}
Step 3: Update CommentServiceImpl class:
@Override
// retrieve comment by id
if(![Link]().getId().equals([Link]())){
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
URL: [Link]
@DeleteMapping("/posts/{postId}/comments/{id}")
[Link](postId, commentId);
import [Link];
@Override
// retrieve comment by id
if(![Link]().getId().equals([Link]())){
[Link](comment);
<dependency>
<groupId>[Link]</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.9</version>
</dependency>
@SpringBootApplication
public class MbyblogApplication {
@Bean
public ModelMapper modelMapper(){
return new ModelMapper();
}
@Service
[Link] = postRepository;
[Link] = mapper;
@Override
return postResponse;
@Override
public PostResponse getAllPosts(int pageNo, int pageSize, String sortBy, String sortDir) {
: [Link](sortBy).descending();
[Link](content);
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
return postResponse;
@Override
@Override
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
return mapToDTO(updatedPost);
@Override
[Link](post);
}
// convert Entity into DTO
// [Link]([Link]());
// [Link]([Link]());
// [Link]([Link]());
// [Link]([Link]());
return postDto;
// [Link]([Link]());
// [Link]([Link]());
// [Link]([Link]());
return post;
@Service
public class CommentServiceImpl implements CommentService {
[Link] = commentRepository;
[Link] = postRepository;
[Link] = mapper;
@Override
[Link](post);
// comment entity to DB
Comment newComment = [Link](comment);
return mapToDTO(newComment);
@Override
@Override
// retrieve comment by id
return mapToDTO(comment);
@Override
// retrieve comment by id
if(![Link]().getId().equals([Link]())){
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
return mapToDTO(updatedComment);
@Override
// retrieve comment by id
if(![Link]().getId().equals([Link]())){
[Link](comment);
}
private CommentDto mapToDTO(Comment comment){
// [Link]([Link]());
// [Link]([Link]());
// [Link]([Link]());
// [Link]([Link]());
return commentDto;
// [Link]([Link]());
// [Link]([Link]());
// [Link]([Link]());
// [Link]([Link]());
return comment;
[Link] = timestamp;
[Link] = message;
[Link] = details;
return timestamp;
return message;
return details;
}
}
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import
[Link];
import [Link];
import [Link];
import [Link];
@ControllerAdvice
@ExceptionHandler([Link])
public ResponseEntity<ErrorDetails>
handleResourceNotFoundException(ResourceNotFoundException exception,
WebRequest webRequest){
[Link](false));
@ExceptionHandler([Link])
WebRequest webRequest){
[Link](false));
// global exceptions
@ExceptionHandler([Link])
WebRequest webRequest){
[Link](false));
Spring Validations
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Data
@NotEmpty
@NotEmpty
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
@RestController
@RequestMapping()
[Link] = postService;
@PostMapping("/api/v1/posts")
if([Link]()){
return new ResponseEntity<>([Link]().getDefaultMessage(),
HttpStatus.INTERNAL_SERVER_ERROR);
}
@GetMapping("/api/v1/posts")
){
// get post by id
@GetMapping(value = "/api/v1/posts/{id}")
return [Link]([Link](id));
@DeleteMapping("/api/v1/posts/{id}")
[Link](id);
Spring Security
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Step 2: All Links of rest api are now secured
[Link]=pankaj
[Link]=password
[Link]=ADMIN
@Configuration
@EnableWebSecurity
@Override
http
.csrf().disable()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
In memory Authentication
import [Link];
import [Link];
import [Link];
import
[Link]
alMethodSecurity;
import
[Link];
import
[Link]
rity;
import
[Link]
nfigurerAdapter;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers([Link], "/api/**").permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
@Override
@Bean
protected UserDetailsService userDetailsService() {
UserDetails ramesh =
[Link]().username("pankaj").password(passwordEncoder()
.encode("password")).roles("USER").build();
UserDetails admin =
[Link]().username("admin").password(passwordEncoder()
.encode("admin")).roles("ADMIN").build();
return new InMemoryUserDetailsManager(ramesh, admin);
}
}
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
@RestController
@RequestMapping("/api/posts")
public class PostController {
@PreAuthorize("hasRole('ADMIN')")
// create blog post rest api
@PostMapping
public ResponseEntity<PostDto> createPost(@Valid @RequestBody PostDto
postDto){
return new ResponseEntity<>([Link](postDto),
[Link]);
}
@PreAuthorize("hasRole('ADMIN')")
// update post by id rest api
@PutMapping("/{id}")
public ResponseEntity<PostDto> updatePost(@Valid @RequestBody PostDto
postDto, @PathVariable(name = "id") long id){
@PreAuthorize("hasRole('ADMIN')")
// delete post rest api
@DeleteMapping("/{id}")
public ResponseEntity<String> deletePost(@PathVariable(name = "id") long
id){
[Link](id);
import [Link];
import [Link].*;
import [Link];
@Data
@Entity
@Table(name = "users", uniqueConstraints = {
@UniqueConstraint(columnNames = {"username"}),
@UniqueConstraint(columnNames = {"email"})
})
public class User {
@Id
@GeneratedValue(strategy = [Link])
private long id;
private String name;
private String username;
private String email;
private String password;
import [Link];
import [Link];
import [Link].*;
@Setter
@Getter
@Entity
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue(strategy = [Link])
private long id;
@Column(length = 60)
private String name;
}
import [Link];
import [Link];
import [Link];
import [Link];
UserDetailsService Implementation
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String usernameOrEmail) throws
UsernameNotFoundException {
User user = [Link](usernameOrEmail,
usernameOrEmail)
.orElseThrow(() ->
new UsernameNotFoundException("User not found with
username or email:" + usernameOrEmail));
return new
[Link]([Link](),
[Link](), mapRolesToAuthorities([Link]()));
}
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import
[Link]
icationManagerBuilder;
import
[Link]
alMethodSecurity;
import
[Link];
import
[Link]
rity;
import
[Link]
nfigurerAdapter;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService userDetailsService;
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers([Link], "/api/**").permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
[Link](userDetailsService)
.passwordEncoder(passwordEncoder());
}
// @Override
// @Bean
// protected UserDetailsService userDetailsService() {
// UserDetails ramesh =
[Link]().username("ramesh").password(passwordEncoder()
// .encode("password")).roles("USER").build();
// UserDetails admin =
[Link]().username("admin").password(passwordEncoder()
// .encode("admin")).roles("ADMIN").build();
// return new InMemoryUserDetailsManager(ramesh, admin);
// }
}
@Data
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@PostMapping("/signin")
public ResponseEntity<String> authenticateUser(@RequestBody LoginDto
loginDto){
Authentication authentication = [Link](
new
UsernamePasswordAuthenticationToken([Link](),
[Link]())
);
[Link]().setAuthentication(authentication);
return new ResponseEntity<>("User signed-in successfully!.",
[Link]);
}
}
Step 3: Update SecurityConfig File:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import
[Link]
icationManagerBuilder;
import
[Link]
alMethodSecurity;
import
[Link];
import
[Link]
rity;
import
[Link]
nfigurerAdapter;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService userDetailsService;
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception
{
return [Link]();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers([Link], "/api/**").permitAll()
.antMatchers("/api/auth/**").permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
[Link](userDetailsService)
.passwordEncoder(passwordEncoder());
}
// @Override
// @Bean
// protected UserDetailsService userDetailsService() {
// UserDetails ramesh =
[Link]().username("ramesh").password(passwordEncoder()
// .encode("password")).roles("USER").build();
// UserDetails admin =
[Link]().username("admin").password(passwordEncoder()
// .encode("admin")).roles("ADMIN").build();
// return new InMemoryUserDetailsManager(ramesh, admin);
// }
}
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import
[Link]
n;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@PostMapping("/signin")
public ResponseEntity<String> authenticateUser(@RequestBody LoginDto
loginDto){
Authentication authentication = [Link](new
UsernamePasswordAuthenticationToken(
[Link](), [Link]()));
[Link]().setAuthentication(authentication);
return new ResponseEntity<>("User signed-in successfully!.",
[Link]);
}
@PostMapping("/signup")
public ResponseEntity<?> registerUser(@RequestBody SignUpDto signUpDto){
[Link](user);
return new ResponseEntity<>("User registered successfully",
[Link]);
}
}
@Data
public class SignUpDto {
private String name;
private String username;
private String email;
private String password;
}
<dependency>
<groupId>[Link]</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Component
@Override
HttpServletResponse response,
[Link](HttpServletResponse.SC_UNAUTHORIZED,
[Link]());
## App Properties
[Link]-secret= JWTSecretKey
[Link]-expiration-milliseconds = 604800000
package [Link];
import [Link];
import
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
// inject dependencies
@Autowired
@Autowired
@Override
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
// validate token
);
[Link](new
WebAuthenticationDetailsSource().buildDetails(request));
[Link]().setAuthentication(authenticationToken);
[Link](request, response);
// Bearer <accessToken>
return null;
package [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Component
@Value("${[Link]-secret}")
// generate token
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(expireDate)
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
return token;
.setSigningKey(jwtSecret)
.parseClaimsJws(token)
.getBody();
return [Link]();
try{
[Link]().setSigningKey(jwtSecret).parseClaimsJws(token);
return true;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
@Autowired
@Autowired
@Autowired
@Autowired
@PostMapping("/signin")
[Link](), [Link]()));
[Link]().setAuthentication(authentication);
// get token form tokenProvider
@PostMapping("/signup")
if([Link]([Link]())){
if([Link]([Link]())){
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]([Link]()));
[Link]([Link](roles));
[Link](user);
[Link] = accessToken;
[Link] = accessToken;
}
[Link] = tokenType;
return accessToken;
return tokenType;
1. AWS
2. Heroku
3. Google Cloud
4. Microsoft Azure
5. Oracle
6. IBM Cloud
Important AWS Services every java developer should be aware of:
1. Amazon EC2 - Amazon Elastic Compute Cloud (EC2) is a web service that
provides resizable computing capacity in the cloud. It allows users to rent
virtual machines (VMs), known as instances, which can be used to run a
variety of different operating systems and applications. With EC2, users can
easily scale their computing resources up or down as needed, paying only for
the resources they actually use. This makes it an ideal service for applications
that have varying compute needs, such as web servers, batch processing, and
big data processing. EC2 also provides a variety of different instance types,
each optimized for different types of workloads, such as compute-optimized,
memory-optimized, and storage-optimized instances. Additionally, EC2 also
provides features such as load balancing, auto-scaling, and virtual private
cloud (VPC) to give users more control and security over their instances
2. AWS Elastic Beanstalk -
Amazon Elastic Beanstalk is a fully managed service offered by AWS that makes
it easy to deploy, run, and scale web applications and services. It supports
several programming languages including Java, .NET, PHP, [Link], Python,
Ruby, and Go. Elastic Beanstalk handles the provisioning of the infrastructure
resources, load balancing, and automatic scaling, allowing developers to focus
on writing code for their application. The service also includes monitoring and
logging features, so developers can easily track the performance and
troubleshoot issues.
Elastic Beanstalk provides a simple, unified user interface to deploy and manage
web applications, as well as a command-line interface and APIs for more
advanced users. It integrates with other AWS services such as Amazon RDS,
Amazon S3, Amazon SNS, and AWS Elasticache. Elastic Beanstalk also provides a
feature called "platform versions" that allows developers to choose a specific
version of the language runtime, web server, and other software components to
use with their application.
3. AMAZON RDS –
Amazon Relational Database Service (RDS) is a web service that makes it easy
to set up, operate, and scale a relational database in the cloud. RDS supports
several popular database engines including MySQL, PostgreSQL, Oracle,
Microsoft SQL Server, and Amazon Aurora.
RDS also provides a feature called "Multi-AZ Deployments" that allows the user
to create a primary DB instance and synchronously replicate the data to a
standby instance in a different availability zone (AZ) for failover capabilities. This
provides an automatic failover to the standby instance in the event of a planned
or unplanned outage of the primary instance.
Amazon Route 53 is a highly available and scalable Domain Name System (DNS)
web service offered by AWS. It translates human-friendly domain names, such as
[Link], into the IP addresses, such as [Link], that computers use
to identify each other on the internet. Route 53 is designed to give developers
and businesses a reliable and cost-effective way to route end users to internet
applications.
Route 53 also provides a feature called "Health Check", that allows the user to
monitor the health of their resources, such as web servers, and route traffic to
healthy resources. It also integrates with other AWS services such as Amazon
CloudFront, Elastic Load Balancing, and AWS Elastic Beanstalk.
It also provides a feature called "Traffic Flow" that allows the user to create a
visual representation of their routing policies and test how the traffic will be
routed before it's updated.
# hibernate properties
#[Link] =
[Link].MySQL5InnoDBDialect
# App Properties
[Link]-secret= JWTSecretKey
[Link]-expiration-milliseconds = 604800000
[Link]=prod
[Link] content:
[Link] = jdbc:mysql://localhost:3306/myblog
[Link] = root
[Link] = test
# hibernate properties
[Link] =
[Link].MySQL5InnoDBDialect
[Link] content:
[Link] = jdbc:mysql://localhost:3306/myblog
[Link] = root
[Link] = test
# hibernate properties
[Link] =
[Link].MySQL5InnoDBDialect
[Link] content:
[Link] = jdbc:mysql://localhost:3306/myblog
[Link] = root
[Link] = test
# hibernate properties
[Link] =
[Link].MySQL5InnoDBDialect
Manually Enter Data into Roles Table Using Command Line Runner
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@SpringBootApplication
public class SpringbootBlogRestApiApplication implements CommandLineRunner {
@Autowired
private RoleRepository roleRepository;
@Bean
public ModelMapper modelMapper(){
return new ModelMapper();
}
@Override
public void run(String... args) throws Exception {
Role adminRole = new Role();
[Link]("ROLE_ADMIN");
[Link](adminRole);
Step 1:
Step 2: Go to AWS:
Step 3: Update Localhostname
Step 6: Click on ok
Step 7: Create Database in aws throughmysql workbench
Step 4:
Step 5:
Step 6:
Step 7:
Step 8:
Step 11:
Step 12:
[Link] status code in API development
HTTP status codes are a crucial part of API development as they provide information about
the status of a request made to a server.
They help communicate the outcome of the request to the client or the calling application.
Here are some commonly used HTTP status codes in API development:
1. 200 OK: This status code indicates that the request was successful, and the server has
returned the requested resource or completed the requested action.
2. 201 Created: This code is used when a new resource is successfully created as a result of a
POST request.
The server should include the location of the newly created resource in the response
headers.
3. 204 No Content: It indicates that the server has successfully processed the request but
does not need to return any content.
4. 400 Bad Request: This status code indicates that the server could not understand the
request due to malformed syntax,
5. 401 Unauthorized: It signifies that the request requires authentication. The client must
provide valid credentials
but the client does not have sufficient permissions to access the requested resource.
7. 404 Not Found: It indicates that the requested resource could not be found on the server.
8. 500 Internal Server Error: This status code indicates that an unexpected error occurred on
the server while processing the [Link] is a generic error message used when no more
specific code is suitable.
These are just a few examples of HTTP status codes used in API [Link] are many
more status codes available, each serving a specific purpose. API developers should choose
the appropriate status codes to provide meaningful information to clients about the outcome
of their requests.-
import lombok.*;
import [Link].*;
@Data
@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = [Link])
private long id;
private String name;
private String course;
private double fee;
@OneToOne(cascade = [Link])
@JoinColumn(name = "id_proof_id",referencedColumnName = "id")
private IdProof idProof;
}
3. create idproof entity class
package [Link];
import [Link];
import [Link].*;
@Entity
@Data
@Table(name = "idproofs")
public class IdProof {
@Id
@GeneratedValue(strategy = [Link])
private long id;
private String pancardNumber;
@OneToOne(mappedBy = "idProof")
private Student student;
}
[Link] [Link] give this
[Link]=jdbc:mysql://localhost:3306/studentinfo?
useSSL=false&serverTimezone=UTC
[Link]=root
[Link]=9861369983
[Link]-class-name=[Link]
[Link]-platform=[Link].MySQL5InnoDBDialect
[Link]-auto=create
# Hibernate Configuration
[Link]-sql=true
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Data
public class StudentDto {
private long id;
private String name;
private String course;
private double fee;
private IdProofDto idProofDto;
}
package [Link];
import [Link];
@Data
public class IdProofDto {
private long id;
private String pancardNumber;
}
7. create service layer
package [Link];
import [Link];
}
package [Link];
import [Link];
@Data
public class IdProofDto {
private long id;
private String pancardNumber;
}
8. create serviceImpl class
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Service
public class StudentServiceImpl implements StudentService {
private StudentRepository studentRepo;
private IdProofRepository idProofRepo;
@Override
public StudentDto saveStudent(StudentDto studentDto) {
IdProof idProof =new IdProof();
idProof=[Link](idProof);
Student student =new Student();
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link](idProof);
student= [Link](student);
StudentDto dto =new StudentDto();
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link](idDto);
return dto;
}
}
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Service
public class IdProofServiceImpl implements IdProofService {
private IdProofRepository idProofRepo;
@Override
public IdProofDto updateIdProof(long id, String pancardNumber) {
IdProof proof = [Link](id).orElseThrow(() -> new
IdProofNotFoundException("student not there"));
[Link](pancardNumber);
IdProof save = [Link](proof);
IdProofDto dto=new IdProofDto();
[Link]([Link]());
[Link]([Link]());
return dto;
}
}
9. create exception class
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
@RestController
@RequestMapping("/api/students")
public class StudentController {
private StudentService studentService;
package [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
@RestController
@RequestMapping("/api/students")
public class IdProofController {
private IdProofService idProofService;