标签: spring-3

多个场景@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万
查看次数

org.hibernate.HibernateException:找不到当前线程的Session

我在Spring3和Hibernte4上遇到了上述异常

以下是我的bean xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

   <context:annotation-config/>


   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
      <property name="url" value="jdbc:mysql://localhost:3306/GHS"/>
      <property name="username" value="root"/>
      <property name="password" value="newpwd"/>
  </bean>

  <bean id="sessionFactory"
      class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="hibernateProperties">
        <props>
            <prop key="dialect">org.hibernate.dialect.MySQL5Dialect</prop>
        </props>
    </property>
    <property name="packagesToScan">
        <list>
            <value>com.example.ghs.model.timetable</value>
        </list>
    </property>
  </bean>

   <bean id="baseDAO"
      class="com.example.ghs.dao.BaseDAOImpl"/>
</beans>
Run Code Online (Sandbox Code Playgroud)

我的BaseDAO类看起来像这样

public class BaseDAOImpl implements BaseDAO{
private SessionFactory sessionFactory;

 @Autowired
 public BaseDAOImpl(SessionFactory sessionFactory){
     this.sessionFactory = sessionFactory;
 }

 @Override
 public Session getCurrentSession(){ …
Run Code Online (Sandbox Code Playgroud)

spring hibernate spring-3 hibernate-4.x

33
推荐指数
3
解决办法
6万
查看次数

带有Spring RequestMapping路径参数的编码斜杠(%2F)提供HTTP 400

这不是重复引用的问题,因为它是特定于Spring的.无论谁添加了(事实发生3年后!)都没有费心去阅读问题或评论帖子,看看真正的答案是什么.接受的答案并不是答案,但答案的作者从未回过头来编辑它,就像我问的那样.

鉴于下面的restful方法,Spring 3.1给出了400错误,"客户端发送的请求在语法上是不正确的()".当token参数包含URL编码的斜杠(%2F)时,例如" https://somewhere.com/ws/stuff/lookup/resourceId/287559/token/R4o6lI%2FbBx43/userName/jim "没有%2F一切正常精细.第三方已经在调用此服务(当然!)因此我至少在短期内无法更改发送的内容.有关如何在服务器端解决此问题的任何想法?

这个问题在https://jira.springsource.org/browse/SPR-8662中得到了很好的描述,尽管这个问题与UriTemplate有关,我没有使用它,我可以说.

@RequestMapping("/ws/stuff/**")
@Controller
public class StuffController {
  @RequestMapping(value = "/ws/stuff/lookup/resourceId/{resourceId}/token/{token}/userName/{userName}", method = RequestMethod.GET)
   public @ResponseBody
   String provisionResource(@PathVariable("resourceId") String resourceId, @PathVariable("token") String token, @PathVariable("userName") String userName, ModelMap modelMap,
         HttpServletRequest request, HttpServletResponse response) {
      return handle(resourceId, userName, request, token, modelMap);
   }
}
Run Code Online (Sandbox Code Playgroud)

注意:这是在Glassfish 3.1.2上,最初是Grizzly/Glassfish不接受斜线,但是

-Dcom.sun.grizzly.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true

修好了.

asadmin set configs.config.server-config.network-config.protocols.protocol.http-listener-2.http.encoded-slash-enabled=true

似乎没有帮助.

rest spring glassfish glassfish-3 spring-3

33
推荐指数
7
解决办法
4万
查看次数

Spring MVC的REST框架可以接受查询字符串而不是PathVariables吗?

在我阅读的关于Spring 3的Spring MVC的RESTful添加的所有教程和文章中,我只看到过一种方法,用于通过a传递查询数据@PathVariable,如下所示:

@RequestMapping(value="/shops/{name}", method=RequestMethod.GET)
public @ResponseBody Shop getShopInJSON(@PathVariable String name) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

这将回应类似的东西http://www.example.com/myservlet/shops/{name},可以评估http://www.example.com/myservlet/shops/thebestshoparound.

我的问题是:是否可以设置一个RESTful接口,它接受基于经典查询字符串的请求,例如http://www.example.com/myservlet/shops?name=thebestshoparound,而不是PathVariables

这似乎是一个非常简单的问题,但我无法在网上找到它.

path-variables spring-mvc query-string spring-3

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

如果找不到,@ PathVariable可以返回null吗?

@PathVariable如果路径变量不在url中,是否可以使返回null?否则我需要做两个处理程序.一个用于/simple另一个/simple/{game},但两者都做同样的事情,如果没有定义游戏我从列表中选择第一个然而如果有游戏参数定义然后我使用它.

@RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
public ModelAndView gameHandler(@PathVariable("example") String example,
            HttpServletRequest request) {
Run Code Online (Sandbox Code Playgroud)

这是我在尝试打开页面时得到的/simple:

引起:java.lang.IllegalStateException:在@RequestMapping中找不到@PathVariable [example]

java path-variables spring-annotations spring-3

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

带有2个事务管理器的@EnableTransactionManagement注释

我正在使用@Configuration注释来配置spring而不是xml文件.我正在配置具有不同会话工厂和不同事务管理器的2个数据源.我在这里遇到了一个@EnableTransactionManagement注释问题.我在其文档中读到,

@EnableTransactionManagement更灵活; 它将回退到PlatformTransactionManager容器中任何bean 的类型查找.因此,名称可以是"txManager","transactionManager"或"tm":它无关紧要.

这意味着我给方法的任何名称,它总是会搜索返回PlatformTransactionManager对象的方法,而我有2个transactionmanagers.现在问题是,当我测试这个类时,它给了我错误:

org.springframework.beans.factory.NoSuchBeanDefinitionException:没有org.springframework.transaction.PlatformTransactionManager定义类型为[ ]的唯一bean :期望的单个bean但找到2

我甚至试图拥有2个不同的配置类但是徒劳无功.在xml配置中,情况并非如此.我用两个<tx:annotation-driven transaction-manager="" />标签注册了我的两个交易管理器,它运行正常.但是这里不能用注释做同样的事情.

如果我想在Spring注释配置类中配置2个具有2个不同事务管理器的数据源,我该怎么办?

java spring spring-annotations spring-3

27
推荐指数
3
解决办法
4万
查看次数

使用FileSystemResource强制文件下载文件时如何设置'Content-Disposition'和'Filename'?

设置Content-Disposition=attachmentfilename=xyz.zip使用Spring 3 的最合适,最标准的方法是FileSystemResource什么?

该动作如下:

@ResponseBody
@RequestMapping(value = "/action/{abcd}/{efgh}", method = RequestMethod.GET, produces = "application/zip")
@PreAuthorize("@authorizationService.authorizeMethod()")
public FileSystemResource doAction(@PathVariable String abcd, @PathVariable String efgh) {

    File zipFile = service.getFile(abcd, efgh);

    return new FileSystemResource(zipFile);
}
Run Code Online (Sandbox Code Playgroud)

虽然该文件是一个zip文件,因此浏览器总是下载该文件,但我想明确提到该文件为附件,并提供与文件实际名称无关的文件名.

可能有解决此问题的方法,但我想知道正确的Spring和FileSystemResource实现此目标的方法.

PS此处使用的文件是临时文件,在JVM存在时标记为删除.

java spring content-disposition spring-3

27
推荐指数
4
解决办法
5万
查看次数

Spring的@Scheduled错误:上下文中只能存在一个AsyncAnnotationBeanPostProcessor

我正在尝试Spring 3的@Scheduled注释.这是我的配置(app.xml):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:task="http://www.springframework.org/schema/task"
  xsi:schemaLocation="
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
      http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
      "
>

  <context:component-scan base-package="destiny.web"/>  
  <context:annotation-config/>
  // other beans

  <task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
  <task:executor  id="myExecutor"  pool-size="5"/>
  <task:scheduler id="myScheduler" pool-size="10"/>
</beans>
Run Code Online (Sandbox Code Playgroud)

这是我的服务类:

@Service
public class ServiceImpl implements Service , Serializable
{
  //other injections

  @Override
  @Transactional
  public void timeConsumingJob()
  {
    try
    {
      Thread.sleep(10*1000);
    }
    catch (InterruptedException e)
    {
      e.printStackTrace();
    }
  }

  @Override
  @Scheduled(cron="* * * * * ?") 
  public void secondly() …
Run Code Online (Sandbox Code Playgroud)

spring scheduler crontrigger spring-3

25
推荐指数
4
解决办法
3万
查看次数

名为"XXX"的组件已在JBoss 7.1.1的此模块中定义

我没有TimerServiceDispatcher在我的应用程序中创建spring bean名称.但是,JBoss抛出异常因为TimerServiceDispatcher已在此模块中定义.我不知道是什么问题.我错过了什么?我需要做什么?

我的应用程序使用Seam 2.3,Spring 3.0和JPA 2.0.我不用EJB.

11:29:01,531 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015876: Starting deployment of "MRBS.war"
11:29:04,217 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-5) MSC00001: Failed to start service jboss.deployment.unit."MRBS.war".PARSE: org.jboss.msc.service.StartExcept
ion in service jboss.deployment.unit."MRBS.war".PARSE: Failed to process phase PARSE of deployment "MRBS.war"
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:119) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) [rt.jar:1.6.0_23]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [rt.jar:1.6.0_23]
    at java.lang.Thread.run(Unknown Source) [rt.jar:1.6.0_23]
Caused by: java.lang.IllegalArgumentException: JBAS011046: A component named …
Run Code Online (Sandbox Code Playgroud)

java jboss spring spring-3 jboss7.x

24
推荐指数
6
解决办法
2万
查看次数

Spring 3 @ImportResource包含多个文件

我正在尝试使用Spring 3 @ImportResource注释找到导入多个spring xml上下文文件的语法.

我尝试使用逗号分隔文件名,如下图所示,但这不起作用:

@Configuration
@ImportResource("spring-context1.xml", "spring-context2.xml")
public class ConfigClass { }
Run Code Online (Sandbox Code Playgroud)

@ImportResource的文档说"表示包含要导入的bean定义的一个或多个资源".所以我认为应该有一种方法来指定多个上下文文件.令人惊讶的是,我无法在Google上找到任何示例

java spring spring-3

24
推荐指数
2
解决办法
5万
查看次数