gpt4 book ai didi

java - 从 View 访问 Controller 中的方法

转载 作者:行者123 更新时间:2023-11-30 08:32:06 26 4
gpt4 key购买 nike

我的 View 中有这段代码来显示输入框和提交按钮。 (更新)

  <form action="/hms/accommodations" method="GET">
<input type="text" name="searchKeyword"/>
<input type="submit" value="Submit"/>
</form>

当我点击提交按钮时,我需要将用户输入到输入框中的任何内容传递到我的 Controller 中的方法。

这是我的 Controller 中的方法。 (更新)

@RequestMapping(value = "/hms/accommodations", method = RequestMethod.GET)
public List<Accommodation> listofAccomo(@RequestParam String searchKeyword){
List<Accommodation> searchResult = accommodationService.findAllAccommodationBySearchBox(searchKeyword);
return searchResult;
}

我的 AccommodationService 类中有这个:

 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 方法,因为它没有返回它应该返回的值.我在这里错过了什么?希望有人能帮忙。谢谢!

编辑:这是我的 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;
}




}

最佳答案

问题似乎是在您的 Controller 方法中您需要一个路径参数,而在表单中您传递的是一个查询参数。我会改变方法来接受像

这样的查询参数
@RequestMapping(value = "/hms/accommodations", method = RequestMethod.GET)
public List<Accommodation> listofAccomo(@RequestParam String searchKeyword){
List<Accommodation> searchResult = accommodationService.findAllAccommodationBySearchBox(searchKeyword);
return searchResult;
}

有两个变化:

  1. 更改映射以匹配表单操作
  2. 使 searchKeyword 成为请求参数而不是路径变量。

此外,在表单中,您不需要操作中的查询参数部分,因为它将在提交期间由浏览器替换,并且数据将作为查询参数附加:

  <form action="/hms/accommodations" method="GET">
<input type="text" name="searchKeyword"/>
<input type="submit" value="Submit"/>
</form>

关于java - 从 View 访问 Controller 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40290185/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com