首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >带有Thymeleaf和SpringBoot的下拉列表

带有Thymeleaf和SpringBoot的下拉列表
EN

Stack Overflow用户
提问于 2016-02-29 06:20:35
回答 1查看 15.8K关注 0票数 3

我有一个SpringBoot1.3应用程序,它在HTML上使用Thymeleaf。我有一页用户,当我编辑他们,我希望用户机构从一个列表中选择。我有一个窗口正确地显示了一切,但是当我选择机构时,控制器没有显示所选的值。

以下是我的HTML:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 <div class="form-group">
     <label class="col-md-3 control-label">Institution</label>
         <div class="col-md-5">
         <div th:if="${institutionList != null and not #lists.isEmpty(institutionList)}">
             <select>
                 <option th:each="dropDownItem : ${institutionList}"
                                 th:value="${dropDownItem.name}"
                                 th:text="${dropDownItem.name}" />
             </select>
        </div>
        <div th:if="${institutionList == null or lists.isEmpty(institutionList)}">
            <div>"No Institutions were found, please create some first"</div>
        </div>
    </div>
 </div>

这是我的控制器

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Controller
@PreAuthorize("hasRole('Admin')")
@RequestMapping("/admin")
public class AdminController {
    @Transactional
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public String checkPersonInfo(@ModelAttribute User user, Model model, Authentication authentication) {
        // user does not have the selected institution set
        customUserDetailsService.createNewUser(user);
        updateModelWithAllUsers(model);
        return "admin";
    }

    private void updateModelWithAllUsers(Model model) {
        model.addAttribute(USERLIST, customUserDetailsService.findAllUsers());
        model.addAttribute(INSTITUTION_LIST, institutionService.findAll());
        model.addAttribute("user", new User());
    }

...
}

这是我的用户:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Entity
@Table(name = "Users")
public class User implements UserDetails {
 @Id
    private String username;

    @Column(nullable = false)
    private String password;

    private boolean enabled;
    private boolean accountNonExpired;
    private boolean accountNonLocked;
    private boolean credentialsNonExpired;
    private String companyName;
    private String email;

    @ElementCollection(fetch=FetchType.EAGER)
    @CollectionTable(name="Authorities", joinColumns=@JoinColumn(name="username"))
    @Column(name="authority")
    private Set<String> roles = new HashSet<String>();

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "institutionId", nullable = false)
    private Institution institution;
... getters & setters
}

我的机构:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Entity
@Table(name = "Institution")
public class Institution {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long institutionId;
    private String name;

    @OneToMany(mappedBy = "institution", fetch = FetchType.EAGER)
    @Fetch(value = FetchMode.SUBSELECT)
    List<User> users = new ArrayList<User>();
    ... getters & setters
}

当"/addUser“从UI中获取用户对象时,机构为null。

我使用Sergios建议使用select th:field="${user.institution}"select th:field="*{institution}"

但这给了我一个错误:

org.springframework.validation.BeanPropertyBindingResult: 1在字段‘com.security.Institution@3e3945d2’上的对象'user‘中的字段错误:拒绝值com.security.Institution@3e3945d2;代码typeMismatch.user.institution、typeMismatch.institution、typeMismatch.com。参数[org.springframework.context.support.DefaultMessageSourceResolvable:代码,制度;参数[];默认消息机构;默认消息未能将属性' java.lang.String‘类型的属性值转换为属性’制度‘所需的类型'com.security.Institution’;嵌套异常是org.springframework.core.convert.ConversionFailedException:未能从java.lang.String类型转换为值‘com.security.Institution@3e3945d2’的java.lang.Long类型;嵌套异常是java.lang.NumberFormatException: For input string:"com。.security.Institution@3e3945d2“

不确定我是否正确地阅读了这篇文章,但这是否意味着Thymeleaf试图将Institution.name传递给user.institution字段?

有人能就如何做到这一点提出建议吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-29 06:42:13

您已经忘记指出必须从其中选取所选值的字段:

示例:我假设用户类有一个机构属性。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<div class="form-group">
 <label class="col-md-3 control-label">Institution</label>
     <div class="col-md-5">
     <div th:if="${institutionList != null and not #lists.isEmpty(institutionList)}">
         <select th:field="*{institution}">
             <option th:each="dropDownItem : ${institutionList}"
                             th:value="${dropDownItem.name}"
                             th:text="${dropDownItem.name}" />
         </select>
    </div>
    <div th:if="${institutionList == null or lists.isEmpty(institutionList)}">
        <div>"No Institutions were found, please create some first"</div>
    </div>
</div>

更多信息:http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#dropdownlist-selectors

编辑:您需要向您的应用程序说明如何将表单内返回的Id (字符串类型)转换为“机构”实体。为此,您必须使用转换器。

首先,将选项的值更改为institutionId:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<div class="form-group">
 <label class="col-md-3 control-label">Institution</label>
     <div class="col-md-5">
     <div th:if="${institutionList != null and not #lists.isEmpty(institutionList)}">
         <select th:field="*{institution}">
             <option th:each="dropDownItem : ${institutionList}"
                             th:value="${dropDownItem.institutionId}"
                             th:text="${dropDownItem.name}" />
         </select>
    </div>
    <div th:if="${institutionList == null or lists.isEmpty(institutionList)}">
        <div>"No Institutions were found, please create some first"</div>
    </div>
</div>

您必须创建一个实现转换器接口的类。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Component
public class StringToInstitution implements Converter<String, Institution> {

@Autowired
private InstitutionRepository repository; //Or the class that implments the repository.

    @Override
    public Institution convert(String arg0) {
        Long id = new Long(arg0);
        return repository.findOne(id);
    }

}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35701905

复制
相关文章
Mongoose多表查询运用实例
在开发内容管理系统时,经常会用到多表关联查询场景,如文章分类、文章详情、文章作者三张表,UML图如下:
越陌度阡
2020/11/26
1.7K0
Mongoose多表查询运用实例
mongoose验证
enum: [‘html’, ‘css’, ‘javascript’, ‘node.js’]
Qwe7
2022/05/23
2.4K0
Mongoose aggregate 多表关联查询
使用Mongoose操作MongoDB数据库进行关联查询是一种比较常见的操作,操作方式有哪几种呢?下面用一个具体的案例来演示。
越陌度阡
2020/11/26
3.6K0
48、mongoose入门
现在假设我们想把看到的每一只猫都用数据库给记录下来,即每只猫都是一条document(数据行)。
Ewall
2018/11/21
2K0
Mongoose中的修饰符
Mongoose提供了修饰符功能用于对存取的数据进行一些加工,常用的修饰符有以几下几种:
越陌度阡
2020/11/26
1.2K0
mongoose食用姿势!
Mongoose库简而言之就是对node环境中MongoDB数据库操作的封装,一种对象模型工具,可以将数据库中的数据转换为JavaScript对象供我们使用。
十月梦想
2018/08/29
1.5K0
Mongoose 数据校验
Mongoose为了保证数据库数据的一致性,提供了对数据校验的功能,常用的校验有以下这些:
越陌度阡
2020/11/26
1K0
四、mongoose的使用
2.定义路由 分模块开发,将路由的方法写在/constroller/stu.js文件中。
Dreamy.TZK
2020/07/09
1.9K0
使用 Mongoose 操作 MongoDB
Mongoose是在node.js环境下对mongodb进行便捷操作的对象模型工具。
4O4
2022/04/25
1.7K0
使用 Mongoose 操作 MongoDB
Egg 中结合Mongoose操作Mongodb
1. 安装模块 npm i egg-mongoose --save 2. 配置 egg-mongoose 插件 // config/plugin.js 'use strict'; exports.ejs = { enable: true, package: 'egg-view-ejs', }; // 配置egg-mongoose插件 exports.mongoose = { enable: true, package: 'egg-mongoose' }; 3. 配置连接数据库
越陌度阡
2020/11/26
2.2K0
mongoose官方文档总结
你也可以设定虚拟值的 setter ,下例中,当你赋值到虚拟值时,它可以自动拆分到其他属性:
六个周
2022/10/28
20.7K0
mongoose根据关键字模糊查询(包括前端模糊查询)
后端: 使用new RegExp()实例对象 eg: const Schema = mongoose.model("modelName") let reg = new RegExp("查询关键词") awati Schema.fine || where(say:reg).exec().then(res=>{ 成功回调}) .catch(err=>{ 失败回调 }) 前端: eg: var arr = ['草莓','苹果'] newArr = [] for(var i = 0;i<arr.length;i++
biaoblog.cn 个人博客
2022/08/11
2.8K0
针对Mongoose自定义分页查询通用方法
直接上代码: var mongoose = require('mongoose'); var Schema = mongoose.Schema; var async = require('async'); var pageQuery = function (page, pageSize, Model, populate, queryParams, sortParams, callback) { var start = (page - 1) * pageSize; var $page = {
飞奔去旅行
2019/06/13
2.8K0
使用Mongoose做关联查询的设计方案
在关系型数据库中,我们通常将这两个对象设计成一对多的关系,一个User对应多个Article。而使用mongoose我们可以如此设计:
飞奔去旅行
2019/06/13
2.8K1
使用Mongoose的populate方法实现多表关联查询
MongoDB在3.2以上的版本有类似于 join 的 $lookup 聚合操作符,其实 Mongoose 有一个更强大的替代方法,叫做populate ( ),它允许你在其他集合中引用文档,实现更简洁优雅的查询操作。
越陌度阡
2020/11/26
3.7K0
使用Mongoose的populate方法实现多表关联查询
Mongoose学习参考文档
一、快速通道 1.1 名词解释 Schema : 一种以文件形式存储的数据库模型骨架,不具备数据库的操作能力 Model : 由Schema发布生成的模型,具有抽象属性和行为的数据库操作对 Entity : 由Model创建的实体,他的操作也会影响数据库 注意: 1.本学习文档采用严格命名方式来区别不同对象,例如: var PersonSchema; //Person的文本属性 var PersonModel; //Person的数据库模型 var Per
庞小明
2018/03/07
24.2K0
Mongoose 实现关联查询和踩坑记录
本文源自工作中的一个问题,在使用 Mongoose 做关联查询时发现使用 populate() 方法不能直接关联非 _id 之外的其它字段,在网上搜索时这块的解决方案也并不是很多,在经过一番查阅、测试之后,有两种可行的方案,使用 Mongoose 的 virtual 结合 populate 和 MongoDB 原生提供的 Aggregate 里面的 $lookup 阶段来实现。
五月君
2020/08/20
26.5K0
Mongoose 实现关联查询和踩坑记录
mongodb操作之mongoose
/** * Created by chaozhou on 2015/10/6. */ var mongoose = require("mongoose"); var db = mongoose.c
用户1141560
2017/12/26
1.4K0
初试MongoDB学习之Mongoose的使用
在MongoDB中,多个Document可以组成Collection(以下简称集合),多个集合又可以组成数据库。我们想要操作MongoDB数据,那就得先要具备上面所说的包含数据的“文档”,文档又是什么意思呢,请看如下介绍。
九旬
2020/10/23
5.9K0
初试MongoDB学习之Mongoose的使用
Mongoose模块化实践
Mongoose为操作MongoDB数据库提供了很大的方便,在实际开发过程中,为了保证可扩展与可维护性,通常会将Mongoose进行模块化,下面记录一个模块化的实例,便于在以后的项目中复用。
越陌度阡
2020/11/26
1K0

相似问题

findOne mongoose查询未正常工作

118

分页不能正常工作的Mongoose查询

120

populate返回空查询mongoose

127

Mongoose查询返回空数组

10

Mongoose查询返回空数组

120
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文