Java Spring MVC在同一个JSP中获取/发布

前端之家收集整理的这篇文章主要介绍了Java Spring MVC在同一个JSP中获取/发布前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我的控制器..
@RequestMapping(value = "/add",method = RequestMethod.GET)
public String add(Model model) {
    return "add";
}

@RequestMapping(value = "/add",method = RequestMethod.POST)
public String added(@RequestParam("name") String name,Model model) {
    City city = new City();
    city.setCity(name);
    service.addCity(city);
    return "add";
}

这是我的JSP视图..这只是为了添加…这是add.jsp..so它回发给自己

<form method="post" action="/spring/krams/edit/add">
Linna nimi
<input type="text" name="name">
<input type="submit" value="Test" name="submit" />
</form>

我希望JSP文件发生变化,以便当我将其发布到此文件时,它会说…“添加了城市”.那可能吗?

什么关于更新城市?

@RequestMapping(value = "/update",method = RequestMethod.POST)
public String updated(@RequestParam("city") int city_id,@RequestParam("text") String name,Model model) {
    service.updateCity(name,city_id);
    return "update";
}

这里没有对象?

解决方法

在post方法中,您可以使用addAttribute方法添加属性
@RequestMapping(value = "/add",Model model) {
    City city = new City();
    city.setCity(name);
    service.addCity(city);
    model.addAttribute("city",city);
    return "add";
}

在JSP中,您可以检查属性city是否为null(标记为< c:if />).如果它不是null,那是因为它刚刚被添加到模型中,所以你可以显示你想要的任何东西. ${city.city}它只是一个JSTL表达式,它访问city属性,然后调用getter来访问该属性的city属性

<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>

<c:if test="${city != null}">
    CITY <c:out value="${city.city}" /> ADDED
</c:if>

UPDATE

如果根据更新/创建操作需要不同的消息,则可以执行以下操作:(在示例中,当id param不为null时进行更新,因为id是要更新的城市的标识符)

@RequestMapping(value = "/add",method = RequestMethod.POST)
public String added(@RequestParam(value="id",required=false) String id,@RequestParam("name") String name,Model model) {
    City city;
    String operation;
    if(id== null){
        //create operation
        city = new City();
        operation = "CREATE";

    }else{
        //update operation
        city = service.findCity(id);
        operation = "UPDATE";
    }
    city.setCity(name);        
    service.saveCity(city); //save or update
    model.addAttribute("city",city);
    model.addAttribute("operation",operation); //add operation param
    return "add";
}

在JSP中你可以做到:

<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>

<c:if test="${operation == 'CREATE'}">
    <c:if test="${city != null}">
          CITY <c:out value="${city.city}" /> ADDED
    </c:if>
    <c:if test="${operation == 'UPDATE'}">
          CITY <c:out value="${city.city}" /> UPDATED
    </c:if>
</c:if>
原文链接:https://www.f2er.com/java/129424.html

猜你在找的Java相关文章