如何使用Spring 4 Rest Controller为Jsp视图服务?
我已经创建了Spring 4项目来构建rest服务。 所以我已经创建了超过50个rest服务,现在需要为此创建web-app。 所以我想重用相同的控制器,所以我只需要编写视图(JSP)代码。
为了同样我用Google搜索并找到了http://www.mkyong.com/spring-mvc/spring-3-mvc-contentnegotiatingviewresolver-example/,但这给了我一个错误。 Morover我的项目结构如下。
那么我需要在servlet-context.xml中编写这个配置? 实现的最佳方式是什么?
主要是我只需要输出Json和html。 所以它的我的http请求有一个扩展名.json和.jsp。
下面是我的一个控制器的代码。 下面是我创建Rest服务的方式,现在我希望这个方法与JSP页面的服务器相同。
package com.alumini.spring.controller; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.alumini.spring.DAO.CourseDAO; import com.alumini.spring.model.Alumini; import com.alumini.spring.model.Course; @RestController public class CourseController { @Autowired private CourseDAO courseDao; @RequestMapping(value = "/getCourseList") public List getCourseList(@RequestParam("email") String email,@RequestParam("password") String password) { List listCourse = courseDao.list(); List finalList= new ArrayList(); for(Course course: listCourse) { finalList.add(course); } return finalList; } }
如果你们之前有人这么做的话,请帮助我吗?
package com.apmc.rest; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.codehaus.jackson.map.ObjectMapper; import org.hibernate.SessionFactory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.apmc.Generic.CommonMethods; import com.apmc.domain.Auction; import com.apmc.domain.Commodity; import com.apmc.jsonObjectMaker.GetEntryDetails; import com.apmc.services.AuctionService; import com.apmc.services.CommodityService; @RestController @RequestMapping("auction") public class RestAuctionController { List
就像@Sotirios Delimanolis这样说:
你不应该。 @RestController并不意味着返回视图。 这意味着返回将直接写入响应主体的内容。
如果确实需要,可以声明方法具有View或ModelAndView的返回类型,并返回具有标识视图名称的相应对象。