当我尝试从AngularJS调用RESTful Web服务时,我找不到404响应。以下是代码示例:
WebAppConfiguration.java
public class WebAppConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/");
viewResolver.setSuffix(".html");
registry.viewResolver(viewResolver);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/app/**").addResourceLocations("/app/");
}
}
WebAppInitializer.java
public class WebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebBeanConfig.class);
ctx.setServletContext(servletContext);
DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("mvc-dispatcher", dispatcherServlet);
servlet.addMapping("/");
servlet.setAsyncSupported(true);
servlet.setLoadOnStartup(1);
}
}
WebBeanConfig.java
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.rvc.releaseSessionDemo")
public class WebBeanConfig {
}
SessionController.java
@RestController
@RequestMapping("/session")
public class SessionController {
@Autowired
private ISessionService sessionService;
@RequestMapping(value = "/releaseSession", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Boolean> releaseSession(@RequestBody String sessionId) throws Exception {
Boolean response = sessionService.releaseSession(sessionId());
return new ResponseEntity<Boolean>(response, HttpStatus.OK);
}
}
session.service.js
angular.module('session', []).factory('sessionService', ['$http', '$q', sessionService]);
function sessionService($http, $q) {
return {
releaseSession : releaseSession
}
function releaseSession(sessionId) {
var deferred = $q.defer();
var req = {sessionId : sessionId};
$http.post('session/releaseSession', req).then(function(response) {
deferred.resolve(response.data);
}, function(errorResponse) {
deferred.reject(errorResponse);
});
return deferred.promise;
}
}
答案 0 :(得分:0)
你应该使用@ResponseBody
的包装类。
使用类似的东西:
public class Session {
private String sessionId;
//getter setter
}
并将其传递给控制器@RequestBody Session session
。然后,您可以通过getter获取会话ID。
答案 1 :(得分:0)
我想回答这个问题。
问题是servlet映射,即&#34; /&#34;仅适用于基于XML的配置。如果我们使用基于注释的配置,那么servlet映射应该是&#34; / *&#34;在初始化类中。
<强> servlet.addMapping(&#34; / *&#34); 强>