将类别填充到控制器中的下拉列表中以进行查看

时间:2018-12-22 06:05:30

标签: java spring model-view-controller

我有两个类Product和Category,我想在Product Controller中传递category到addProduct视图,如下代码所示:error是请求处理失败;嵌套异常为java.lang.NullPointerException

ProductController.java

@RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView getAddNewProductForm(@RequestParam(required=false) String id) {
        ModelAndView mv = new ModelAndView();
        //Product newProduct = new Product();
        if (id == null) {
            mv.addObject("newProduct",new Product());
        } else { 
            mv.addObject("product", productService.getProductById(id));
        }
        mv.addObject("category", categoryService.listCategory()); //If I remove this line of code. I didn't get error.
        mv.setViewName("addProduct");
        return mv;
    }
@RequestMapping(value = "/add", method = RequestMethod.POST)
    public String save(@ModelAttribute("newProduct")Product newProduct, @ModelAttribute Category category, Model model) {
        productService.addProduct(newProduct);
        return "redirect:/product/list";
    }

addProduct.jsp

<select class="form-control" style="width:200px" name="category">
<c:forEach items="${category}" var="category">
    <option name="category" value="${category.categoryId}">${category.categoryName}</option>
</c:forEach>
</select>

InMemoryCategoryRepository.java

package com.giantcambodia.domain.repository.impl;

@Repository
public class InMemoryCategoryRepository implements CategoryRepository {
    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Override
    public List<Category> listCategory(){
        /*List<Category> category = new ArrayList<>();*/
        String SQL = "SELECT * FROM CATEGORIES";
        Map<String, Object> params = new HashMap<String, Object>();
        List<Category> result = jdbcTemplate.query(SQL, params, new CategoryMapper());      
        return result;
    }

    private static final class CategoryMapper implements RowMapper<Category>{
        public Category mapRow(ResultSet rs, int rowNum) throws SQLException{               
            Category category = new Category();
            category.setCategoryId(rs.getLong("CATEGORY_ID"));
            category.setCategoryName(rs.getString("CATEGORY_NAME"));
            category.setCategoryType(rs.getString("CATEGORY_TYPE"));
            category.setDescription(rs.getString("DESCRIPTION"));
            category.setStatus(rs.getString("STATUS"));
            return category;
        }
    }
}

CategoryServerImpl.java

package com.giantcambodia.service.impl;


@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryRepository categoryRepository;

    @Override
    public List<Category> listCategory(){

        return categoryRepository.listCategory();
    }
}

0 个答案:

没有答案