为什么我不能按我的意愿重定向页面

iswrvxsc  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(265)

它可以正确地从localhost/gwtech/trangchu重定向到localhost/gwtech/search/example,但是在这个localhost/gwtech/san pham/example上,它会转到localhost/gwtech/san pham/search,但我希望它像localhost/gwtech/search/example一样,并显示http状态405–方法不允许我的代码:

<form method="post" action="search" modelAttribute="search" name="search" onsubmit="return validateSearch()">
    <div class="form-group">
        <input  type="text" id="txtsearch" path="tensanpham" name="search-field" value="" placeholder="Nhập tên sẩn phẩm...."/>
        <button type="submit"><h1>Find</h1><span class="icon fa fa-search"></span></button>
    </div>
</form>

控制器

@Autowired
public HomeServiceImpl homeService;
@Autowired
private ProductServiceImpl productService;
@RequestMapping(value = {"/", "/trangchu"})
public ModelAndView home(HttpSession session) {
    session.removeAttribute("LoginInfo2");
    ModelAndView mv = new ModelAndView("users/index");
    mv.addObject("slides", homeService.GetDataSlides());
    mv.addObject("loaisp", homeService.GetLoaiSPs());
    mv.addObject("nsx", homeService.GetNSXs());
    mv.addObject("allsp", homeService.GetSPAlls());
    mv.setViewName("users/index");

    return mv;
}

@RequestMapping(value = "/search")
public void search(HttpServletRequest request,HttpServletResponse resp, @ModelAttribute("search") String search) throws IOException {
    String searchfield = request.getParameter("search-field");
    resp.sendRedirect("/gwtech/search/"+searchfield);

}

@Autowired
private DeProductServiceImpl deproductService;

@RequestMapping(value = {"/san-pham","/san-pham/{masp}"}, method = RequestMethod.GET)
public ModelAndView deproduct(HttpSession session,@PathVariable String masp) {
    ModelAndView mv = new ModelAndView("users/detail-product");
    mv.addObject("loaisp", homeService.GetLoaiSPs());
    mv.addObject("nsx", homeService.GetNSXs());
    mv.addObject("spbysp", deproductService.GetSPBySP(masp));
    mv.addObject("allsp", homeService.GetSPAlls());
    mv.setViewName("users/detail-product");
    return mv;
}

当我在trangchu上使用search时,它运行得非常好,但在san pham上,它转到localhost/gwtech/san pham/search并显示http状态405–方法不允许

wooyq4lh

wooyq4lh1#

试试这个:

@RequestMapping(value = "/search","/san-pham/search")
public void search(HttpServletRequest request,HttpServletResponse resp, @ModelAttribute("search") String search) throws IOException {
    String searchfield = request.getParameter("search-field");
    resp.sendRedirect("/gwtech/search/"+searchfield);
}

我希望这能奏效。

yqkkidmi

yqkkidmi2#

您遇到此问题是因为您在表单操作中调用了错误的url。

<form method="post" action="search" modelAttribute="search" name="search" onsubmit="return validateSearch()">

action=“search”将在当前url中添加搜索,即localhost/gwtech/san pham/search
所以改变你的动作形式如下

<form method="post" action="search" modelAttribute="/search" name="search" onsubmit="return validateSearch()">

现在可以了。如果有任何疑问,请告诉我。

相关问题