Skip to content

Instantly share code, notes, and snippets.

@jacobheric
Created March 13, 2011 14:54
Show Gist options
  • Save jacobheric/868144 to your computer and use it in GitHub Desktop.
Save jacobheric/868144 to your computer and use it in GitHub Desktop.
An annotated spring mvc controller snippet offering restful json services
@Controller
@RequestMapping(value="/recipe")
public class RecipeController extends BaseController implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(RecipeController.class);
@Autowired
private IRecipeService recipeService;
@Autowired
private IYeastService yeastService;
/**
* Default constructor
*/
public RecipeController() {
}
@RequestMapping(method = {RequestMethod.GET})
public @ResponseBody ServiceResultWrapper<Recipe> SearchRecipes(@ModelAttribute RecipeCriteria criteria)
{
return new ServiceResultWrapper(this.recipeService.search(criteria), true, "Search successful", criteria.getTotal());
}
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody ServiceResultWrapper<List<Recipe>> addRecipes(@RequestBody RecipeListInput recipeListInput)
{
List<Recipe> recipes = recipeListInput.getItems();
//
//some reasonable defaults
ServiceResultWrapper<List<Recipe>> result = new ServiceResultWrapper<List<Recipe>>(null, true, "Recipe(s) saved successfully", 0);
//
//Validate this entity
this.validateEntities(result, recipes);
if (!result.getSuccess()){
return result;
}
try {
//
//Must send back all data including generated PK for UI grids to synch up
for (Recipe r : recipes){
//
//Load the recipe from db
if (!StringUtils.isEmpty(r.getYeastName())){
r.setYeast(this.yeastService.findByName(r.getYeastName()).get(0));
}
recipeService.insert(r);
}
result.setItem(recipes);
}
catch(Exception e){
log.error("error", e);
result.setSuccess(false);
result.setMessage(e.getMessage());
result.setItem(recipes);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment