java - Java Spring表单检查输入字符串是否包含特殊字符
问题描述
我正在尝试创建一个 Java Spring 表单来检查输入字符串是否包含特殊字符。例如,当用户键入包含特殊字符的字符串时,将弹出一条消息,说明输入字符串包含特殊字符。
我的问题是如何实现java函数来检查输入字符串中的特殊字符?
模型
package com.mkyong.customer.model;
public class Customer {
String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
控制器
package com.mkyong.customer.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.mkyong.customer.model.Customer;
public class TextBoxController extends SimpleFormController{
public TextBoxController(){
setCommandClass(Customer.class);
setCommandName("customerForm");
}
@Override
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
Customer customer = (Customer)command;
return new ModelAndView("CustomerSuccess","customer",customer);
}
}
客户表格
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<style>
.error {
color: #ff0000;
}
.errorblock{
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding:8px;
margin:16px;
}
</style>
</head>
<body>
<h2>Java Textbox Special Characters</h2>
<form:form method="POST" commandName="customerForm">
<form:errors path="*" cssClass="errorblock" element="div"/>
<table>
<tr>
<td>Keyword:</td>
<td><form:input path="userName" /></td>
<td><form:errors path="userName" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
客户成功
<html>
<body>
<h2>Java Textbox Special Characters</h2>
Keyword: ${customer.userName}
</body>
</html>
解决方案
您可以拥有所有特殊字符的列表并使用正则表达式进行检查:
Pattern regex = Pattern.compile("[$&+,:;=\\\\?@#|/'<>.^*()%!-]"); // fill in any chars that you consider special
if (regex.matcher(stringToCheck).find()) {
// found
}
您还可以查看Guava's CharMatcher
(没有正则表达式并且更具可读性)。您可以像这样构建自己的匹配逻辑:
boolean isAMatch = CharMatcher.WHITESPACE
.or(CharMatcher.anyOf("[$&+,:;=\\\\?@#|/'<>.^*()%!-]")) // fill in any chars that you consider special
.matchesAnyOf(stringToCheck);
推荐阅读
- java - 配置 logback-spring.xml 以拥有一些常见的记录器和一些特定于环境的记录器
- image-processing - 从给定的调色板中找到匹配的颜色
- amazon-web-services - 在 AWS Spot 实例上运行一批作业
- angular - 如何在 three.js 中使用 ArrowHelper 绘制圆柱体
- android - Flutter 程序不显示图像
- amazon-web-services - 当我尝试附加我创建的规则组时,wafv2 webacl cloudformation 出现错误
- flutter - Flutter - NoSuchMethodError:在 null 上调用了 getter 'isNotEmpty'
- docker - 错误:不可满足的约束:在 alpine docker 文件中更新包时
- azure - PowerShell 版本及其管理 Azure Active Directory 的能力有什么区别?
- oauth - 谷歌登录响应没有 idToken ionic4