欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringDataJpa杂记(二) SpringMVC与SpringDataJpa小集成

程序员文章站 2022-06-22 09:46:32
...
零) 代码
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/c")
public class TestController {

	@ResponseBody
	@RequestMapping(value = "/t1", method = RequestMethod.GET)
	// http://localhost:8080/c/t1?page.page=2&page.size=50&page.sort=email&page.sort.dir=desc
	public Object test1(Pageable pageable) {
		PageRequest p = (PageRequest) pageable;
		System.out.println(p.getPageNumber() + " " + p.getPageSize() + " " + p.getSort());
		return "OK";
	}
	
	@ResponseBody
	@RequestMapping(value = "/t2/{id}", method = RequestMethod.GET)
	// http://localhost:8080/c/t2/1
	public Object test2(@PathVariable("id") User user) {
		return user;
	}

}


一) Web Pagination
代码参考上面的 test1()
这需要一个WebArgumentResolver实现,这个接口我还第一次注意,MethodArgumentResolver用过,两者用法大同小异。
<mvc:annotation-driven>
	<mvc:message-converters>
		<!-- ... -->
	</mvc:message-converters>
	<mvc:argument-resolvers>
		<!-- 配置 -->
		<bean class="org.springframework.data.web.PageableArgumentResolver" />
	</mvc:argument-resolvers>
</mvc:annotation-driven>


二) Domain class web binding for Spring MVC
代码参考上面 test2()
与Web Pagination 不同,这里不是使用的WebArgumentResolver或MethodArgumentResolver,而是注册PropertyEditor,
注册时这两个bean放在root上下文之中
<bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
	<property name="converters">
		<util:set>
		</util:set>
	</property>
	<property name="formatters">
		<util:set>
		</util:set>
	</property>
</bean>

<bean class="org.springframework.data.repository.support.DomainClassConverter">
	<constructor-arg ref="conversion-service" />
</bean>