powered by simpleCommunicator - 2.0.49     © 2025 Programmizd 02
Форумы / Java [игнор отключен] [закрыт для гостей] / Почему не показывает страницу логина
10 сообщений из 10, страница 1 из 1
Почему не показывает страницу логина
    #39824002
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Я хочу в своем проекте реализовать одну функцию. У меня есть список студентов, я хочу чтобы на ту jsp страницу мог заходить только авторизованный пользователь в моем случае только админ. Когда я запускаю проект он просит войти, когда я нажимаю войти он не запрашивает логин и пароль и сразу же отправляет на страницу где список студентов. А нужно чтобы он запросил логин и пароль и если он правильный то только тогда можно будет войти.

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.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
package adil.java.schoolmaven.controller;
    
    import org.springframework.stereotype.Controller;
    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{
    
    	// If user will be successfully authenticated he/she will be taken to the login secure page.
    	@RequestMapping(value="/admin", method = RequestMethod.GET)
    	public ModelAndView adminPage() {
    
    		ModelAndView m = new ModelAndView();
    		m.addObject("title", "Вы успешно вошли");
    		m.addObject("message", "Основная");
    		m.setViewName("admin");
                    
                    return new ModelAndView("redirect: allStudents");
    		
    	}
    
    	// Spring security will see this message.
    	@RequestMapping(value = "/login", method = RequestMethod.POST)
    	public ModelAndView login(@RequestParam(value = "error", required = false) String error, 
    			@RequestParam(value = "logout", required = false) String logout) {
    
    		ModelAndView m = new ModelAndView();
    		if (error != null) {
    			m.addObject("error", "Неверный логин и пароль");		
    		}
    
    		if (logout != null) {
    			m.addObject("msg", "Вы успешно вышли");		
    		}
    
    		m.setViewName("login");
    		 
                     return new ModelAndView("redirect: allStudents");
    	}
    }




StudentController
Код: 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.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
    package adil.java.schoolmaven.controller;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.List;
    import javax.servlet.ServletContext;
    import adil.java.schoolmaven.entity.Student;
    import adil.java.schoolmaven.service.StudentService;
    import java.nio.file.FileSystemException;
    import javax.servlet.http.HttpServletRequest;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.lang.NonNull;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    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.multipart.MultipartFile;
    import org.springframework.web.servlet.ModelAndView;
    
    @Controller
    public class StudentController {
    
        @Autowired
        private ServletContext servletContext;
    
        // Constructor based Dependency Injection
        private StudentService studentService;
    
        public StudentController() {
    
        }
    
        @Autowired
        public StudentController(StudentService studentService) {
            this.studentService = studentService;
        }
    
        
       
       
        @RequestMapping(value = "/allStudents", method = {RequestMethod.GET, RequestMethod.POST})
    
        public ModelAndView displayAllUser() {
            System.out.println("User Page Requested : All Students");
            ModelAndView mv = new ModelAndView();
            List<Student> studentList = studentService.getAllStudents();
            mv.addObject("studentList", studentList);
            mv.setViewName("allStudents");
            return mv;
        }
    
        @RequestMapping(value = "/addStudent", method = RequestMethod.GET)
        public ModelAndView displayNewUserForm() {
            ModelAndView mv = new ModelAndView("addStudent");
            mv.addObject("headerMessage", "Add Student Details");
            mv.addObject("student", new Student());
            return mv;
        }
    
        @PostMapping(value = "/addStudent")
        public String saveNewStudent(@RequestParam("name") @NonNull String name,
                @RequestParam("surname") @NonNull String surname,
                @RequestParam("avatar") MultipartFile file)
                throws IOException {
    
            Student student = new Student();
            student.setSurname(surname);
            student.setName(name);
    
            if (file != null && !file.isEmpty()) {
                student.setAvatar(studentService.saveAvatarImage(file).getName());
            }
    
            studentService.saveStudent(student);
            return "redirect:/allStudents";
        }
    
        @GetMapping(value = "/editStudent/{id}")
        public ModelAndView displayEditUserForm(@PathVariable Long id) {
            ModelAndView mv = new ModelAndView("editStudent");
            Student student = studentService.getStudentById(id);
            mv.addObject("headerMessage", "Редактирование студента");
            mv.addObject("student", student);
            return mv;
        }
    
        @PostMapping(value = "/editStudent")
        public String saveEditedUser(
                @RequestParam("id") Long id,
                @RequestParam("name") String name,
                @RequestParam("surname") String surname,
                @RequestParam("avatar") MultipartFile file) {
    
            try {
    
                studentService.updateStudent(name, surname, file, studentService.getStudentById(id));
    
            } catch (FileSystemException ex) {
                ex.printStackTrace();
            } catch (IOException e) {
                return "redirect:/error";
            }
    
            return "redirect:/allStudents";
        }
    
        @GetMapping(value = "/deleteStudent/{id}")
        public ModelAndView deleteUserById(@PathVariable Long id) {
            studentService.deleteStudentById(id);
            ModelAndView mv = new ModelAndView("redirect:/allStudents");
    
            return mv;
    
        }
    
    }




mvc-dispatcher-servlet

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
  <?xml version="1.0" encoding="UTF-8"?>
    <beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
        
        <context:component-scan base-package="adil.java.schoolmaven" />
        
        <!-- Resolves Views Selected For Rendering by @Controllers to *.jsp Resources in the /WEB-INF/ Folder -->
        <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/" />
            <property name="suffix" value=".jsp" />
        </bean>
    </beans>
...
Рейтинг: 0 / 0
Почему не показывает страницу логина
    #39824003
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
fallen2019,
CustomWebSecurityConfigurerAdapter
Код: 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.core.annotation.Order;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;

@Order(1)
@Configuration
@EnableWebSecurity
@Component
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
 
    @Autowired
    private MyBasicAuthenticationEntryPoint authenticationEntryPoint;
 
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
          .withUser("admin").password(passwordEncoder().encode("1234"))
          .authorities("ROLE_ADMIN");
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
          .antMatchers("/securityNone").permitAll()
          .anyRequest().authenticated()
          .and()
          .httpBasic()
          .authenticationEntryPoint(authenticationEntryPoint);
 
        http.addFilterAfter(new CustomFilter(),
          BasicAuthenticationFilter.class);
    }
 
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
...
Рейтинг: 0 / 0
Почему не показывает страницу логина
    #39824004
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
fallen2019,

MyBasicAuthenticationEntryPoint
Код: 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.
package adil.java.schoolmaven.config;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.stereotype.Component;

@Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
 
    @Override    
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx) throws IOException, ServletException {
        response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = response.getWriter();
        writer.println("HTTP Status 401 - " + authEx.getMessage());
    }
 
    @Override
    public void afterPropertiesSet() throws Exception {
        setRealmName("Baeldung");
        super.afterPropertiesSet();
    }
}
...
Рейтинг: 0 / 0
Почему не показывает страницу логина
    #39824592
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Совет вам дали 21901817 , но вы по прежнему продолжаете "жрать кактус".
Надеетесь, что как-то по другому все разрешится само?
...
Рейтинг: 0 / 0
Почему не показывает страницу логина
    #39824737
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

Я сделал вроде все правильно, залил на гитхаб. Но че то не пашет сам проект запускается но страницу логина не показывает говорит, что я уже вошел хотя логин и пароль не вводил
...
Рейтинг: 0 / 0
Почему не показывает страницу логина
    #39824980
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
fallen2019SQL2008,

Я сделал вроде все правильно
Ну хорошо.
Тогда покажите мне где и как задали доступ к странице списка студентов только для авторизованных пользователей?
...
Рейтинг: 0 / 0
Почему не показывает страницу логина
    #39824984
Фотография mayton
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
fallen2019SQL2008,

Я сделал вроде все правильно, залил на гитхаб. Но че то не пашет сам проект запускается но страницу логина не показывает говорит, что я уже вошел хотя логин и пароль не вводил
Был у меня знакомый тестер. Он - на любую проблему отвечал - Кеши почистили? Куки удалили?
...
Рейтинг: 0 / 0
Почему не показывает страницу логина
    #39825032
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
fallen2019, рекомендую почитать и разобраться . Мне в свое время очень помогло.
...
Рейтинг: 0 / 0
Почему не показывает страницу логина
    #39825037
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Навскидку (это то чего я долго, но безуспешно допытывался)
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
          .antMatchers("/securityNone").permitAll()
          .and()
          .antMatchers("/allStudents").access("hasRole('ROLE_USER')")
          .and()
          .anyRequest().authenticated()
          .and()
          .httpBasic()
          .authenticationEntryPoint(authenticationEntryPoint);
 
        http.addFilterAfter(new CustomFilter(),
          BasicAuthenticationFilter.class);
    }
...
Рейтинг: 0 / 0
Почему не показывает страницу логина
    #39825170
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

У меня получилось))

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.
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package adil.java.schoolmaven.config;

import org.springframework.beans.factory.annotation.Autowired;
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;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("{noop}1234").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .anyRequest().access("hasRole('ROLE_ADMIN')")
                .and()
                .authorizeRequests().antMatchers("/login**").permitAll()
                .and()
                .formLogin().loginPage("/login").loginProcessingUrl("/loginAction").permitAll()
                .and()
                .logout().logoutSuccessUrl("/login").permitAll()
                .and()
                .csrf().disable();
    }
}
...
Рейтинг: 0 / 0
10 сообщений из 10, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Почему не показывает страницу логина
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


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