从视图访问控制器中的方法
Posted
技术标签:
【中文标题】从视图访问控制器中的方法【英文标题】:Access method in controller from view 【发布时间】:2016-10-27 16:48:59 【问题描述】:我的视图中有这段代码来显示一个输入框和一个提交按钮。 (更新)
<form action="/hms/accommodations" method="GET">
<input type="text" name="searchKeyword"/>
<input type="submit" value="Submit"/>
</form>
当我单击提交按钮时,我需要将用户在输入框中输入的任何内容传递给我的控制器中的方法。
这是我在控制器中的方法。 (更新)
@RequestMapping(value = "/hms/accommodations", method = RequestMethod.GET)
public List<Accommodation> listofAccomo(@RequestParam String searchKeyword)
List<Accommodation> searchResult = accommodationService.findAllAccommodationBySearchBox(searchKeyword);
return searchResult;
我的住宿服务类中有这个:
public abstract List<Accommodation> findAllAccommodationBySearchBox(String searchKeyword);
这在另一个班级:
public List<Accommodation> findAllAccommodationBySearchBox(String searchKeyword)
TypedQuery<Accommodation> searchResult = em.createNamedQuery("findAllAccommodationBySearch", Accommodation.class);
searchResult.setParameter("searchKeyword",'%'+searchKeyword+'%');
List<Accommodation> result=searchResult.getResultList();
return result;
我的域中有这个 NamedQuery。:
@NamedQueries(
@NamedQuery(
name = "findAllAccommodationBySearch",
query = "SELECT a FROM Accommodation a WHERE a.person.firstName LIKE :searchKeyword OR a.person.middleName LIKE :searchKeyword OR a.person.lastName LIKE :searchKeyword OR a.room.roomNumber LIKE :searchKeyword OR a.person.pvId LIKE :searchKeyword OR a.startDate LIKE :searchKeyword OR a.endDate LIKE :searchKeyword"
)
)
发生的情况是,当我在键入后单击提交按钮时,它会重定向到同一页面但使用不同的 URL,但它似乎没有访问我的 Controller 方法,因为它没有返回它应该返回的值. 我在这里错过了什么?希望有人可以提供帮助。谢谢!
编辑:这是我的控制器类代码。
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;
import ph.com.smesoft.hms.domain.Accommodation;
import ph.com.smesoft.hms.service.AccommodationService;
import ph.com.smesoft.hms.service.PersonService;
import ph.com.smesoft.hms.service.RoomService;
@Controller
@RequestMapping("/accommodations")
public class AccommodationController
@RequestMapping(value = "/id", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<String> showJson(@PathVariable("id") Long id)
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json; charset=utf-8");
try
Accommodation accommodation = accommodationService.findAccommodation(id);
if (accommodation == null)
return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
return new ResponseEntity<String>(accommodation.toJson(), headers, HttpStatus.OK);
catch (Exception e)
return new ResponseEntity<String>("\"ERROR\":"+e.getMessage()+"\"", headers, HttpStatus.INTERNAL_SERVER_ERROR);
[1:49:35 AM] Kath Revilla: @RequestMapping(headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<String> listJson()
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json; charset=utf-8");
try
List<Accommodation> result = accommodationService.findAllAccommodations();
return new ResponseEntity<String>(Accommodation.toJsonArray(result), headers, HttpStatus.OK);
catch (Exception e)
return new ResponseEntity<String>("\"ERROR\":"+e.getMessage()+"\"", headers, HttpStatus.INTERNAL_SERVER_ERROR);
@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(@RequestBody String json, UriComponentsBuilder uriBuilder)
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
try
Accommodation accommodation = Accommodation.fromJsonToAccommodation(json);
accommodationService.saveAccommodation(accommodation);
RequestMapping a = (RequestMapping) getClass().getAnnotation(RequestMapping.class);
headers.add("Location",uriBuilder.path(a.value()[0]+"/"+accommodation.getId().toString()).build().toUriString());
return new ResponseEntity<String>(headers, HttpStatus.CREATED);
catch (Exception e)
return new ResponseEntity<String>("\"ERROR\":"+e.getMessage()+"\"", headers, HttpStatus.INTERNAL_SERVER_ERROR);
@RequestMapping(value = "/jsonArray", method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJsonArray(@RequestBody String json)
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
try
for (Accommodation accommodation: Accommodation.fromJsonArrayToAccommodations(json))
accommodationService.saveAccommodation(accommodation);
return new ResponseEntity<String>(headers, HttpStatus.CREATED);
catch (Exception e)
return new ResponseEntity<String>("\"ERROR\":"+e.getMessage()+"\"", headers, HttpStatus.INTERNAL_SERVER_ERROR);
@RequestMapping(value = "/id", method = RequestMethod.PUT, headers = "Accept=application/json")
public ResponseEntity<String> updateFromJson(@RequestBody String json, @PathVariable("id") Long id)
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
try
Accommodation accommodation = Accommodation.fromJsonToAccommodation(json);
accommodation.setId(id);
if (accommodationService.updateAccommodation(accommodation) == null)
return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
return new ResponseEntity<String>(headers, HttpStatus.OK);
catch (Exception e)
return new ResponseEntity<String>("\"ERROR\":"+e.getMessage()+"\"", headers, HttpStatus.INTERNAL_SERVER_ERROR);
@Autowired
AccommodationService accommodationService;
@Autowired
PersonService personService;
@Autowired
RoomService roomService;
@RequestMapping(produces = "text/html")
public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @RequestParam(value = "sortFieldName", required = false) String sortFieldName, @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel)
if (page != null || size != null)
int sizeNo = size == null ? 10 : size.intValue();
final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
uiModel.addAttribute("accommodations", Accommodation.findAccommodationEntries(firstResult, sizeNo, sortFieldName, sortOrder));
float nrOfPages = (float) accommodationService.countAllAccommodations() / sizeNo;
uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
else
uiModel.addAttribute("accommodations", Accommodation.findAllAccommodations(sortFieldName, sortOrder));
addDateTimeFormatPatterns(uiModel);
return "accommodations/list";
@RequestMapping(value = "/hms/accommodations", method = RequestMethod.GET)
public List<Accommodation> listofAccomo(@RequestParam String searchKeyword)
List<Accommodation> searchResult = accommodationService.findAllAccommodationBySearchBox(searchKeyword);
return searchResult;
void addDateTimeFormatPatterns(Model uiModel)
uiModel.addAttribute("accommodation_startdate_date_format","yyyy-MM-dd");
uiModel.addAttribute("accommodation_enddate_date_format","yyyy-MM-dd");
void populateEditForm(Model uiModel, Accommodation accommodation)
uiModel.addAttribute("accommodation", accommodation);
addDateTimeFormatPatterns(uiModel);
uiModel.addAttribute("people", personService.findAllPeople());
uiModel.addAttribute("rooms", roomService.findAllRooms());
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest)
String enc = httpServletRequest.getCharacterEncoding();
if (enc == null)
enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
try
pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
catch (UnsupportedEncodingException uee)
return pathSegment;
【问题讨论】:
你能提供你完整的控制器类代码吗? @javaguy 我已经编辑了问题并包含了控制器类代码。 【参考方案1】:问题似乎在于,在您的控制器方法中,您需要一个路径参数,而在表单中您传递的是一个查询参数。 我会更改方法以接受查询参数,例如
@RequestMapping(value = "/hms/accommodations", method = RequestMethod.GET)
public List<Accommodation> listofAccomo(@RequestParam String searchKeyword)
List<Accommodation> searchResult = accommodationService.findAllAccommodationBySearchBox(searchKeyword);
return searchResult;
有两个变化:
-
更改了映射以匹配表单操作
将 searchKeyword 设为请求参数而不是路径变量。
同样在表单中你不需要查询参数部分,因为它将在提交期间被浏览器替换,并且数据将作为查询参数附加:
<form action="/hms/accommodations" method="GET">
<input type="text" name="searchKeyword"/>
<input type="submit" value="Submit"/>
</form>
【讨论】:
我试过了,但它仍然没有返回任何东西。我尝试在代码之间打印字符串以查看它是否通过每一行,但它没有打印出任何东西。仍然对为什么它似乎无法访问控制器方法感到困惑。 你能从任何其他客户端访问控制器方法吗? curl,浏览器? 实际上,当我点击提交按钮时,它会转到这个网址:localhost:8080/hms/accommodations?searchKeyword=keyword“关键字”是我在输入框中输入的单词。这是否意味着我可以访问控制器方法? 你能从浏览器访问“localhost:8080/hms/accommodations?searchKeyword=keyword”,看看它是否返回任何内容。如果它没有检查你的 Controller 类是否有 @Controller 注释。没有它,方法将不会注册映射。 可以通过浏览器访问是的,但它根本不返回任何内容。只有同一个页面只有这个 "localhost:8080/hms/accommodations?searchKeyword=keyword" 。是的,它确实有一个 @Controller 注释。我很确定我的 Controller 类本身正在工作,因为我还有其他方法,而且它似乎做得很好。现在真的很迷茫。【参考方案2】:问题在于您当前的代码,最终的 url 如下所示: /accommodations/hms/accommodations
换句话说,总 url = 类级别的@RequestMapping + 方法级别的@RequestMapping (总 url 是 spring 处理程序映射看到的,然后映射/标识以调用相应的方法)
选项(1):
因此,要使其正常工作,您需要在顶部(类级别)删除 @RequestMapping("/accommodations")
控制器类:
@Controller
public class AccommodationController
@RequestMapping(value = "/hms/accommodations", method = RequestMethod.GET)
public List<Accommodation> listofAccomo(@RequestParam String searchKeyword)
List<Accommodation> searchResult = accommodationService.findAllAccommodationBySearchBox(searchKeyword);
return searchResult;
//add all other methods
HTML:
<form action="/hms/accommodations" method="GET">
<input type="text" name="searchKeyword"/>
<input type="submit" value="Submit"/>
</form>
选项 (2): 您可以将您的表单更改为如下所示,操作为“/accommodations/hms/accommodations”:
控制器类:
@Controller
@RequestMapping("/accommodations")
public class AccommodationController
@RequestMapping(value = "/hms/accommodations", method = RequestMethod.GET)
public List<Accommodation> listofAccomo(@RequestParam String searchKeyword)
List<Accommodation> searchResult = accommodationService.findAllAccommodationBySearchBox(searchKeyword);
return searchResult;
//add all other methods
HTML:
<form action="/accommodations/hms/accommodations" method="GET">
<input type="text" name="searchKeyword"/>
<input type="submit" value="Submit"/>
</form>
【讨论】:
用我当前的代码,点击提交后url变成"localhost:8080/hms/accommodations?searchKeyword=keyword"。 这就是您在浏览器中看到的,没有映射控制器 url 你能试试我上面的选项(2)吗? 我试过了,它返回 localhost page not found。 你试过我的 Option(1) 删除类级别的@RequestMapping 吗?以上是关于从视图访问控制器中的方法的主要内容,如果未能解决你的问题,请参考以下文章