close
build.gradle
buildscript { ext { springBootVersion = '2.0.4.RELEASE' jjwtVersion = '0.9.0' findbugsVersion='3.0.1' bootstrapVersion = '3.3.7' jqueryVersion = '3.3.1' vueVersion ='2.5.13' fontawesomeVersion = '5.2.0' jspapiVersion = '2.3.3' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } /* * 在這個段落中你可以聲明使用哪些外掛程式 * apply plugin: 'java' 代表這是一個Java專案,需要使用java外掛程式 * 如果想生成一個 `Intellij IDEA` 的工程,類似的如果要生成 * eclipse工程,就寫 apply plugin: 'eclipse' * 同樣的我們要學的是Spring Boot,所以應用Spring Boot外掛程式 */ apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' // 在這個段落中你可以聲明編譯後的Jar檔資訊 bootJar { baseName = 'myspring' group = 'com.polinwei' version = '0.0.1-SNAPSHOT' } // 在這個段落中你可以聲明原始檔案和目標編譯後的Java版本相容性 sourceCompatibility = 1.8 targetCompatibility = 1.8 // 在這個段落中你可以聲明在哪裡可以找到你的項目依賴 repositories { mavenCentral() maven { url "https://repo.spring.io/snapshot" } maven { url "https://repo.spring.io/milestone" } maven { url "https://code.lds.org/nexus/content/groups/main-repo"} maven { url "http://maven.aliyun.com/nexus/content/repositories/central"} } dependencies { compile("org.springframework.boot:spring-boot-starter-data-jpa") compile("org.springframework.boot:spring-boot-starter-thymeleaf") compile("org.springframework.boot:spring-boot-starter-freemarker") compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-security") compile("org.springframework.security:spring-security-taglibs") compile("org.springframework.boot:spring-boot-devtools") // Class 程式有更改時, 自動重啟 compile("org.hibernate.validator:hibernate-validator") //驗證 compile("javax.servlet.jsp:javax.servlet.jsp-api:${jspapiVersion}") compile("org.springframework.session:spring-session-data-redis") compile("org.springframework.boot:spring-boot-starter-data-redis") runtime("mysql:mysql-connector-java") compileOnly("org.projectlombok:lombok") compile("com.maxmind.geoip2:geoip2:2.12.0") compile("io.jsonwebtoken:jjwt:${jjwtVersion}") compile("com.google.code.findbugs:findbugs:${findbugsVersion}") compile("org.webjars:bootstrap:${bootstrapVersion}") compile("org.webjars:jquery:${jqueryVersion}") compile("org.webjars:vue:${vueVersion}") compile("org.webjars:font-awesome:${fontawesomeVersion}") compile("org.webjars.bowergithub.lipis:flag-icon-css:3.1.0") compileOnly("org.springframework.boot:spring-boot-configuration-processor") testCompile("org.springframework.boot:spring-boot-starter-test") testCompile("org.springframework.security:spring-security-test") }
model: Authority.java
/** * Authority generated by hbm2java */ @Entity @Table(name = "authority", uniqueConstraints = @UniqueConstraint(columnNames = "name")) public class Authority implements java.io.Serializable { private Long id; private String name; @Size(min=2, max=30 , message = "{Size}") private String description; private Set users = new HashSet(0); public Authority() { } public Authority(String name, String description) { this.name = name; this.description = description; } public Authority(String name, String description, Set users) { this.name = name; this.description = description; this.users = users; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @Column(name = "name", unique = true, nullable = false, length = 50) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "description", nullable = false, length = 100) public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "user_authority", joinColumns = { @JoinColumn(name = "authority_id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "user_id", nullable = false, updatable = false) }) @JsonBackReference public Set getUsers() { return this.users; } public void setUsers(Set users) { this.users = users; } }
Control: AuthorityController.java
@Controller @RequestMapping(path = "/security") public class AuthorityController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private AuthorityRepository authorityRepository; public void init(Model model) { model.addAttribute("programName", "Authority"); } @RequestMapping("authority") public String crudAuthority(Model model) { init(model); model.addAttribute("authority", new Authority()); model.addAttribute("authorityList",authorityRepository.findAll()); return "/security/authority"; } /** * Get Authority Role from id * @param model * @param id * @return */ @RequestMapping(value= {"authorityEdit","authorityEdit/{id}"} , method = RequestMethod.GET) public String crudAuthority(Model model, @PathVariable( required = false , name="id") Long id) { init(model); if (Objects.isNull(id)) { model.addAttribute("authority", new Authority()); } else { model.addAttribute("authority", authorityRepository.findById(id).get()); } return "/security/authority"; } /** * Save Authority Role * @param model * @param authority * @return */ @RequestMapping(value="authorityEdit" , method = RequestMethod.POST) public String crudAuthority(Model model, @Valid Authority authority, BindingResult bindingResult) { init(model); if (bindingResult.hasErrors()) { return "/security/authority"; } authorityRepository.save(authority); model.addAttribute("authority", new Authority()); return "/security/authority"; } /** * Delete Authority Role * @param model * @param id * @return */ @RequestMapping(value="authorityDelete/{id}" , method = RequestMethod.GET) public String authorityDelete(Model model, @PathVariable( required = true, name = "id") Long id) { init(model); authorityRepository.deleteById(id); model.addAttribute("authority", new Authority()); return "/security/authority"; } }
加入了@Valid注解 是為了實現JSR-303的驗證。
ftl: authority.ftl
<!-- form id="authorityForm" --> <form id="authorityForm" action="/security/authorityEdit" method="post" > <input type="hidden" id="authorityId" name="id" value='${authority.id!""}' > <div class="box box-danger"> <div class="box-header with-border"> <h3 class="box-title"><@spring.message "program.block.manipulate" /></h3> <div class="box-tools pull-right"> <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button> <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-remove"></i></button> </div> </div> <!-- /.box-header --> <div class="box-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="authorityName"><@spring.message "program.authority.name" /></label> <input type="text" class="form-control" id="authorityName" placeholder="<@spring.message "program.authority.name" />" name="name" value='${authority.name!""}' required> </div> <!-- /.form-group --> <div class="form-group"> <label for="authorityDescription"><@spring.message "program.authority.description" /></label> <input type="text" class="form-control" id="authorityDescription" placeholder="<@spring.message "program.authority.description" />" name="description" value='${authority.description!""}' required> <#if authority??> <@spring.bind "authority.description" /> <@spring.showErrors "<br />" "color:red"/> </#if> </div> <!-- /.form-group --> </div><!-- /.col --> </div><!-- /.row --> <div class="row"> <div class="col-xs-6"> <button id="btn-login" type="submit" class="btn btn-alert "><@spring.message "label.submit"/></button> </div> </div> <!-- /.row --> </div> <!-- /.box-body --> <div class="box-footer"> Visit <a href="/security/authority">Authority</a> </div> </div> <!-- /.box --> <!-- /.form id="authorityForm" -->
值得一提的是:SpringMVC为FreeMarker提供了支持。
首先要在頁面中引入:<#import "spring.ftl" as spring />,才會有對表單驗證的支援
<div class="form-group">
<label for="authorityDescription"><@spring.message "program.authority.description" /></label>
<input type="text" class="form-control" id="authorityDescription" placeholder="<@spring.message "program.authority.description" />" name="description" value='${authority.description!""}' required>
<#if authority??>
<@spring.bind "authority.description" />
<@spring.showErrors "<br />" "color:red"/>
</#if>
</div>
spring.bind 指定要校驗綁定的欄位。格式是: <@spring.bind 屬性名 />
spring.showErrors 指定顯示錯誤消息。格式是:<@spring.showErrors 分隔符號 樣式 />
編寫驗證配置文件: 在src/main/resources 目前下建立 ValidationMessages.properties , ValidationMessages_en_US.properties , ValidationMessages_zh_TW.properties 這三個檔案, 並放入
Size = Size must be between {2} and {1}.
這樣子運行起就可以了有多語言錯誤訊息的顯示了
https://spring.io/guides/gs/validating-form-input/
https://my.oschina.net/mondayer/blog/879425
文章標籤
全站熱搜
留言列表