标签: spring-4

为Spring RESTful应用程序使用ResponseEntity <T>和@RestController时

我正在使用Spring Framework 4.0.7,以及MVC和Rest

我可以和平地工作:

  • @Controller
  • ResponseEntity<T>

例如:

@Controller
@RequestMapping("/person")
@Profile("responseentity")
public class PersonRestResponseEntityController {
Run Code Online (Sandbox Code Playgroud)

用这个方法(只是为了创建)

@RequestMapping(value="/", method=RequestMethod.POST)
public ResponseEntity<Void> createPerson(@RequestBody Person person, UriComponentsBuilder ucb){
    logger.info("PersonRestResponseEntityController  - createPerson");
    if(person==null)
        logger.error("person is null!!!");
    else
        logger.info("{}", person.toString());

    personMapRepository.savePerson(person);
    HttpHeaders headers = new HttpHeaders();
    headers.add("1", "uno");
    //http://localhost:8080/spring-utility/person/1
    headers.setLocation(ucb.path("/person/{id}").buildAndExpand(person.getId()).toUri());

    return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
Run Code Online (Sandbox Code Playgroud)

返回一些东西

@RequestMapping(value="/{id}", method=RequestMethod.GET)
public ResponseEntity<Person> getPerson(@PathVariable Integer id){
    logger.info("PersonRestResponseEntityController  - getPerson - id: {}", id);
    Person person = personMapRepository.findPerson(id);
    return new ResponseEntity<>(person, HttpStatus.FOUND);
}
Run Code Online (Sandbox Code Playgroud)

工作良好

我可以这样做:

  • @RestController(我知道它与@Controller+ …

spring spring-mvc spring-3 spring-4

153
推荐指数
4
解决办法
22万
查看次数

@GetMapping和@RequestMapping(method = RequestMethod.GET)注释之间的区别

@GetMapping和之间有什么区别@RequestMapping(method = RequestMethod.GET)
我在一些Spring Reactive示例中看到过, @GetMapping而不是使用它@RequestMapping

java spring spring-mvc spring-4

130
推荐指数
4
解决办法
9万
查看次数

如何使用@ResponseBody从spring Controller返回JSON数据

Spring版本4.2.0,Hibernate 4.1.4 这是我的Controller功能:

@RequestMapping(value = "/mobile/getcomp", method = RequestMethod.GET)
@ResponseBody
public List<Company>  listforCompanies() {      
    List<Company> listOfCompanies= new ArrayList<Company>();        
    listOfCompanies = companyManager.getAllCompanies();
    return listOfCompanies;
}
Run Code Online (Sandbox Code Playgroud)

杰克逊JSON映射器依赖Pom.xml:

    <!-- Jackson JSON Mapper -->
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>${jackson.version}</version>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

获取列表ArrayList,但返回时会显示以下错误:

SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [/IrApp] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.ArrayList] with root cause
    java.lang.IllegalArgumentException: No converter found for return …
Run Code Online (Sandbox Code Playgroud)

java spring json spring-mvc spring-4

48
推荐指数
5
解决办法
9万
查看次数

为[class org.springframework.web.bind.MethodArgumentNotValidException]映射的不明确的@ExceptionHandler方法

我正在尝试使用@ControllerAdvice处理MethodArgumentNotValidException作为下面给出的代码:

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    private Logger log = LoggerFactory.getLogger(RestResponseEntityExceptionHandler.class);

    @Autowired
    private ApplicationContext applicationContext;

    @ExceptionHandler({ ConstraintViolationException.class })
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorWrapper handleConstraintViolationException(ConstraintViolationException e) {
        String fieldName = e.getConstraintName();
        String message = getResourceMessage(fieldName + ".alreadyExists", "Already Exists");
        return new ErrorWrapper(fieldName + ".error", message);
    }

    @ExceptionHandler({ MethodArgumentNotValidException.class })
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorWrapper handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return new ErrorWrapper(".error", "test");
    }

    private String getResourceMessage(String key, String defaultMessage) {
        String message = applicationContext.getMessage(key, null, Locale.getDefault());
        if (StringUtils.isNotEmpty(message)) {
            return message;
        } …
Run Code Online (Sandbox Code Playgroud)

spring-4

43
推荐指数
3
解决办法
2万
查看次数

@EntityScan和@ComponentScan之间的区别

我试图了解这里的区别.我看到一个类已经使用相同的包示例注释了它们:

@Configuration
@EntityScan("some.known.persistence")
@ComponentScan({ "some.known.persistence"})
public class ApiConfig {

}
Run Code Online (Sandbox Code Playgroud)

我理解与API文档的不同之处,但希望详细了解.这也意味着扫描的任何东西@ComponentScan都具有更广泛的可见性和Spring背景,而@EntityScan不是.如果这样使用某些属性@ComponentScan应该已经足够需要在JPA上下文中绑定,不是吗?

spring-annotations spring-boot spring-4 java-annotations

43
推荐指数
1
解决办法
3万
查看次数

何时使用AbstractAnnotationConfigDispatcherServletInitializer和WebApplicationInitializer?

我正在使用Spring 4.0.7

我通过JavaConfig对配置Spring MVC进行了研究.

实际上直到昨天我已经看到使用这两个选项的两种配置

  1. 扩展AbstractAnnotationConfigDispatcherServletInitializer
  2. 扩展WebMvcConfigurerAdapter 实现WebApplicationInitializer

注意:(2)是两个类,一个用于扩展,另一个用于实现

我正在使用(2)因为我找到了很多例子,我可以配置转换器,格式化程序,资源处理程序等...

但是在最近的几天里,我试图帮助StackOverflow上的一个问题,我确实认识到(1)存在..我在Google上做了一些关于(1)的概述,并且存在一些与(1)一起工作的例子

我的问题是这篇文章的标题如何描述.

谢谢

spring spring-mvc spring-3 spring-4

42
推荐指数
2
解决办法
3万
查看次数

在Tomcat 6中部署Spring 4.0的AbstractMethodError

我在Tomcat 6.0.37中部署Spring 4.0.1应用程序时遇到异常:

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.AbstractMethodError: org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultParameterNameProvider()Ljavax/validation/ParameterNameProvider;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:943)
    at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:778)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:504)
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1317)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:324)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142) …
Run Code Online (Sandbox Code Playgroud)

spring tomcat tomcat6 hibernate-validator spring-4

40
推荐指数
1
解决办法
3万
查看次数

如何在Spring MVC中使用JasperReports?

我一直在调查使用JasperReports(6.0.0)和Spring MVC(4.1.3)来生成PDF报告.Spring充斥着"Spring特定"方式与JasperReports集成以生成PDF:

我努力在网上找到好的,完整的例子,并想分享我的发现(见下面的答案).

随意添加与"如何将JasperReports与Spring4集成"相关的其他方法和/或改进?

java spring spring-mvc jasper-reports spring-4

37
推荐指数
1
解决办法
5万
查看次数

多个场景@RequestMapping与Accept或ResponseEntity一起生成JSON/XML

我正在使用Spring 4.0.7

关于Spring MVC,出于研究目的,我有以下内容:

@RequestMapping(value="/getjsonperson", 
                method=RequestMethod.GET, 
                produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Person getJSONPerson(){
    logger.info("getJSONPerson - getjsonperson");
    return PersonFactory.createPerson();
}

@RequestMapping(value="/getperson.json", method=RequestMethod.GET)
public @ResponseBody Person getPersonJSON(){
    logger.info("getPerson - getpersonJSON");
    return PersonFactory.createPerson();
}
Run Code Online (Sandbox Code Playgroud)

每个都工作正常,观察JSON,有和没有扩展:

  • / getjsonperson
  • /getperson.json

对于XML也是如此

@RequestMapping(value="/getxmlperson",
                method=RequestMethod.GET,
                produces=MediaType.APPLICATION_XML_VALUE
                )
public @ResponseBody Person getXMLPerson(){
    logger.info("getXMLPerson - getxmlperson");
    return PersonFactory.createPerson();
}

@RequestMapping(value="/getperson.xml", method=RequestMethod.GET)
@ResponseBody
public Person getPersonXML(){
    logger.info("getPerson - getpersonXML");
    return PersonFactory.createPerson();
}
Run Code Online (Sandbox Code Playgroud)

每个都工作正常,观察XML,有和没有扩展:

  • / getxmlperson
  • /getperson.xml

现在关于Restful我有以下内容:

@RequestMapping(value="/person/{id}/", 
                method=RequestMethod.GET,
                produces={MediaType.APPLICATION_JSON_VALUE, 
                          MediaType.APPLICATION_XML_VALUE})
public ResponseEntity<Person> getPersonCustomizedRestrict(@PathVariable Integer id){
    Person person = personMapRepository.findPerson(id); …
Run Code Online (Sandbox Code Playgroud)

rest spring spring-mvc spring-3 spring-4

36
推荐指数
1
解决办法
12万
查看次数

WebSocket与Sockjs和Spring 4但没有Stomp

有没有办法将WebSockets与SockJS客户端和Spring 4服务器一起使用但不使用STOMP?

基于Spring网站的这个教程,我知道如何使用Stomp和Spring 4设置基于WebSocket的应用程序.在客户端,我们有:

     var socket = new SockJS('/hello');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function(frame) {
            setConnected(true);
            console.log('Connected: ' + frame);
            stompClient.subscribe('/topic/greetings', function(greeting){
                showGreeting(JSON.parse(greeting.body).content);
            });
        });
Run Code Online (Sandbox Code Playgroud)

在服务器端,我们在控制器中有以下内容:

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
    Thread.sleep(3000); // simulated delay
    return new Greeting("Hello, " + message.getName() + "!");
}
Run Code Online (Sandbox Code Playgroud)

现在,据我所知,@MessageMapping("/hello")确保如果将消息发送到目标"/hello",则将greeting()调用该方法.并且由于stompClient订阅了"/topic/greetings",所以@SendTo("/topic/greetings")会将消息发送回stompClient.

但是上面的问题是stompClient是一个Stomp对象.我想简单地使用sock.send('test');并将其发送到我的服务器目的地.我想做@SendTo("myownclientdestinationmap"),我可以收到它

sock.onmessage = function(e) {
     console.log('message', e.data);
 };
Run Code Online (Sandbox Code Playgroud)

那么,使用Spring 4,SockJS和没有Stomp的任何方法都可以做到这一点?或者Spring 4 WebSocket只支持Stomp?

java websocket sockjs spring-4

33
推荐指数
1
解决办法
2万
查看次数