我是Spring MVC的新手,并尝试使用AngularJS和SpringMVC(Uisng Maven和Eclipse)构建一个基本的hello world示例。 在浏览了一些关于互联网的教程后,我做了以下事情
Web MVC配置
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars/**").addResourceLocations("/webjars/")
.resourceChain(false)
.addResolver(new WebJarsResourceResolver())
.addResolver(new PathResourceResolver());
}
}
Servlet初始化程序
public class SampleInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { WebMvcConfig .class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Filter[] getServletFilters() {
Filter [] singleton = { new CORSFilter() };
return singleton;
}
}
CORS过滤器
public class CORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
SampleController:
@RestController
public class SampleController {
@RequestMapping(path = "/sample", method = RequestMethod.GET)
public List<String> listUsers() {
List<String> result = new ArrayList<>();
result.add("user1");
return result;
}
}
Webapp结构
angular
.module('app', ['ngRoute', 'ngCookies' ,'ngTable'])
.config(config)
.run(run);
config.$inject = ['$routeProvider', '$locationProvider'];
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'home/home.view.html',
controllerAs: 'vm'
})
.when('/login', {
controller: 'LoginController',
templateUrl: 'login/login.view.html',
controllerAs: 'vm'
})
Tomcat设置:
由于没有WEB-INF / web.xml,我已将其删除 tomcat-8 \ conf \ context.xml
<!-- Default set of monitored resources. If one of these changes, the-->
<!-- web application will be reloaded.-->
<!--<WatchedResource>WEB-INF/web.xml</WatchedResource>-->
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
在tomcat-8 \ conf \ web.xml中,我看到index.html被称为欢迎文件
当我将我的应用程序部署到tomcat时,它能够显示index.html并且由于我的路由代码,它能够路由到login.html。但是当我尝试访问其余服务时,它会显示404 HTTP状态。
我需要在某处保留其他设置吗? 我已经重新检查了我的RestService代码,这似乎对我来说是正确的。我也检查了tomcat日志,它也没有显示任何错误。
如果可能的话,请您指点一下使用AngularJS和基于Spring的Rest服务(使用maven)的一步一步的教程