Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save Kurukshetran/1aec976f341a307ebbb8c4dffba7e219 to your computer and use it in GitHub Desktop.

Select an option

Save Kurukshetran/1aec976f341a307ebbb8c4dffba7e219 to your computer and use it in GitHub Desktop.
Complete E-Commerce Course - Java,Spring,Hibernate and MySQL
----------------------------------------------------------------
Complete E-Commerce Course - Java,Spring,Hibernate and MySQL
================================================================
We will decouple project on two parts - frontend, backend
Some code will dublicate - this is a negative side of two server project.
1. my account module:
user - order history, shipping, profile , billing
guest - login , forget password, create account
2.the browse book model:
search - by category , by keywords in book title, fuzzy search
view book Detail - add book to shopping cart, showbook
3. bookstore - shopping Cart:
cart item - modify cart item
checkout - shipping, billing, payment, order confirmation
4. Admin portal - book mangemnt:
book - add boook , update book, delete book
----------------------------------------------
Start Project with Index Page
----------------------------------------------
*file - new spring starter project --> bookstore
description - frontend part of bookstore
*then choose web
*download bootstrap and copy files to the main -- resources -- static
main - resources --> templates create a new index html
*copying https://getbootstrap.com/examples/navbar
and paste to our file
*in our file add a dependency : spring boot starter thymeleaf
*modify bootstrap css path like that
/css/bootstrap.min.css
*go to navbar.css and copy style
*create style css in static/css
*rename path og cuton styles /css/style.css
*correct the js path
/js/bootstrap.min.js
*java/bookstore/controller create a Home controller
@Controller
public class HomeController{
@RequestMapping("/")
public String index() {
return "index";
}
}
*deploy -- error 500 - internal error
correct index html (forget closing tag)
*set "spring.thymeleaf.cache=false;" in application properties
now сhanges in static content will be enabled without
rebooting appliaction
-----------------------------------------------------------
Adding carousel in index page
-----------------------------------------------------------
*remove <container> from the navbar to make it the whole width
*remove "test of block" container
*adding test container with box.css and disable cache in chrome
to see the updtes : developing kit -- network -- disable cache
*use css/carousel from bootstrap site, adding a closing tag to
img tag
*Add images to cousel and lorem
------------------------------------------------------------
Adding more pictures
------------------------------------------------------------
*adding panel from bootstrap on top of carousel
*adding a logo, create package "img/logo" and add to the carousel
col-xs-4
*extend the container of carousel with css. Use incognito chrome
to see this changing
*add a horizonral line after the carousel (<hr/>)
*remove red panel around the caurusel
*add 3 pivtures after the horizontal line
*need to refresh the folder img, because 3 pictures were added
*remove body style css
*adding div class ="page-top" before static navbar
------------------------------------------------------------
Adding Featured-books and Non-responsive CSS
------------------------------------------------------------
*adding div of featured books
*adding a horizontal line after
*adding another courusel editing the first one (carousel inner of books)
*adding non responsive navbar , because in small resolutions it becomes VERY small. Bootstrap - disable responsiveless(google)
*correct page top
*add favicon
-----------------------------------------------------------
navbar
------------------------------------------------------------
Correcting some details
*add shelf.img to carousel of the books
*removing the "collapse" from navbar witch is response to the adaptive design
*fill in a dropdown menu and other text
*add a search form
------------------------------------------------------------
Adding Common Part of Template(thymeleaf)
------------------------------------------------------------
*split main html into many files, put it into the "common" libraryS
*adding a thymeleaf
*union the parts using thymeleaf(th:replace)
=============================================================
Adding my account page
------------------------------------------------------------
creating an acc page html
add to the Home Controller
adding NAv tabs to the acc page html
------------------------------------------------------------
Adding MyAccount Page Body
------------------------------------------------------------
adding tab panels
That's it! See the source code
-----------------------------------------------------------
Adding User Entity, JPA, Hibernate and MySQL
-----------------------------------------------------------
Creating java/bookstore/domain/User
*set attributes of class User
*add dependencies jdbc, data-jpa, mySQL
*add annotations of jpa to the User
*generate getters and setters
*additions to application.properties
default hosting for the database is 3306
*Create database in MySQLWorkbrench
-----------------------------------------------------------
Adding Security and Security Entities
-----------------------------------------------------------
create domain/security
add depency spring boot starter security
create domain/security/Authority
*create class Role:
https://spring-source.ru/docs_simple.php?type=manual&theme=docs_simple&docs_simple=chap04_p03
В JPA описаны два типа fetch стратегии:
1) LAZY — данные поля будут загруженны только во время первого доступа к этому полю,
2) EAGER — данные поля будут загруженны немедленно
*create UserRole class
*Adding security to the
-----------------------------------------------------------
Adding Security Configuration
-----------------------------------------------------------
create java/bookstore/config/SecurityConfig
@EnableWebSecurity will provide configuration via HttpSecurity providing the configuration you could find with <http></http> tag in xml configuration, it's allow you to configure your access based on urls patterns, the authentication endpoints, handlers etc...
EnableGlobalMethodSecurity provides AOP security on methods, some of annotation it will enable are PreAuthorize PostAuthorize also it has support for JSR-250. There is also more parameters in configuration for you
For your needs, it's better mix the two. With REST you can achieve all you need only with @EnableWebSecurity, since HttpSecurity#antMatchers(HttpMethod,String...) accepts controls over Http methods
Аннотация @EnableWebSecurity в связке с WebSecurityConfigurerAdapter классом работает над обеспечением аутентификации. По умолчанию в Spring Security встроены и активны HTTP аутентификация и аутентификация на базе веб форм.
Кроме всего, здесь прописываем пользователей с их ролями, а затем указываем адреса ресурсов с ограниченным доступом, ограничение задано по ролям. Имена и пароли пользователей, для простоты, указаны прямо в коде. Spring Security позволяет с легкостью указать другой источник для данных о пользователях, например базу данных. Обратите внимание что роли в месте где мы присваиваем их пользователю пишутся без префикса ROLE_, в то время как в указании в методе access, в котором мы, с помощью языка выражений SPEL (Spring Expression Language), задаем выражения проверки ресурса (в нашем случае выражение проверки роли пользователя hasRole(‘ROLE_имя роли’)), мы пишем роль с префиксом ROLE_. Еще одна маленькая хитрость для аутентификации: defaultSuccessUrl("/", false), установка второго параметра (alwaysUse) в false говорит Spring Security что в случае успешной авторизации можно перенаправить пользователя на ту страничку, с которой он пришел на страницу аутентификации.
...
THIS IS A DIFFICULT MODULE NEED TO BE REWRITTEN after getting
additional information abouspring security
--------------------------------------------------------------
Adding More to Login
--------------------------------------------------------------
Также буду рассматирвать потом, после изучения дополнительного материала. Нужная фишка, если напрмер залогинен - не выводить кнопку логин, пароль и тд. Делается с помощью thymeleaf.
В этом уроки есть все что свзяано с thymeleaf и логин страницей
--------------------------------------------------------------
Adding PasswordResetToken and UserService
--------------------------------------------------------------
C этого урока пожалуй можно начать пока...
тут идет создание нового юзера
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment