website development denton


The last small black introduced four distributed consistency in the article. Session Implementation,The most commonly used in these four is the rear centralized storage solution,This is even web Application restart or expand,Session There is no loss of risk。

website development denton(Website development Denton)

Today we use this way to Session Storage mode is transformed,Store it in uniform Redis middle。


Let's first think about it.,If we don't rely on any framework,How to implement the backend Session Central storage。

(Website development Denton)Here we assume that our website except some pages,For example, the homepage can be directly accessed,Other pages need to be logged in to visit。

If you need this need,This requires our authentication to each request.,The authentication is to determine if the user is logged in.,Determine user role。

If the user is not logged in,We need to force the request to jump to the login page for login。

After the user logs in,We need to store the user information acquired by the login to Session middle,This is requested after requesting authentication only needs to be judged. Session Whether there is existence。

Know the entire process,In fact, the principle of achieving is not very difficult.。

We can use similar AOP Principle,After each request comes in,First judge first Session Is there any user information?,If you don't exist, you jump to the login page.。

The whole process is as follows:

website development denton

We can use Servelt Filter Implement the above process,However, the above sets of flows,Spring Has helped us achieve,Then we don't have to repeat the wheels.。

We can use Spring-Session and Spring-security Realize the process of the above website。

Spring-Session Yes Spring Provide a set of management users Session Implementation,use Spring-Session Later,default WEB container,for example Tomcat,produced Session Be Spring-Session take over。

Besides,Spring-Session Several common backend storage implementation,for example Redis,Database, etc.。

Have Spring-Session Later,It just helped us solve Session Back end concentrated storage。But in the above process, we also need to log in to authorization.,And this piece we can use Spring-security to realise。

Spring-security Can maintain a unified login authorization method,At the same time it can combine Spring-Session use together。After the user login authorization,The acquired user information can be stored automatically Spring-Session middle。

All right,Don't say nonsense,Let's see the implementation code.。

Below Spring Boot accomplish, Spring-Boot Version:2.3.2.RELEASE

Spring Session

First of all we introduce Spring Session rely,Here we use Redis Central storage Session information,So we need the following dependencies.。


if not Spring Boot project,The main need to introduce the following dependencies:


Relative,We first need application.propertiesIncrease Session Related configuration:

## Session Storage method

## Session Expiration,The default unit is s
## Session Store Redis Key prefix

## Redis Related configuration

After the configuration is completed,Spring Session Will start management Session information,Let's test it.:

public String hello() {
    return "Hello World";
(Website development Denton)When we access the above address,access Redis ,Can see stored Session information。

I recommend everyone Redis Client「Another Redis DeskTop Manager」,This client UI Page very beautiful,It is also very convenient to operate,download link:

(Website development Denton)

website development denton

by default,Session By defaultHttpSession Serialization,This value looks not intuitive enough。We can modify it into json Serialization,Store redis middle。

public class HttpSessionConfig implements BeanClassLoaderAware {

    private ClassLoader loader;

    public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
        return new GenericJackson2JsonRedisSerializer(objectMapper());

     * Customized {@link ObjectMapper} to add mix-in for class that doesn't have default
     * constructors
     * @return the {@link ObjectMapper} to use
    private ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        return mapper;

    public void setBeanClassLoader(ClassLoader classLoader) {
        this.loader = classLoader;

after modification Redis The key value is as follows:

(Website development Denton)website development denton

ps:here Redis Key value meaning,When the source code is analyzed next time,A further analysis。

Spring Session There is still one @EnableRedisHttpSession,We can configure this annotation Spring Session Related configuration。

@EnableRedisHttpSession(redisNamespace = "test:session")

have to be aware of is,If you use this annotation,Will be caused Session Related configuration invalid,Means of Spring Session Will directly use an annotation configuration。

website development denton

Here, small black comparison recommending everyone to use configuration files。

All right,Spring Session Here we have completed it.。

Spring security

We integrate above Spring Session,Finish Session Unite Redis storage。Next, it is mainly necessary to implement the login authentication of the request.。

This step we use Spring security Realize unified login authentication services,The same frame is still Shiro,We will use it here Spring Full-family bucket。

(Website development Denton)First of all, we need to rely on the corresponding dependence:


Introducing above,A random password will be generated after the application is started,Then all requests will jump to one Spring security Page。

website development denton

default password

website development denton

log in page

Here we need to realize the landing page of your business,So we need to customize login check logic。

(Website development Denton)exist Spring security We only need to implement UserDetailsServiceinterface,Rewrite loadUserByUsernameMethod logic。

public class UserServiceImpl implements UserDetailsService {

    PasswordEncoder passwordEncoder;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // Simplicity,Direct internal verification
        String uname = "admin";
        String passwd = "1234qwer";

        // If it is a formal project,We need to data data from database data,Then check,The form is as follows:
        // User user = userDAO.query(username);

        if (!username.equals(uname)) {
            throw new UsernameNotFoundException(username);
        // Encapsulate Spring security Defined User Object
        return User.builder()
                .passwordEncoder(s -> passwordEncoder.encode(passwd))
                .authorities(new SimpleGrantedAuthority("user"))

Above code implementation,Here mainly in memory fixed username and password,Under the real environment,We need to modify to query user information from the database。

(Website development Denton)Then we need to put UserServiceImpl Configure Spring security middle。

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    UserServiceImpl userService;

    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();

     * Use custom user service check-in information
     * @param auth
     * @throws Exception
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // User login information verification use custom userService
        // You should also pay attention to password encryption and verification needs to use the same way.


In the above configuration,Password part we use BCrypt Algorithm encryption,I need attention here.,Encryption and decryption requires the same way。

Then we need to implement a custom landing page,Here is too lazy to write yourself.,Use directly spring-session-data-redis page。

<!DOCTYPE html>
<html xmlns:th="" xmlns:layout=""
<div layout:fragment="content">
    <!-- Custom login request    -->
    <form name="f" th:action="@{/auth/login}" method="post">
            <legend>Please Login -</legend>
            <div th:if="${param.error}" class="alert alert-error">Invalid username and password.</div>
            <div th:if="${param.logout}" class="alert alert-success">You have been logged out.</div>
            <label for="username">Username</label>
            <input type="text" id="username" name="username"/>
            <label for="password">Password</label>
            <input type="password" id="password" name="password"/>
            <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
            <label>remember me: </label>
            <input type="checkbox" name="remember-me"/>
            <div class="form-actions">
                <button type="submit" class="btn">Log in</button>
(Website development Denton)I need a little attention here.,here form Request address of the form /auth/login,We need to modify it in the configuration below,The address of the login request is required by default. /login。

Then we are above SecurityConfig Category increase the corresponding configuration method:

 * Custom processing login processing
 * @param http
 * @throws Exception
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests((authorize) -> authorize
            .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll() // Static resource,for example css,js No need to log in
            .anyRequest().permitAll() // Other pages require login authentication
    ).formLogin((formLogin) -> formLogin  // Custom login page
            .loginPage("/login"// Login page
            .loginProcessingUrl("/auth/login"// Custom login request address
            .permitAll()// The login page is of course no need to authenticate,Otherwise don't you do this??
    ).logout(LogoutConfigurer::permitAll // Logout page
    ).rememberMe(rememberMe -> rememberMe
            .rememberMeCookieName("test-remember"// Remember me cookie name
            .key("test"// Salt value
            .tokenValiditySeconds(3600 * 12)) // remember me,Local generation cookie Contains user information


This method may be longer,Focus on explanation:

Finally, we need to configure some page jump addresses.:

public class WebMvcConfig implements WebMvcConfigurer {

    public void addViewControllers(ViewControllerRegistry registry) {
        // front page
        // Jump after login home Page



So far,We have integrated Spring-Session and Spring-security Complete the full site login authentication function。From this example you can see,After introducing this two framework,We only need to follow Spring Standardize development,Other complex realization principles, we don't need to achieve themselves.,This is really convenient。

It's just a simple small example,Small black is just throwing jade,Real development may need to modify the configuration will be more,Here you need a small partner yourself to study in depth.。

refer to


website development company american fork


website development company american fork Florida, USA,What is the cost of a dynamic e-commerce website??At the data exitWe are e-commerce website designersThe company provides the best professional web design for small or large companies in

quality management plan for website development


quality management plan for website development Website as a facade in the Internet promotion,Is the display of corporate image,The importance is self-evident。So how to build a high quality website?What issues need to pay attention to during websit

how to choose website development company


how to choose website development company In today's fast-developing economy,Small and medium-sized enterprises have realized the importance of enterprise website to enterprise development。However,The website building market is polarized。Some