免费的课程设计哪个网站有,代理网络是什么意思,网站取源用iapp做软件,做网站需要一些什么东西总览 我们将要讨论的重要主题涉及空值#xff0c;空字符串和输入验证#xff0c;因此我们不会在数据库中输入无效数据。 在处理空值时#xff0c;我们使用了Java 1.8中引入的java.util.Optional 。 0 – Spring Boot Thymeleaf示例表单验证应用程序 我们正在为一所大学构… 总览 我们将要讨论的重要主题涉及空值空字符串和输入验证因此我们不会在数据库中输入无效数据。 在处理空值时我们使用了Java 1.8中引入的java.util.Optional 。 0 – Spring Boot Thymeleaf示例表单验证应用程序 我们正在为一所大学构建一个Web应用程序使潜在的学生可以请求有关其课程的信息。 查看并从 Github 下载代码 1 –项目结构 2 –项目依赖性 除了典型的Spring Boot依赖关系之外我们还在 LEGACYHTML5模式下使用嵌入式HSQLDB数据库和nekohtml 。 ?xml version1.0 encodingUTF-8?
project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersiongroupIdcom.michaelcgood/groupIdartifactIdmichaelcgood-validation-thymeleaf/artifactIdversion0.0.1/versionpackagingjar/packagingnamemichaelcgood-validation-thymeleaf/namedescriptionMichael C Good - Validation in Thymeleaf Example Application/descriptionparentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion1.5.7.RELEASE/versionrelativePath/ !-- lookup parent from repository --/parentpropertiesproject.build.sourceEncodingUTF-8/project.build.sourceEncodingproject.reporting.outputEncodingUTF-8/project.reporting.outputEncodingjava.version1.8/java.version/propertiesdependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-jpa/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-thymeleaf/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.hsqldb/groupIdartifactIdhsqldb/artifactIdscoperuntime/scope/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependency!-- legacy html allow --dependencygroupIdnet.sourceforge.nekohtml/groupIdartifactIdnekohtml/artifactIdversion1.9.21/version/dependency/dependenciesbuildpluginsplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactId/plugin/plugins/build/project3 –模型 在我们的模型中我们定义 自动生成的ID字段 名称字段不能为空 名称必须在2到40个字符之间 由Email批注验证的电子邮件字段 布尔字段“开放日”允许潜在学生指出她是否想参加开放日 布尔字段“订阅”用于订阅电子邮件更新 注释字段是可选的因此没有最低字符要求但有最高字符要求 package com.michaelcgood.model;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;import org.hibernate.validator.constraints.Email;Entity
public class Student {IdGeneratedValue(strategy GenerationType.AUTO)private Long id;NotNullSize(min2, max40)private String name;NotNullEmailprivate String email;private Boolean openhouse;private Boolean subscribe;Size(min0, max300)private String comments;public Long getId() {return id;}public void setId(Long id) {this.id id;}public String getName() {return name;}public void setName(String name) {this.name name;}public String getEmail() {return email;}public void setEmail(String email) {this.email email;}public Boolean getOpenhouse() {return openhouse;}public void setOpenhouse(Boolean openhouse) {this.openhouse openhouse;}public Boolean getSubscribe() {return subscribe;}public void setSubscribe(Boolean subscribe) {this.subscribe subscribe;}public String getComments() {return comments;}public void setComments(String comments) {this.comments comments;}}4 –储存库 我们定义一个存储库。 package com.michaelcgood.dao;import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;import com.michaelcgood.model.Student;Repository
public interface StudentRepository extends JpaRepositoryStudent,Long {}5 –控制器 我们注册StringTrimmerEditor将空字符串自动转换为空值。 当用户发送POST请求时我们希望接收该Student对象的值因此我们使用ModelAttribute来做到这一点。 为确保用户发送的值有效我们接下来使用适当命名的Valid批注。 BindingResult必须紧随其后否则在提交无效数据而不是保留在表单页面时 将为用户提供错误页面。 我们使用if ... else来控制用户提交表单时发生的情况。 如果用户提交了无效数据则该用户将保留在当前页面上而在服务器端将不再发生任何事情。 否则应用程序将使用用户的数据并且用户可以继续。 在这一点上检查学生的姓名是否为空是多余的但是我们这样做。 然后我们调用下面定义的方法checkNullString 以查看注释字段是空的String还是null。 package com.michaelcgood.controller;import java.util.Optional;import javax.validation.Valid;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import com.michaelcgood.dao.StudentRepository;
import com.michaelcgood.model.Student;Controller
public class StudentController {InitBinderpublic void initBinder(WebDataBinder binder) {binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));}public String finalString null;Autowiredprivate StudentRepository studentRepository;PostMapping(value/)public String addAStudent(ModelAttribute Valid Student newStudent, BindingResult bindingResult, Model model){if (bindingResult.hasErrors()) {System.out.println(BINDING RESULT ERROR);return index;} else {model.addAttribute(student, newStudent);if (newStudent.getName() ! null) {try {// check for comments and if not present set to noneString comments checkNullString(newStudent.getComments());if (comments ! None) {System.out.println(nothing changes);} else {newStudent.setComments(comments);}} catch (Exception e) {System.out.println(e);}studentRepository.save(newStudent);System.out.println(new student added: newStudent);}return thanks;}}GetMapping(valuethanks)public String thankYou(ModelAttribute Student newStudent, Model model){model.addAttribute(student,newStudent);return thanks;}GetMapping(value/)public String viewTheForm(Model model){Student newStudent new Student();model.addAttribute(student,newStudent);return index;}public String checkNullString(String str){String endString null;if(str null || str.isEmpty()){System.out.println(yes it is empty);str null;OptionalString opt Optional.ofNullable(str);endString opt.orElse(None);System.out.println(endString : endString);}else{; //do nothing}return endString;}} Optional.ofNullablestr; 表示字符串将成为数据类型Optional但是字符串可以为空值。 endString opt.orElse“ None”; 如果变量opt为null则将String值设置为“ None”。 6 – Thymeleaf模板 正如您在上面的Controller映射中所看到的有两个页面。 index.html是我们的主页具有针对潜在大学生的表格。 我们的主要对象是学生因此我们的thobject当然是指该对象 。 我们模型的字段分别进入thfield 。 我们将表单的输入包装在表格中以进行格式化。 在每个表单元格td下我们都有一个条件语句如下所示 […] thif ” $ {fields.hasErrorsname}“ therrors ” * {name}” […] 上面的条件语句意味着如果用户在该字段中输入的数据与我们在Student模型中对该字段的要求不符然后提交表单则在用户返回此页面时显示输入要求。 index.html html xmlnshttp://www.w3.org/1999/xhtmlxmlns:thhttp://www.thymeleaf.orghead
!-- CSS INCLUDE --
link relstylesheethrefhttps://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.cssintegritysha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4VaPmSTsz/K68vbdEjh4ucrossoriginanonymous/link!-- EOF CSS INCLUDE --
/head
body!-- START PAGE CONTAINER --div classcontainer-fluid!-- PAGE TITLE --div classpage-titleh2span classfa fa-arrow-circle-o-left/span Request UniversityInfo/h2/div!-- END PAGE TITLE --div classcolumnform action# th:action{/} th:object${student}methodposttabletrtdName:/tdtdinput typetext th:field*{name}/input/tdtd th:if${#fields.hasErrors(name)} th:errors*{name}NameError/td/trtrtdEmail:/tdtdinput typetext th:field*{email}/input/tdtd th:if${#fields.hasErrors(email)} th:errors*{email}EmailError/td/trtrtdComments:/tdtdinput typetext th:field*{comments}/input/td/trtrtdOpen House:/tdtdinput typecheckbox th:field*{openhouse}/input/td/trtrtdSubscribe to updates:/tdtdinput typecheckbox th:field*{subscribe}/input/td/trtrtdbutton typesubmit classbtn btn-primarySubmit/button/td/tr/table/form/div!-- END PAGE CONTENT --!-- END PAGE CONTAINER --/divscript srchttps://code.jquery.com/jquery-1.11.1.min.jsintegritysha256-VAvG3sHdS5LqTT5A/aeq/bZGa/Uj04xKxY8KM/w9EEcrossoriginanonymous/scriptscriptsrchttps://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.jsintegritysha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txacrossoriginanonymous/script/body
/html 这是用户成功完成表单后看到的页面。 我们使用thtext向用户显示他或她在该字段中输入的文本。 Thanks.html html xmlnshttp://www.w3.org/1999/xhtmlxmlns:thhttp://www.thymeleaf.orghead
!-- CSS INCLUDE --
link relstylesheethrefhttps://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.cssintegritysha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4VaPmSTsz/K68vbdEjh4ucrossoriginanonymous/link!-- EOF CSS INCLUDE --/head
body!-- START PAGE CONTAINER --div classcontainer-fluid!-- PAGE TITLE --div classpage-titleh2span classfa fa-arrow-circle-o-left/span Thank you/h2/div!-- END PAGE TITLE --div classcolumntable classtable datatabletheadtrthName/ththEmail/ththOpen House/ththSubscribe/ththComments/th/tr/theadtbodytr th:eachstudent : ${student}td th:text${student.name}Text .../tdtd th:text${student.email}Text .../tdtd th:text${student.openhouse}Text .../tdtd th:text${student.subscribe}Text .../tdtd th:text${student.comments}Text .../td/tr/tbody/table/div /div!-- END PAGE CONTAINER --/divscriptsrchttps://code.jquery.com/jquery-1.11.1.min.jsintegritysha256-VAvG3sHdS5LqTT5A/aeq/bZGa/Uj04xKxY8KM/w9EEcrossoriginanonymous/scriptscriptsrchttps://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.jsintegritysha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txacrossoriginanonymous/script/body
/html7 –配置 使用Spring Boot Starter并包括Thymeleaf依赖项您将自动拥有/ templates /的模板位置并且Thymeleaf可以直接使用。 因此不需要大多数这些设置。 要注意的一个设置是nekohtml提供的LEGACYHTM5 。 如果需要这使我们可以使用更多随意HTML5标签。 否则Thymeleaf将非常严格并且可能无法解析您HTML。 例如如果您不关闭输入标签Thymeleaf将不会解析您HTML。 application.properties #
# Thymeleaf configurations
#
spring.thymeleaf.check-template-locationtrue
spring.thymeleaf.prefixclasspath:/templates/
spring.thymeleaf.suffix.html
spring.thymeleaf.content-typetext/html
spring.thymeleaf.cachefalse
spring.thymeleaf.modeLEGACYHTML5server.contextPath/8 –演示 主页 在这里我们到达主页。 无效数据 我在名称字段和电子邮件字段中输入了无效数据。 有效数据无评论 现在我在所有字段中输入了有效数据但未提供注释。 不需要提供评论。 在我们的控制器中我们使所有空字符串都为空值。 如果用户未提供注释则将String值设置为“ None”。 9 –结论 包起来 该演示应用程序演示了如何以Thymeleaf形式验证用户输入。 我认为Spring和Thymeleaf与javax.validation.constraints一起可以很好地验证用户输入。 源代码在 Github上 笔记 Java 8的Optional出于某种演示目的而被强加到该应用程序中我想指出的是当使用RequestParam时 如我的PagingAndSortingRepository教程中所示它可以更有机地工作。 但是如果您不使用Thymeleaf则可以将我们不需要的字段设置为Optional 。 Vlad Mihalcea在这里讨论了使用JPA和Hibernate映射Optional实体属性的最佳方法 。 翻译自: https://www.javacodegeeks.com/2017/10/validation-thymeleaf-spring.html