Гость
Форумы / Java [игнор отключен] [закрыт для гостей] / Почему после авторизации не показывает нужную страницу / 4 сообщений из 4, страница 1 из 1
17.06.2019, 08:01
    #39827071
fallen2019
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Почему после авторизации не показывает нужную страницу
Я хочу чтобы после авторизации админа сразу показывала страницу "allStudents.jsp", но у меня ее не показывает. Я вроде все правильно написал, можете посмотреть может написал с ошибкой

Security Config

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
package adil.java.schoolmaven.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Bean    
public UserDetailsService userDetailsService() {    
    InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();    
    manager.createUser(User.withDefaultPasswordEncoder()  
    .username("admin").password("1234").roles("ADMIN").build());    
    return manager;    
}    
    
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/allStudents**").permitAll()
                .antMatchers("/addStudent**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/editStudent/**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/deleteStudent/**").access("hasRole('ROLE_ADMIN')")
                
       .antMatchers("/index", "/user","/").permitAll()  
      .antMatchers("/admin").authenticated()  
      .and()  
      .formLogin()  
      .loginPage("/login") 
      .defaultSuccessUrl("/allStudents")
      .and()  
      .logout()  
      .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));  
}           
                
     
}




AuthorizationController


Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
package adil.java.schoolmaven.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class AuthorizationController {
    
    
@RequestMapping(value="/", method=RequestMethod.GET)    
    public String index() {    
            
        return "index";    
    }    
    @RequestMapping(value="/login", method=RequestMethod.GET)    
    public String login() {    
            
        return "login";    
    }    
}

    



login.jsp
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
<c:url value="/login" var="loginUrl"/>  
<form action="${loginUrl}" method="post">         
    <c:if test="${param.error != null}">          
        <p>  
            Invalid username and password.  
        </p>  
    </c:if>  
    
    <p>  
        <label for="username">Username</label>  
        <input type="text" id="username" name="username"/>      
    </p>  
    <p>  
        <label for="password">Password</label>  
        <input type="password" id="password" name="password"/>      
    </p>  
    <input type="hidden"                          
        name="${_csrf.parameterName}"  
        value="${_csrf.token}"/>  
    <button type="submit" class="btn">Log in</button>  
</form>




allStudents.JSP
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
        <link href="../css/style.css" rel="stylesheet" type="text/css">
        <style><%@include file="/css/style.css"%></style>
        <title>Все студенты</title>
    </head>
    <body>
         
        
          
        
         <c:if test="${param.logout != null}">         
        <p>  
            You have been logged out.  
        </p> 
        
 
        <br>
        <br>
        <br>
        <br>
        <div class="it">
            <h3>Список всех студентов</h3>
            ${message}
            
            <br>
            <br>
            <table class="table">
                <thead>
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Name</th>

                        <th scope="col">Surname</th>
                        <th scope="col">Avatar</th>
                    </tr>
                </thead>
                <tbody>
                    <c:forEach var="student" items="${studentList}">
                        <tr>
                            <th scope="row">1</th>
                            <td>${student.name}</td>
                            <td>${student.surname}</td>

                            <td><img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}" style="max-height: 200px; max-width: 200px;" /></td>

                            <td>
                                <a href="${pageContext.request.contextPath}/editStudent/${student.id}">
                                    <button type="button" class="btn btn-primary">Edit</button>
                                </a>
                            </td>
                            <td>
                                <a href="${pageContext.request.contextPath}/deleteStudent/${student.id}">
                                    <button type="button" class="btn btn-primary">Delete</button>
                                </a>
                            </td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
            
        </div>
    </body>
</html>
...
Рейтинг: 0 / 0
17.06.2019, 09:15
    #39827081
SQL2008
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Почему после авторизации не показывает нужную страницу
А в WEB.XML какая определена страница по-умолчанию?
...
Рейтинг: 0 / 0
17.06.2019, 09:27
    #39827090
fallen2019
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Почему после авторизации не показывает нужную страницу
SQL2008,

Я без WEB.XML делаю

ServletInitializer

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
package adil.java.schoolmaven.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Value("${spring.servlet.multipart.max-file-size}")

    private int maxFileSize;

    @Value("${spring.servlet.multipart.max-request-size}")

    private int maxRequestSize;

    @Autowired

    private Environment environment;

    @Override

    protected Class<?>[] getRootConfigClasses() {

        return new Class[]{HibernateConfig.class, SecurityConfig.class };

    }

    @Override

    protected Class<?>[] getServletConfigClasses() {

        return new Class[]{WebMvcConfig.class};

    }

    @Override

    protected String[] getServletMappings() {

        return new String[]{"/"};

    }
}



Web MVC config
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
package adil.java.schoolmaven.config;



import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.annotation.Order;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@EnableJpaRepositories
@ComponentScan(basePackages = "adil.java.schoolmaven")
@PropertySource("classpath:application.properties")
public class WebMvcConfig implements WebMvcConfigurer {
        
    @Value("${spring.servlet.multipart.max-file-size:1024}")

    private int maxUploadFileSize;

    @Bean

    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

  

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/css");
    }

    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();

        resolver.setMaxUploadSize(maxUploadFileSize * 1024);

        return resolver;
    }
    
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

	
...
Рейтинг: 0 / 0
17.06.2019, 09:43
    #39827095
SQL2008
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Почему после авторизации не показывает нужную страницу
fallen2019SQL2008,

Я без WEB.XML делаю


Значит я тут не помощник... Как-то по старинке, все проекты с WEB.XML
...
Рейтинг: 0 / 0
Форумы / Java [игнор отключен] [закрыт для гостей] / Почему после авторизации не показывает нужную страницу / 4 сообщений из 4, страница 1 из 1
Целевая тема:
Создать новую тему:
Автор:
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]