java校验器的代码 Java参数检验
求Java大神给个代码!计算验证条形码
public class Ean13Barcode {
创新互联网站建设公司一直秉承“诚信做人,踏实做事”的原则,不欺瞒客户,是我们最起码的底线! 以服务为基础,以质量求生存,以技术求发展,成交一个客户多一个朋友!专注中小微企业官网定制,成都网站设计、成都做网站,塑造企业网络形象打造互联网企业效应。
private String code;
public Ean13Barcode(String code) {
super();
this.code = code;
}
public String encode() {
if (null == code) {
return "";
}
char[] codes = code.toCharArray();
int sum = 0;
for (int i = 0; i codes.length; i++) {
int num = codes[i] - '0';
if (isEven(num)) {
sum += num;
} else {
sum += num * 3;
}
}
int x = sum % 10;
return code + (x == 0 ? 0 : 10 - x);
}
private boolean isEven(int x) {
return x % 2 == 0;
}
public static void main(String[] args) {
System.out.println(new Ean13Barcode("692223361219").encode());
}
}
信用卡号码校验(java代码实现)
#includestdio.h
main()
{int i,n=0,m=0;
char a[16];
printf("输入卡号:\n");
scanf("%s",a);
for(i=0;i16;i++)
a[i]=a[i]-'0';
for(i=1;i16;i=i+2)
n+=a[i];
for(i=0;i16;i=i+2)
{a[i]+=a[i];
if(a[i]9)
a[i]-=9;
m+=a[i];
}
if((n+m)==70)
printf("成功");
else
printf("失败");
scanf("%s",a);
}你可以参考哈
哪位大哥用java写过CRC8校验, 多项式X7 +X6 +X5 +X2 +1,求代码?
代码如下
public static byte CRC8(byte[] buffer)
{
byte crc = 0;
for (int j = 0; j buffer.Length; j++)
{
crc ^= buffer[j];
for (int i = 0; i 8; i++)
{
if ((crc 0x01) != 0)
{
crc = 1;
crc ^= 0x8c;
}
else
{
crc = 1;
}
}
}
return crc;
}
Java程序——奇偶校验
debug跟应该能看出来。
?=[0-9] 这个正则表达式的规则是取每一个数字的前一位,第一个是数字取到空了,要处理下第一位。
应该就是这个问题了
如何使用java validation api进行参数校验
JAVA中通过Hibernate-Validation进行参数验证
在开发JAVA服务器端代码时,我们会遇到对外部传来的参数合法性进行验证,而hibernate-validator提供了一些常用的参数校验注解,我们可以拿来使用。
1.maven中引入hibernate-validator对应的jar:
dependency
groupIdorg.hibernate/groupId
artifactIdhibernate-validator/artifactId
version4.3.1.Final/version
/dependency
2.在Model中定义要校验的字段(即该字段不能为空,并且最大长度为14):
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class PayRequestDto {
/**
* 支付完成时间
**/
@NotEmpty(message="支付完成时间不能空")
@Size(max=14,message="支付完成时间长度不能超过{max}位")
private String payTime;
public String getPayTime() {
return payTime;
}
public void setPayTime(String payTime) {
this.payTime = payTime;
}
}
3.定义Validation工具类:
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.hibernate.validator.HibernateValidator;
import com.atai.framework.lang.AppException;
public class ValidationUtils {
/**
* 使用hibernate的注解来进行验证
*
*/
private static Validator validator = Validation
.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
/**
* 功能描述: br
* 〈注解验证参数〉
*
* @param obj
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
public static T void validate(T obj) {
SetConstraintViolationT constraintViolations = validator.validate(obj);
// 抛出检验异常
if (constraintViolations.size() 0) {
throw new AppException("0001", String.format("参数校验失败:%s", constraintViolations.iterator().next().getMessage()));
}
}
}
4.在代码中调用工具类进行参数校验:
ValidationUtils.validate(requestDto);
以下是对hibernate-validator中部分注解进行描述:
@AssertTrue 用于boolean字段,该字段只能为true
@AssertFalse 该字段的值只能为false
@CreditCardNumber 对信用卡号进行一个大致的验证
@DecimalMax 只能小于或等于该值
@DecimalMin 只能大于或等于该值
@Digits(integer=,fraction=) 检查是否是一种数字的整数、分数,小数位数的数字
@Email 检查是否是一个有效的email地址
@Future 检查该字段的日期是否是属于将来的日期
@Length(min=,max=) 检查所属的字段的长度是否在min和max之间,只能用于字符串
@Max 该字段的值只能小于或等于该值
@Min 该字段的值只能大于或等于该值
@NotNull 不能为null
@NotBlank 不能为空,检查时会将空格忽略
@NotEmpty 不能为空,这里的空是指空字符串
@Null 检查该字段为空
@Past 检查该字段的日期是在过去
@Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式
@Range(min=,max=,message=) 被注释的元素必须在合适的范围内
@Size(min=, max=) 检查该字段的size是否在min和max之间,可以是字符串、数组、集合、Map等
@URL(protocol=,host,port) 检查是否是一个有效的URL,如果提供了protocol,host等,则该URL还需满足提供的条件
@Valid 该注解主要用于字段为一个包含其他对象的集合或map或数组的字段,或该字段直接为一个其他对象的引用,这样在检查当前对象的同时也会检查该字段所引用的对象
校验FTP是否能正常连接的Java类
先写一个异常类,如果FTP的用户名或者密码不正确就通过这个异常类抛出异常,代码如下:
FTPException.java
public class FTPException extends Exception {
private int replyCode = -1;
public FTPException(String msg) {
super(msg);
}
public FTPException(String msg, String replyCode) {
super(msg);
try {
this.replyCode = Integer.parseInt(replyCode);
}
catch (NumberFormatException ex) {
this.replyCode = -1;
}
}
public int getReplyCode() {
return replyCode;
}
}
FtpUtil.java校验类代码如下:
import java.io.*;
import java.net.Socket;
public class FtpUtils {
static Logger logger = Logger.getLogger(FtpUtils.class);
public static boolean debugResponsesUtil = false;
public static PrintWriter printlog = null;
public static boolean getFtpLogin(String ip, String port, String username, String password){
boolean flag = false; //默认FTP未连接
printlog = new PrintWriter(System.out);
debugResponsesUtil = true;
try {
Socket controlSock = new Socket(ip, Integer.parseInt(port));
if (controlSock == null) {
try{
throw new IllegalStateException("Failed to set timeout - no control socket");
} catch (IllegalStateException e) {
logger.error(e.getMessage());
e.printStackTrace();
return flag;
}
}
controlSock.setSoTimeout(0);
InputStream is = controlSock.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// output stream
OutputStream os = controlSock.getOutputStream();
Writer writer = new OutputStreamWriter(os);
String replyStr1 = curReadReply(reader); //第一次调用curReadReply函数
String replyCodeStr1 = replyStr1.substring(0, 3);
String replyText1 = replyStr1.substring(4);
if (replyCodeStr1.equals("220")) {
debugResponsesUtil = false;
} else {
// if unexpected reply, throw an exception
try {
throw new FTPException(replyText1, replyCodeStr1);
} catch (FTPException e) {
logger.error(e.getMessage());
e.printStackTrace();
return flag;
}
}
if (debugResponsesUtil) {
printlog.println("--- " + "USER " + username);
}
//send it
writer.write("USER " + username + "\r\n");
writer.flush();
String replyStr2 = curReadReply(reader); //第二次调用curReadReply函数
String replyCodeStr2 = replyStr2.substring(0, 3);
String replyText2 = replyStr2.substring(4);
if (replyCodeStr2.equals("331")) {
debugResponsesUtil = false;
} else {
//if unexpected reply, throw an exception
try {
throw new FTPException(replyText2, replyCodeStr2);
} catch (FTPException e) {
logger.error(e.getMessage());
e.printStackTrace();
return flag;
}
}
if (debugResponsesUtil) {
printlog.println("--- " + "PASS " + password);
}
//send it
writer.write("PASS " + password + "\r\n");
writer.flush();
String replyStr3 = curReadReply(reader); //第三次调用curReadReply函数
String replyCodeStr3 = replyStr3.substring(0, 3);
String replyText3 = replyStr3.substring(4);
if (replyCodeStr3.equals("230")) {
debugResponsesUtil = false;
} else {
//if unexpected reply, throw an exception
try {
throw new FTPException(replyText3, replyCodeStr3);
} catch (FTPException e) {
logger.error(e.getMessage());
e.printStackTrace();
return flag;
}
}
controlSock.setSoTimeout(1000);
flag = true; //FTP连接成功
controlSock.setSoTimeout(10000);
} catch (IOException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
return flag;
}
private static String curReadReply(BufferedReader reader){
String firstLine = null;
try {
firstLine = reader.readLine();
} catch (IOException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
if (firstLine == null || firstLine.length() == 0) {
try{
throw new IOException("Unexpected null reply received");
} catch (IOException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
StringBuffer reply = new StringBuffer(firstLine);
if (debugResponsesUtil) {
printlog.println(reply.toString());
}
String replyCode = reply.toString().substring(0, 3);
//check for multiline response and build up
//the reply
if (reply.charAt(3) == '-') {
boolean complete = false;
while (!complete) {
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
if (line == null) {
try{
throw new IOException("Unexpected null reply received");
} catch (IOException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
if (debugResponsesUtil) {
printlog.println(line);
}
if (line.length() 3 line.substring(0, 3).equals(replyCode) line.charAt(3) == ' ') {
reply.append(line.substring(3));
complete = true;
} else { //not the last line
reply.append(" ");
reply.append(line);
}
} //end while
} //end if
return reply.toString();
}
}
摘自:iteye博客地址如下:
文章名称:java校验器的代码 Java参数检验
URL网址:http://cdiso.cn/article/dooosgd.html