我正在使用Spring和基于注释的配置来处理POC。在努力的同时,我面临以下问题:
当我使用调度程序servlet映射为/
时,我可以访问控制器但不能访问html页面。
当我将映射更改为/**
时,我可以访问html页面而不是控制器。
我不确定是否应该添加另一个调度程序servlet并在其中添加一个映射。我也试过在调度程序servlet中传递两个映射,但它没有工作。
也许有人可以帮我解决这个问题。
以下是代码:
的AppConfig
package com.upload.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import(WebConfig.class)
@ComponentScan(basePackages= "com.upload")
public class AppConfig {
}
WebConfig
package com.upload.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter{
}
ServletInitializer
public class ServletInitializer extends AbstractDispatcherServletInitializer {
@Override
protected WebApplicationContext createServletApplicationContext() {
final AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);
context.getEnvironment().setActiveProfiles("prod");
return context;
}
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
}
FileUploadController
@Controller
@RequestMapping("/ws")
public class FileUploadController {
@RequestMapping(value="hello",method=RequestMethod.GET)
public String hello(){
return "Hello";
}
}
答案 0 :(得分:3)
使用以下方法: 您需要添加addResourceHandler以从web-inf结构WEB-INF / views / viewer中获取html页面,其中包含所有页面:js / html / css / images等。您可以删除上面显示的AppConfig .java。
package com.Configuration.si.config;
@Configuration
@ComponentScan("com.Configuration.si")
@EnableWebMvc
public class Configuration extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/viewer/**","/lib/**","/js/**","/images/**","/css/**","/swf/**")
.addResourceLocations("/WEB-INF/views/viewer/","/WEB-INF/views/lib/","/WEB-INF/views/js/","/WEB-INF/views/images/","/WEB-INF/views/css/","/WEB-INF/views/swf/")
.setCachePeriod(315569126);
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
同时将此类添加到您的结构
package com.Configuration.si.config;
@Configuration
public class WebMvcConfiguration {
@Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setViewClass(JstlView.class);
internalResourceViewResolver.setPrefix("/WEB-INF/views/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
}
内部视图解析器将使用model.setViewName(“login”)解析您需要的页面;在控制器中。希望它能帮到你