Spring Security 4和REST的问题不会显示HTML文件

时间:2015-12-08 21:57:09

标签: java spring spring-mvc spring-security

我的proyect有问题,我尝试使用Spring REST配置Spring Security 4,但是当我尝试使用任何上下文访问时出现问题。

这是我的项目结构:

enter image description here

"观点"是我的HTML页面。

这是我的弹簧配置。

<import resource="classpath:applicationContext-business.xml"/>
<mvc:annotation-driven />


<security:http auto-config="true" >

    <security:intercept-url pattern="/" access="permitAll" />
    <security:intercept-url pattern="/home" access="permitAll" />

    <security:form-login  login-page="/iniciar_sesion"
                 username-parameter="email"
                 password-parameter="password"
                 authentication-failure-url="/Access_Denied" />
    <security:csrf/>

</security:http>
<context:component-scan base-package="turing.solutions.dy.web" >
    <context:include-filter type="regex" expression=".*\.(.)*"/>
    <context:exclude-filter type="regex" expression="security"/>
</context:component-scan>

<bean id="customUserDetailsService" class="turing.solutions.dy.web.security.CustomUserDetailService" />

<security:authentication-manager>
    <security:authentication-provider user-service-ref="customUserDetailsService"/>
</security:authentication-manager>

我的web.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>dy</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dy</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>


<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<session-config>
    <session-timeout>
        10
    </session-timeout>
</session-config>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

这是我的RestController:

@RestController
public class LoginController {

@RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
public String homePage() {
    System.out.println("Redirect");
    return "index";
}

@RequestMapping(value="iniciar_sesion",method = RequestMethod.GET)
public String iniciarSession(ModelMap model){
    model.put("login", "log");
    return "iniciar_sesion";
}

@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")
public Map<String, Object> login() {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("login", "ok");
    return map;
}

@RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
public String accessDeniedPage(ModelMap model) {
    model.addAttribute("user", getPrincipal());
    return "accessDenied";
}

private String getPrincipal() {
    String userName = null;
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    if (principal instanceof UserDetails) {
        userName = ((UserDetails) principal).getUsername();
    } else {
        userName = principal.toString();
    }
    return userName;
}

}

Ant这是我的CustomUserDetailService

@Service("customUserDetailService")
public class CustomUserDetailService implements UserDetailsService {

@Autowired
private UsuariosService usuariosService;

@Override
public UserDetails loadUserByUsername(String correo) throws UsernameNotFoundException {
    Usuarios usuario = this.usuariosService.findByCorreo(correo);
    if (usuario == null) {
        throw new UsernameNotFoundException("El usuairo " + correo + " no existe, favor de verificar");
    }
    return new User(usuario.getEmail(), usuario.getPassword(), usuario.getActivo(), true, true, true, getGrantedAuthorities(usuario));
}

private List<GrantedAuthority> getGrantedAuthorities(Usuarios usuario) {
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    for (Roles rol : usuario.getRolesList()) {
        System.out.println("Usuario " + usuario.getEmail() + " ROl" + rol.getDescRol().toUpperCase());
        authorities.add(new SimpleGrantedAuthority("ROLE_" + rol.getDescRol().toUpperCase()));
    }
    return authorities;
}
}

当我尝试访问网址&#34; http://localhost:9080/DespreocupateYA/home&#34;我看到了这个

enter image description here

但我应该看到这个

enter image description here

所以,我的问题是:为什么我无法在项目中看到html页面?我已经搜索过了,我找到了许多Spring配置,但是我还没能解决问题。

我的服务器是Apache Tomcat 8.0.28。

我希望你能帮助我,谢谢。

1 个答案:

答案 0 :(得分:2)

将您的@RestController注释更改为@Controller,它将正常运行。

Here是解释这两个注释之间差异的文档

当你说RestController时,你指的是一个控制器,它处理一些像JSON对象这样的数据。在这里,您需要一个简单的Controller来处理html视图。

修改

您没有提到您正在使用哪种视图呈现引擎,这是jsp的示例配置

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
</bean>

这是你的spring conifguration文件,请确保声明"http://www.springframework.org/schema/beans"名称空间,以便可以使用bean定义