Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Lab Assignment Spring Framework

The document outlines a series of lab assignments focused on building a book application using various Spring technologies, including Dependency Injection (DI), Aspect-Oriented Programming (AOP), JDBC, Hibernate, MVC, REST, and Security. It provides detailed instructions for designing the persistence and service layers, implementing CRUD operations, applying DI through XML, annotations, and Java configuration, and enhancing the application with logging and security features. The document emphasizes maintaining a clean separation of concerns and ensuring that the service layer remains unaffected by changes in the persistence layer.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lab Assignment Spring Framework

The document outlines a series of lab assignments focused on building a book application using various Spring technologies, including Dependency Injection (DI), Aspect-Oriented Programming (AOP), JDBC, Hibernate, MVC, REST, and Security. It provides detailed instructions for designing the persistence and service layers, implementing CRUD operations, applying DI through XML, annotations, and Java configuration, and enhancing the application with logging and security features. The document emphasizes maintaining a clean separation of concerns and ensuring that the service layer remains unaffected by changes in the persistence layer.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 7

LAB ASSIGNMENTS: Spring DI, AOP, Spring-JDBC, Spring-Hibernate, Spring-MVC,

Spring REST, Spring Security

CORE SPRING: Dependency injection

1. Create an book application

Design persistance layer:

com.training.model.persistance

public class Book {


private int id;
private String isbn;
private String title;
private String author;
private double price;

//getter setter , ctr


}

public interface BookDao {


public List<Book> getAllBooks();
public Book addBook(Book book);
public void deleteBook(int id);
public void updateBook(int id, Book book);
public Book getBookById(int id);
}

public class BookDaoImp implements BookDao {


private static Map<Integer, Book> booksMap = new HashMap<Integer, Book>();
private static int counter = 0;
static {
booksMap.put(++counter, new Book(counter, "ABC123", "Head first Java" ,
"Katthy", 600));
booksMap.put(++counter, new Book(counter, "ABC723", "Servlet jsp Java" ,
"Katthy", 700));
}

@Override
public List<Book> getAllBooks() {
return new ArrayList<Book>(booksMap.values());
}

@Override
public Book addBook(Book book) {
book.setId(++counter);
booksMap.put(counter, book);
return booksMap.get(counter);
}
@Override
public void deleteBook(int id) {
booksMap.remove(id);
}

@Override
public void updateBook(int id, Book book) {
booksMap.put(id, book);
}

@Override
public Book getBookById(int id) {
return booksMap.get(id);
}

Design Service layer:

com.training.model.service

public interface BookService {


public List<Book> getAllBooks();
public Book addBook(Book book);
public void deleteBook(int id);
public void updateBook(int id, Book book);
public Book getBookById(int id);
}

public class BookServiceImp implements BookService {

//BAD CODE HARD CODING....

private BookDao dao=new BookDaoImp();

@Override
public List<Book> getAllBooks() {
return dao.getAllBooks();
}

@Override
public Book addBook(Book book) {
return dao.addBook(book);
}

@Override
public void deleteBook(int id) {
dao.deleteBook(id);
}
@Override
public void updateBook(int id, Book book) {
dao.updateBook(id, book);
}

@Override
public Book getBookById(int id) {
return dao.getBookById(id);
}

Improve application design by dependency injection

1. Apply DI using xml


2. Apply DI using annotation
3. Apply DI using java configuraiton
4. we have used hard coded collection in dao layer, and initilized it

private static Map<Integer, Book> booksMap = new HashMap<Integer, Book>();


private static int counter = 0;
static {
booksMap.put(++counter, new Book(counter, "ABC123", "Head first Java" ,
"Katthy", 600));
booksMap.put(++counter, new Book(counter, "ABC723", "Servlet jsp Java" ,
"Katthy", 700));
}

Now replace this configuration with bean wiring in xml.

CORE SPRING: AOP

In lab DI you have created book application, now we require to log information while somebody
deleted book
Improve the application using AOP to applying logging, You can create an custom annotation such
as @Loggable and put it one deleteBook method. Now if book is deleted information about
deleted book should added to log file in aop way.
You can use code snippet mentioned below.

@Service
public interface BookService implements BookService {
@Autowire
private BookDao dao;
public List<Book> getAllBooks(){
}
public Book addBook(Book book){}

public void deleteBook(int id){


// if somebody delete book we need to log information in log file using AOP
}
public void updateBook(int id, Book book){}
public Book getBookById(int id){}
}

Custom annotation

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Loggable {

Improve application design by AOP

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class MethodLogger {
private static final Logger logger=LoggerFactory.getLogger(MethodLogger.class);

@Around("@annotation(Loggable)")
public Object around(ProceedingJoinPoint point) throws Throwable {
long start = System.currentTimeMillis();
Object result = point.proceed();
logger.info("start "+MethodSignature.class.cast(" Method takes " +(System.currentTimeMillis() -
start));
return result;
}
}

Spring JDBC

In lab AOP you have created book application, now we require to replace persistance layer with
jdbc. Note that service layer should
remain uneffected by the change.

@Service
public interface BookService implements BookService {

@Autowire
private BookDao dao;

public List<Book> getAllBooks(){


}
public Book addBook(Book book){}

public void deleteBook(int id){

}
public void updateBook(int id, Book book){}
public Book getBookById(int id){}
}

Implement crud method using jdbc, inject datasource in persistane layer, using xml and java
configuration

Spring Hibernate/JPA
In lab Spring Jdbc you have created book application using JDBC, now we require to replace
persistance layer with Hibernate. Note that service layer shouldremain uneffected by the change.

@Service
public interface BookService implements BookService {

@Autowire
private SessionFactory factory;

public List<Book> getAllBooks(){


}
public Book addBook(Book book){}

public void deleteBook(int id){

}
public void updateBook(int id, Book book){}
public Book getBookById(int id){}
}

1. Implement crud method using Hibernate, inject factory in persistane layer, using xml and java
configuration
2. Implement crud method using spring-Hibernate ( reduce boilerplat code)
3. Apply declerative transaction management using @Transactinal annotation
4. Do experiments with different optionals available with @Transactinal annotation

Spring MVC
In lab Spring Hibernate you have created book application with persistance layer using spring-
Hibernate,
now we require to integrate that application using Spring MVC

Web layer<======> Service layer <=======> Persistance layer <=======> DB


1. You need to use validation api 303 for server side validation
2. Use java configuration
3. Use xml configuration
4. Configuration application to use connection pool configured with tomcat
5. Use bootstrap, css, angularjs with book application
Spring REST

In this lab you need to support REST endpoint for book application.

Take the help of given code snippet. Note use of @RestController and @ RequestMapping
annotation.

1. Provide support for CURD operation


2. Proper ResponseEntity should be returned as per requirments
3. study http status code and return appropiate status code
4. Provide HATOAS support to application
5. Test using postman
6. Write client api

@RestController// @RestController=@Controller + @ResponseBody


public class BookResources {

@Autowired
private BookDao dao;

@RequestMapping(value = "/api/book", method = RequestMethod.GET, produces =


MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<Book>> getAllBooks() {
Collection<Book> greetings = dao.getAllBooks();
return new ResponseEntity<Collection<Book>>(greetings, HttpStatus.OK);
}

@RequestMapping(value = "/api/book/{id}", method = RequestMethod.GET, produces =


MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Book> getAnBook(@PathVariable Integer id) {
Book book = dao.getBookById(id);
if (book == null) {
return new ResponseEntity<Book>(HttpStatus.NOT_FOUND);
}

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


}

@RequestMapping(value = "/api/book", method = RequestMethod.POST, consumes =


MediaType.APPLICATION_JSON_VALUE, produces =
MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Book> createBook(@RequestBody Book book) {
Book savedBook = dao.addBook(book);
return new ResponseEntity<Book>(savedBook, HttpStatus.CREATED);
}

@RequestMapping(value = "/api/book/{id}", method = RequestMethod.PUT, consumes =


MediaType.APPLICATION_JSON_VALUE, produces =
MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Book> updateBook(@PathVariable Integer id,
@RequestBody Book book) {

dao.updateBook(id, book);

return new ResponseEntity<Book>(HttpStatus.OK);


}

@RequestMapping(value = "/api/book/{id}", method = RequestMethod.DELETE)


public ResponseEntity<Book> deleteBook(@PathVariable("id") Integer id)
throws Exception {

dao.deleteBook(id);

return new ResponseEntity<Book>(HttpStatus.NO_CONTENT);


}

Spring Security

In lab Spring MVC you have created book application with following design:
Web layer<======> Service layer <=======> Persistance layer <=======> DB

Now Integrate spring security:

1. only registred user can logged in application


2. only admin have right to delete an book
3. Provide url based, method level and object level security
4. Use password hashing
5. Remember me
6. Use JDBC, hibernate to configure user information

You might also like