下面是我的Spring RestController实现的通用版本。其目的是使用基于URI ID输入的资源响应特定基URI(“/ rest / my / uri / to / resource”)的HTTP请求。它工作正常,但由于它返回的数据的结构,我不得不添加一个可选的日期参数。我让控制器计算今天的日期,并在用户不在URI中提供日期时在我的数据库查询中使用它。
我的问题是,如果我在每个响应中使用todaySqlDate
变量,而用户不提供日期,我会在每次响应请求时重新计算日期吗?显然,如果用户输入类似
/rest/my/uri/to/resource/identifier/666?date=2016-03-15
这不是问题。我担心的是,当日期不包括在内时,la
/rest/my/uri/to/resource/identifier/666
它将使用默认日期。如果服务运行超过24小时,默认日期是否会停止当前?
@RestController
@RequestMapping(value = "/rest/my/uri/to/resource")
public class ResourceController
{
private static final Logger LOGGER = LoggerFactory.getLogger(ResourceController.class);
@Autowired
private ResourceService resourceService;
public String todaySqlDate = getTodaySqlDate();
@RequestMapping(value = "/identifier/{id}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public Resource getResource(@PathVariable("id") String id,
@RequestParam(value="date", defaultValue="", required=false) String resourceDate)
throws InvalidParameterException, DataNotFoundException, Exception
{
LOGGER.trace("In ResourceController.getResouce() with {}", id);
try
{
if(!isValidIdentifier(id))
{
throw new InvalidParameterException("id is not valid: " + id);
}
if(resourceDate.isEmpty())
{
resourceDate = todaySqlDate;
}
else if(!isValidSqlDateString(resourceDate))
{
throw new InvalidParameterException("resourceDate is present but not valid: " + resourceDate);
}
ResourceList resourceList = resourceService.getResource(id, resourceDate);
if (resourceList == null)
{
LOGGER.trace("No resources found for given input");
throw new DataNotFoundException("ResourceList for " + id + " not found");
}
return resourceList;
}
catch (Exception e)
{
LOGGER.error(e.getMessage(), e);
throw e;
}
}
public String getTodaySqlDate()
{
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
return sqlDate.toString();
}
}
答案 0 :(得分:1)
是的,每个新请求都将由一个新的单独实例(线程)处理,因此每次都会重新计算日期。
您可以查看Spring / REST文档以获取更多信息。