Tag: spring mvc

如何使用注释自动assemblyRestTemplate

当我尝试自动assemblySpring RestTemplate时,我收到以下错误: nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.client.RestTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. 在注释驱动的环境中使用Spring 4。 我的调度程序servlet配置如下: 我尝试自动assemblyRestTemplate的课程如下: @Service(“httpService”) public class HttpServiceImpl implements HttpService { @Autowired private RestTemplate restTemplate; @Override public void sendUserId(String userId){ MultiValueMap map = new LinkedMultiValueMap(); map.add(“userId”, userId); […]

用于弹簧拦截器的Java配置拦截器使用自动assembly的弹簧豆

我想添加spring mvc拦截器作为Java配置的一部分。 我已经有了一个基于xml的配置,但我正在尝试转向Java配置。 对于拦截器,我知道可以从弹簧文档中这样做 – @EnableWebMvc @Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LocaleInterceptor()); } } 但我的拦截器正在使用一个自动装入它的弹簧豆,如下所示 – public class LocaleInterceptor extends HandlerInterceptorAdaptor { @Autowired ISomeService someService; … } SomeService类如下所示 – @Service public class SomeService implements ISomeService { … } 我正在使用像@Service这样的注释来扫描bean,并且没有在配置类@Bean它们指定为@Bean 据我所知,由于java config使用new来创建对象,spring不会自动将依赖项注入其中。 我如何添加这样的拦截器作为java配置的一部分?

Spring RestTemplate处理状态为NO_CONTENT的响应时的行为

好的,我有一个名为NamedSystems的类,它的唯一字段是一组NamedSystem。 我有一种方法可以通过某些标准找到NamedSystems。 那不是很重要。 当它得到结果时,一切正常。 但是,当它找不到任何东西,从而返回null(或空 – 我已尝试过两种方式)设置时,我就会遇到问题。 让我解释。 我正在使用Spring RestTemplate类,我在unit testing中进行这样的调用: ResponseEntity responseEntity = template.exchange(BASE_SERVICE_URL + “? alias={aliasValue}&aliasAuthority={aliasAssigningAuthority}”, HttpMethod.GET, makeHttpEntity(“xml”), NamedSystems.class, alias1.getAlias(), alias1.getAuthority()); 现在,因为这通常会返回200,但我想返回204,我的服务中有一个拦截器,它确定ModelAndView是否是NamedSystem,如果它的set是null。 如果是,我然后将状态代码设置为NO_CONTENT(204)。 当我运行junit测试时,我收到此错误: org.springframework.web.client.RestClientException: Cannot extract response: no Content-Type found 将状态设置为NO_CONTENT似乎擦除了内容类型字段(当我考虑它时确实有意义)。 那为什么还要看呢? Spring的HttpMessageConverterExtractor extractData方法: public T extractData(ClientHttpResponse response) throws IOException { MediaType contentType = response.getHeaders().getContentType(); if (contentType == null) { throw new […]

具有error handling的Spring MVC Rest服务控制器正确完成了吗?

我想知道如何正确实现一个应该作为REST服务的Spring Controller。 特别是我想尝试使界面尽可能的RESTful。 此外,我想使用HTTP错误代码,以便我的客户端可以采取相应的行动。 我想知道如何实现我的方法,所以他们返回JSON如果一切正常(在响应的主体中)或抛出一个http错误代码以及一个自定义原因它为什么它不起作用(可能是来自DAO的错误或数据库)。 但是我不确定哪一个是正确的方法? 返回一个String并添加值以返回Model,或者返回一个HashMap并将我的东西放在那里? 或直接返回对象? 但那么如果发生错误并且我无法返回所述类怎么办? 返回null而不是? 我发布了2-3种可以想象的方法: @RequestMapping(value=”/addUser”, method= RequestMethod.POST) public String addUser(@RequestBody User user, HttpServletResponse response, Model model) throws Exception{ try{ userService.addUser(user); model.addAttribute(“user”, userService.getUser(user.getUsername(), user.getPassword())); return “user”; }catch(Exception e){ model.addAttribute(“error”, e.toString()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return “error”; } } 或者更确切地说: @RequestMapping(value=”/addUser”, method= RequestMethod.POST) public @ResponseBody Map addUser(@RequestBody User user, HttpServletResponse response){ Map […]

是否可以扩展WebMvcConfigurationSupport并使用WebMvcAutoConfiguration?

我需要扩展WebMvcConfigurationSupport类,修改两件事: @Configuration public class WebConfig extends WebMvcConfigurationSupport { @Override public RequestMappingHandlerMapping requestMappingHandlerMapping() { RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping(); handlerMapping.setRemoveSemicolonContent(false); handlerMapping.setOrder(1); return handlerMapping; } } 我喜欢从WebMvcAutoConfiguration类注册的默认值,但由于类上的条件注释,当我扩展WebMvcConfigurationSupport类时,它会阻止自动配置发生。 @Configuration @ConditionalOnWebApplication @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurerAdapter.class }) @ConditionalOnMissingBean(WebMvcConfigurationSupport.class) @Order(Ordered.HIGHEST_PRECEDENCE + 10) @AutoConfigureAfter(DispatcherServletAutoConfiguration.class) public class WebMvcAutoConfiguration {…} 是否要加载WebMvcAutoConfiguration类而不必实际复制/粘贴该类中的大多数代码? 或者是否可以从其他地方调用RequestMappingHandlerMapping setOrder()和setRemoveSemicolonContent(),这样我就可以使用@EnableWebMvc注释并运行自动配置类而没有任何问题? 提前致谢!

启用S​​pring安全性时,无法加载资源(css或js)

资源在src / main / resources / static / css或src / main / resources / static / js下,我使用的是spring boot,安全类是: @Configuration @EnableWebMvcSecurity @EnableGlobalAuthentication public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // http.authorizeRequests().antMatchers(“/”, “/index”, “/quizStart”) // .permitAll().anyRequest().authenticated(); // http.formLogin().loginPage(“/login”).permitAll().and().logout() // .permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser(“test”).password(“test”) […]

Spring MVC:将请求属性绑定到控制器方法参数

在Spring MVC中,很容易将请求参数绑定到处理请求的方法参数。 我只是使用@RequestParameter(“name”) 。 但是我可以对请求属性执行相同的操作吗? 目前,当我想访问请求属性时 ,我必须执行以下操作: MyClass obj = (MyClass) request.getAttribute(“attr_name”); 但我真的想用这样的东西代替: @RequestAttribute(“attr_name”) MyClass obj 不幸的是,它没有这种方式。 我可以以某种方式扩展Springfunction并添加我自己的“绑定器”吗? 编辑 (我想要实现的目标) :我将当前登录的用户存储在请求属性中。 因此,每当我想访问当前登录的用户(这几乎都在每个方法内)时,我必须写这个额外的行user = (User) request.getAttribute(“user”); 。 我想尽量缩短它,最好将它作为方法参数注入。 或者如果你知道如何通过拦截器和控制器传递某些东西,我会很高兴听到它。

使用Spring MVC HandlerInterceptorAdapter从HttpServletResponse记录响应主体(HTML)

我正在尝试记录(仅为了简单起见,现在是控制台写入)最终呈现的HTML将由HttpServletResponse返回。 (即正文)为此,我使用Spring MVC中的HandlerInterceptorAdapter,如下所示: public class VxmlResponseInterceptor extends HandlerInterceptorAdapter { @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println(response.toString()); } } 这按预期工作,我在控制台中看到HTTP响应标头。 我的问题是,是否有一种相对简单的方法可以将整个响应体(即最终呈现的HTML)记录到控制台,而无需使用PrintWriters,OutputStream等进行跳跃。 提前致谢。

值’0000-00-00’不能表示为java.sql.Date

我正在研究一些需要从数据库中提取数据的项目,我使用Spring MVC从DB构建模型来选择数据。 这是我的JSP页面的问题: Date to select: Name to select: Type to select: –SELECT– –SELECT– –SELECT– 如您所见,我尝试使用Spring标记库中的 。 题: 但是当它用这个控制器准备我的模型时: @Controller public class HomeController{ @Autowired private ControllerSupportClass controllerSupportClass; @RequestMapping(value=”/search”, method=RequestMethod.GET) public String search(Model model) { List listOfDates = controllerSupportClass.findAllDatesForm(); List listOfInstitutionsNames = controllerSupportClass.findAllInstitutionsForm(); List listOfInstitutionsTypes = controllerSupportClass.findAllTypesForm(); model.addAttribute(“listOfInstitutionsTypes”, listOfInstitutionsTypes); model.addAttribute(“listOfInstitutionsNames”, listOfInstitutionsNames); model.addAttribute(“listOfDates”, listOfDates); return “search”; } […]

Spring中的ConversionService

我在Spring应用程序中遵循此方案。 请求被发送到服务器,其中包含对象的id以及要在此对象中填充的其他一些参数 具有此id的对象从数据库加载 在此对象中调用getter和setter以填充值 然后存储该对象 我在另一个问题中询问,在填充请求的参数之前,准备对象的最佳方法是什么。 答案是最好的方法是使用转换服务而不是在@ModelAtribute注释方法中或在initBinder中使用编辑器。 所以我试图使用转换器,但我没有找到类似的例子,我有点卡住了。 我编写了如下代码:在init binder中我注册了转换服务。 因此,在填充User对象上的值之前,会调用convert()方法从数据库加载对象。 问题是这个配置不起作用,因为它将对象用户的id(用户名字段)转换为Object用户,但是它尝试用对象创建一个setUsername(),所以我得到一个“java.lang” .IllegalArgumentException:参数类型不匹配“。 任何人都可以给我一个线索或使用ConversionService获得所需行为的方法的示例吗? 谢谢。 @Autowired private ConversionService conversionService; @InitBinder(“user”) public void initBinder(@RequestParam(“username”)String username, WebDataBinder binder){ binder.setConversionService(conversionService); } @RequestMapping(value=”/user/save”, method=RequestMethod.POST) public String save(@ModelAttribute(“user”) User user, Model model) { … } 有类似的东西: @Component public class UserConversionService implements ConversionService{ … @Override public Object convert(Object name, TypeDescriptor arg1, […]