Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SpringMVC控制器,在两个方法之间传递bean_Spring_Spring Mvc - Fatal编程技术网

SpringMVC控制器,在两个方法之间传递bean

SpringMVC控制器,在两个方法之间传递bean,spring,spring-mvc,Spring,Spring Mvc,我通过开发一个简单的SpringMVC应用程序开始学习SpringMVC 我创建了一个JSP文件,用于列出-编辑如下用户列表: 当我点击“编辑”链接(来自列表项)时,表单应该由项目信息填充,因此用户可以编辑信息并保存项目(注意,此表单用于创建/编辑项目) 这是与JSP文件相关的代码: <c:url var="addAction" value="/admin/users/add"></c:url> <form:form action="${addAction}"

我通过开发一个简单的SpringMVC应用程序开始学习SpringMVC

我创建了一个JSP文件,用于列出-编辑如下用户列表:

当我点击“编辑”链接(来自列表项)时,表单应该由项目信息填充,因此用户可以编辑信息并保存项目(注意,此表单用于创建/编辑项目)

这是与JSP文件相关的代码:

<c:url var="addAction" value="/admin/users/add"></c:url>

<form:form action="${addAction}" commandName="user">

    <table>

        <c:if test="${!empty user.adminName}">
            <tr>
                <td><form:label path="id">
                        <spring:message text="ID" />
                    </form:label></td>
                <td><form:input path="id" readonly="true" size="8"
                        disabled="true" /> <form:hidden path="id" /></td>
            </tr>
        </c:if>

        <tr>
            <td><form:label path="adminName">
                    <spring:message text="Name" />
                </form:label></td>
            <td><form:input path="adminName" /></td>
        </tr>

        <tr>
            <td><form:label path="adminEmail">
                    <spring:message text="adminEmail" />
                </form:label></td>
            <td><form:input path="adminEmail" /></td>
        </tr>

        <tr>

            <td><form:select path="groups" items="${groupList}" /></td>
        </tr>


        <tr>
            <td colspan="2"><c:if test="${!empty user.adminName}">
                    <input type="submit" value="<spring:message text="Edit Person"/>" />
                </c:if> <c:if test="${empty user.adminName}">
                    <input type="submit" value="<spring:message text="Add Person"/>" />
                </c:if></td>
        </tr>
    </table>
</form:form>





<br>
<div class="bs-example">
    <table class="table">
        <thead>
            <tr>
                <th>Row</th>
                <th>First Name</th>
                <th>Email</th>
            </tr>
        </thead>


        <tbody>

            <c:forEach var="i" items="${users}">

                <tr>
                    <td>${i.id}</td>
                    <td>${i.firstName}</td>
                    <td>${i.adminEmail}</td>

                    <td><a href="<c:url value='/admin/users/edit/${i.id}'/>">Edit</a></td>
                    <td><a href="<c:url value='/admin/users/remove/${i.id}'/>">Delete</a></td>


                </tr>

            </c:forEach>

        </tbody>

    </table>
</div>


一行 名字 电子邮件 ${i.id} ${i.firstName} ${i.adminEmail}
我的控制方法是:

    @Controller
@RequestMapping(value = "/admin/users/")
public class UserController {

    private static final Logger LOGGER = LoggerFactory
            .getLogger(UserController.class);

    @Autowired
    UserService userService;

    @Autowired
    GroupService groupService;

    @Autowired
    LabelUtils messages;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    // @PreAuthorize("hasRole('STORE_ADMIN')")
    @RequestMapping(value = "list.html", method = RequestMethod.GET)
    public String displayUsers(Model model) throws Exception {

        List<User> users = userService.listUser();

        List<Group> groups = groupService.list();

        List<String> groupList = new ArrayList<String>();

        model.addAttribute("users", users);
        model.addAttribute("user", new User());

        for (Group group : groups) {

            groupList.add(group.getGroupName());

        }

        model.addAttribute("groupList", groupList);

        return "admin/userAdmin";

    }

    @RequestMapping("remove/{id}")
    public String removePerson(@PathVariable("id") int id) {

        User user = userService.getById((long) id);

        try {
            userService.delete(user);
        } catch (ServiceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return "redirect:/admin/users/list.html";
    }

    // For add and update person both
    @RequestMapping(value = "add" , method = RequestMethod.POST)
    public String addPerson(@ModelAttribute("user") User user,
            BindingResult result) {

        if (result.hasErrors()) {
            return "error";
        }

        try {
            if (user.getId() == 0) {
                // new person, add it

                this.userService.create(user);

            } else {
                // existing person, call update
                this.userService.saveOrUpdate(user);
            }

        } catch (ServiceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return "redirect:/admin/users/list.html";


    }

    @RequestMapping(value = "edit/{id}" )
    public String editPerson(@PathVariable("id") int id  , Model model) {



        // Prepare Groups

        List<Group> groups = groupService.list();

        List<String> groupList = new ArrayList<String>();

        for (Group group : groups) {

            groupList.add(group.getGroupName());

        }

        model.addAttribute("groupList", groupList);

        model.addAttribute("user", this.userService.getById((long) id));
        model.addAttribute("users", this.userService.list());

        return "admin/userAdmin";

    }


}
@控制器
@请求映射(value=“/admin/users/”)
公共类用户控制器{
专用静态最终记录器记录器=记录器工厂
.getLogger(UserController.class);
@自动连线
用户服务用户服务;
@自动连线
群服务群服务;
@自动连线
阴唇信息;
@自动连线
专用BCryptPasswordEncoder密码编码器;
//@PreAuthorize(“hasRole('STORE_ADMIN')”)
@RequestMapping(value=“list.html”,method=RequestMethod.GET)
公共字符串displayUsers(模型)引发异常{
List users=userService.listUser();
List groups=groupService.List();
List groupList=new ArrayList();
model.addAttribute(“用户”,用户);
model.addAttribute(“user”,new user());
用于(组:组){
groupList.add(group.getGroupName());
}
model.addAttribute(“groupList”,groupList);
返回“admin/userAdmin”;
}
@RequestMapping(“remove/{id}”)
公共字符串removePerson(@PathVariable(“id”)int-id){
User=userService.getById((长)id);
试一试{
userService.delete(用户);
}捕获(服务异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回“重定向:/admin/users/list.html”;
}
//对于添加和更新人员
@RequestMapping(value=“add”,method=RequestMethod.POST)
公共字符串addPerson(@ModelAttribute(“用户”)用户,
BindingResult(结果){
if(result.hasErrors()){
返回“错误”;
}
试一试{
if(user.getId()==0){
//新的人,添加它
this.userService.create(用户);
}否则{
//现有人员,呼叫更新
this.userService.saveOrUpdate(用户);
}
}捕获(服务异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回“重定向:/admin/users/list.html”;
}
@请求映射(value=“edit/{id}”)
公共字符串editPerson(@PathVariable(“id”)int-id,Model){
//分组
List groups=groupService.List();
List groupList=new ArrayList();
用于(组:组){
groupList.add(group.getGroupName());
}
model.addAttribute(“groupList”,groupList);
model.addAttribute(“user”,this.userService.getById((long)id));
model.addAttribute(“users”,this.userService.list());
返回“admin/userAdmin”;
}
}
问题是,当我单击编辑链接时,表单由项目信息正确填充,因此用户可以编辑检索的数据,但对象“用户”是从控制器中“addPerson”方法中的方法“editPerson”检索的(

代码行:model.addAttribute(“user”,this.userService.getById((long)id));在editPerson方法中) 将所有其他字段设为空,这样当我合并数据时,保存操作将失败

示例:当从表单检索数据时,用户项的另一个字段“AdminAPassword”未在JSP中打印,也未更改为bu user。此字段为空

你能帮忙吗


提前感谢

您的问题有些不清楚,我将根据您的头衔行事。我的理解是,您希望在控制器中的方法之间共享用户bean。您可以通过使用
@SessionAttributes

@SessionAttributes("user")
@Controller
@RequestMapping(value = "/admin/users/")
public class UserController {

使用此设置,所有名称与@SessionAttributes中列出的名称匹配的模型属性将在后续请求中保留。您可以了解更多

从Get-to-Post方法传递对象的方法是否符合MVC spring规则。感谢在sessionAttributes中成功地传递了该对象,我尝试了一个例子,当这个对象与另一个对象有很多关系时,比如说“组”,当我们通过代码User.gerGroups检索“User”时,它给出null,尽管最初,它在传递到session属性时有一个组列表。非常感谢您的反馈。