标签: spring-4

Spring 4 - addResourceHandlers无法解析静态资源

我的maven spring项目目录结构如下所示.我正在使用基于Spring-4注释的配置.我配置如下的资源.我尝试了许多Stackoverflow问题和其他网站中提出的方法

Spring 4加载静态资源

http://imwill.com/spring-mvc-4-add-static-resources-by-annotation/#.U5GZlXKs9i4

但是jsp文件无法加载资源,所有静态内容请求都返回404错误.我在jsp中试过这些东西,

 <link href="resources/css/bootstrap.css" rel="stylesheet" media="screen">
 <link href="/resources/css/bootstrap.css" rel="stylesheet" media="screen">
 <link href="css/bootstrap.css" rel="stylesheet" media="screen">
Run Code Online (Sandbox Code Playgroud)

编辑:我正在使用servlet 2.5,因为到目前为止我无法将我的项目从JBoss 5升级到更高版本.JBoss5不支持servlet 3,那重要吗?

@Configuration
@ComponentScan("com.mgage.mvoice")
public class MyAppWebConfig extends WebMvcConfigurerAdapter {
     public void addResourceHandlers(ResourceHandlerRegistry registry) {  
        // I tried these many combinations separately.

        ResourceHandlerRegistration resourceRegistration = registry
            .addResourceHandler("resources/**");
        resourceRegistration.addResourceLocations("/resources/**");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/**");
        registry.addResourceHandler("/img/**").addResourceLocations("/img/**");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/**");
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("classpath:/resources/"); 
              // do the classpath works with the directory under webapp?
     }

}
Run Code Online (Sandbox Code Playgroud)

项目结构

java spring spring-mvc spring-annotations spring-4

29
推荐指数
3
解决办法
8万
查看次数

WebSecurityConfigurerAdapter与ResourceServerConfigurerAdapter之间的关系

我正在尝试将Spring OAuth2集成到Spring MVC REST中.大多数Spring OAuth2示例中只有ResourceServerConfigurerAdapter一些也有一些WebSecurityConfigurerAdapter.我不打算将OAuth与Google,Facebook等集成.我正在尝试为Spring MVC REST提供基于令牌的身份验证,该Basic身份验证目前基于身份验证.有人可以在单个服务器中了解Spring MVC REST + OAuth集成需要什么,而不是或者很好的资源吗?

目前我的POC没有WebSecurityConfigurerAdapter,但与之ResourceServerConfigurerAdapter一起工作AuthorizationServerConfigurerAdapter.看起来ResourceServerConfigurerAdapter就够了.现在我不知道我应该怎样对我现有的WebSecurityConfigurerAdapter,在我的Spring MVC REST应用程序中完美运行.

spring-mvc spring-security spring-4 spring-oauth2

27
推荐指数
1
解决办法
2万
查看次数

Maven:Spring 4 + Spring Security

你能解释一下如何用Spring正确构建一个Web应用程序吗?我知道Spring框架的最新版本是4.0.0.RELEASE,但最新版本的Spring Security是3.2.0.RELEASE,它取决于spring 3.2.6 ...也许我错了:)

如何将其与Maven集成?我可以使用Spring 4还是必须使用以前的版本?什么是正确的方法?

如果它不难你,你能告诉我你的pom.xml吗?

spring spring-mvc spring-security maven spring-4

24
推荐指数
1
解决办法
2万
查看次数

如何在spring4中配置"CommonsMultipartResolver"而不用xml来上传文件

我使用xml配置spring4工作得很好.像这样:

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
    p:defaultEncoding="utf-8" >
    <!-- one of the properties available; the maximum file size in bytes -->  
    <!-- <property name="maxUploadSize" value="40000000" /> -->  
</bean>
Run Code Online (Sandbox Code Playgroud)

当我配置spring4而没有xml.like时:

@Configuration
@ComponentScan({ "common.user", "service" })
@EnableWebMvc
public class SpringMVCConfig {

@Bean
public ViewResolver createInternalResourceViewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setContentType("text/html");
    viewResolver.setPrefix("/view/");
    //viewResolver.setSuffix(".jsp");
    return viewResolver;
}

@Bean
public DefaultServletHttpRequestHandler createDefaultServletHttpRequestHandler() {
    return new DefaultServletHttpRequestHandler();
}


@Bean
public CommonsMultipartResolver createMultipartResolver() {
    CommonsMultipartResolver resolver=new CommonsMultipartResolver();
    resolver.setDefaultEncoding("utf-8");
    return resolver;
}
Run Code Online (Sandbox Code Playgroud)

}

它引发了一个异常:

 ?? 30, 2014 …
Run Code Online (Sandbox Code Playgroud)

java file spring-mvc uploading spring-4

23
推荐指数
1
解决办法
4万
查看次数

使用@Scheduled和@EnableScheduling但是给出NoSuchBeanDefinitionException

我已经在线跟踪非常简单的示例在Spring中设置了一个cron作业但我每次都在我的Tomcat启动日志中不断收到此错误:

2015-05-25 00:32:58 DEBUG ScheduledAnnotationBeanPostProcessor:191 - 
Could not find default TaskScheduler bean org.springframework.beans.factory.NoSuchBeanDefinitionException: No 
qualifying bean of type [org.springframework.scheduling.TaskScheduler] is defined

2015-05-25 00:32:58 DEBUG ScheduledAnnotationBeanPostProcessor:202 - Could not    
find default ScheduledExecutorService bean
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying    
bean of type [org.springframework.scheduling.TaskScheduler] is defined
Run Code Online (Sandbox Code Playgroud)

并且用于实现cron的2个java类:

1)@Configuration类:

@Configuration
@EnableScheduling
public class ClearTokenStoreCronEnable {    
  final static Logger log =   
  LoggerFactory.getLogger(ClearTokenStoreCronEnable.class);
  private @Autowired TokenStoreRepository tokenStoreRepository; 
}
Run Code Online (Sandbox Code Playgroud)

和Cron工作班:

@Service
public class ClearTokenStoreWorkerService {

    final static Logger log = LoggerFactory.getLogger(ClearTokenStoreWorkerService.class);
    private @Autowired TokenStoreRepository tokenStoreRepository;

    //@Scheduled(fixedDelay=5000)
    //run …
Run Code Online (Sandbox Code Playgroud)

java cron scheduled-tasks spring-4

23
推荐指数
4
解决办法
4万
查看次数

java.lang.IllegalArgumentException:期待IdClass映射

我已为我的实体配置了复合主键,Employee如下所示

Employee.java:

@Entity
@Table(name="employee")
@Proxy(lazy=false)
@IdClass(EmployeeId.class)
public class Employee implements Serializable {
    private static final long serialVersionUID = 1L;

    private EmployeeId employeeId;
    private Person person;
    private Branch branch;
    private boolean isActive;

    public Employee() {

    }    

    @EmbeddedId
    @AttributeOverrides({
        @AttributeOverride(name="person", column = @Column(name="person_id")),
        @AttributeOverride(name="branch", column = @Column(name="branch_id"))})

    public EmployeeId getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(EmployeeId employeeId) {
        this.employeeId = employeeId;
    }

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="person_id")
    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person; …
Run Code Online (Sandbox Code Playgroud)

java sessionfactory spring-orm spring-4 hibernate-5.x

23
推荐指数
2
解决办法
9119
查看次数

使用Hibernate 5和Spring 4的编程SchemaExport/SchemaUpdate

使用Spring 4和Hibernate 4,我能够使用Reflection从当前环境中获取Hibernate Configuration对象,使用以下代码:

@Autowired LocalContainerEntityManagerFactoryBean lcemfb;

EntityManagerFactoryImpl emf = (EntityManagerFactoryImpl) lcemfb.getNativeEntityManagerFactory();
SessionFactoryImpl sf = emf.getSessionFactory();
SessionFactoryServiceRegistryImpl serviceRegistry = (SessionFactoryServiceRegistryImpl) sf.getServiceRegistry();
Configuration cfg = null;

try {
    Field field = SessionFactoryServiceRegistryImpl.class.getDeclaredField("configuration");
    field.setAccessible(true);
    cfg = (Configuration) field.get(serviceRegistry);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
    e.printStackTrace();
}

SchemaUpdate update = new SchemaUpdate(serviceRegistry, cfg);
Run Code Online (Sandbox Code Playgroud)

对于Hibernate 5,我必须使用一些MetadataImplementor,这些对象中似乎没有.我还试图用MetadataSourcesserviceRegistry.但它确实说这是错误的ServiceRegistry.

有没有其他方法让这个工作?

java spring hibernate spring-4 hibernate-5.x

21
推荐指数
2
解决办法
7589
查看次数

从另一个异步方法调用的Spring异步方法

我正在使用Spring 4,我注意到一个奇怪的行为......如果我从普通实例方法多次调用异步方法,那么它们都会在不同的线程中调用并随机完成.但是,如果我从另一个异步方法多次调用异步方法,那么它们按顺序完成.我有这样的事情:

@Async
public void nonAsyncMethod() {
  for (int i = 0; i < 30; i++) {
     asyncMethod();
  }
}

@Async
public void asyncMethod() {
   ... something here
}
Run Code Online (Sandbox Code Playgroud)

我正在使用默认的异步执行程序.我应该使用另一个吗?然而,这个执行器不会重复使用任何线程并且每次都启动另一个线程所以它应该没问题......它只是巧合吗?但我尝试过10次以上,如果我恢复到第一种方法的非异步,那么他们会随机完成

java spring multithreading asynchronous spring-4

20
推荐指数
1
解决办法
1万
查看次数

缺少必需的请求正文内容:org.springframework.web.method.HandlerMethod $ HandlerMethodParameter

将JSON数据从JSP传递到ResponseBody中的控制器时出错.

07:13:53.919 DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolving exception from handler [public com.chaitanya.ajax.AjaxResponse com.chaitanya.web.controller.DepartmentController.addDepartment(com.chaitanya.ajax.AjaxResponse)]: 

org.springframework.http.converter.HttpMessageNotReadableException: Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter@98d8d36c
07:13:54.106 DEBUG o.s.w.s.m.a.ResponseStatusExceptionResolver - Resolving exception from handler [public com.chaitanya.ajax.AjaxResponse com.chaitanya.web.controller.DepartmentController.addDepartment(com.chaitanya.ajax.AjaxResponse)]: org.springframework.http.converter.HttpMessageNotReadableException: Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter@98d8d36c
07:13:54.125 DEBUG o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolving exception from handler [public com.chaitanya.ajax.AjaxResponse com.chaitanya.web.controller.DepartmentController.addDepartment(com.chaitanya.ajax.AjaxResponse)]: org.springframework.http.converter.HttpMessageNotReadableException: Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter@98d8d36c
07:1
Run Code Online (Sandbox Code Playgroud)

Ajax调用:

$.ajax({ 
                        url: "/BusinessReimbursment/addDepartment", 
                        method: 'POST', 
                        dataType: 'json', 
                        data: "{\"message\":\"abc\",\"success\":true}",
                        contentType: 'application/json',
                        mimeType: 'application/json',
                        success: function(data) { 
                            alert(data.id + " " …
Run Code Online (Sandbox Code Playgroud)

java ajax json jackson spring-4

20
推荐指数
4
解决办法
10万
查看次数

带有多个DispatcherServlet的Spring Boot,每个都有自己的@Controllers

基本上我想将我的应用程序分成两部分.每个部分都有自己的安全性和自己@Controller的安全性.本@Services应该从两个部分进行访问.

所以我想,我应该得到2 DispatcherServlet.一听,/admin/*第二听其他一切(/).每个都有自己的,AnnotationConfigWebApplicationContext所以我可以对@Controllers 进行单独的组件扫描.

而由于春季启动提供了一个DispatcherServlet监听/开箱,我想,我可以再补充的第二个:

@Configuration
public class MyConfig {
    @Bean(name="myDS")
    public DispatcherServlet myDS(ApplicationContext applicationContext) {
        AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
        webContext.setParent(applicationContext);
        webContext.register(MyConfig2.class);
        // webContext.refresh();
        return new DispatcherServlet(webContext);
    }

    @Bean
    public ServletRegistrationBean mySRB(@Qualifier("myDS") DispatcherServlet dispatcherServlet) {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(dispatcherServlet);
        servletRegistrationBean.addUrlMappings("/admin/*");
        servletRegistrationBean.setName("adminServlet");
        return servletRegistrationBean;
    }
}
Run Code Online (Sandbox Code Playgroud)

这个MyConfig2班,只有@Configuration@ComponentScan.在同一个包中是一个@Controller.

在启动应用程序时,我可以看到第二个servlet映射已经注册,但事实@Controller并非如此.另外,我现在可以从访问所有 . …

spring servlets spring-mvc spring-boot spring-4

18
推荐指数
1
解决办法
2万
查看次数