前言
今天在String转data上花了很多时间,很难受,网站上找了好多没用,心烦意乱。去上了个厕所结果灵感一下就来了。
初学者编写多多交流,如有错误大家积极批评指正。
一、分析
问题
String转data
思路
1.直接转。
2.间接转换类型。
二、实战
我是解决完了才写的博客错误分析暂时没有了
1.直接转
//获得请求参数
try{
String uId = request.getParameter("uId");
System.out.println(uId);
String uPassword=request.getParameter("password");
String uName=request.getParameter("name");
String uNicheng=request.getParameter("w_name");
Date uDatebirth= (Date) new SimpleDateFormat().parse(request.getParameter("data"));
System.out.println(uDatebirth);
String uSex=request.getParameter("sex");
String uPhone=request.getParameter("phone");
System.out.println("参数解析完成");
SqlSession sqlSession = MySqlSession.getSession();
2.间接转换
前面那个强制类型转换失败,我采用的是后面的
try{
String uId = request.getParameter("uId");
System.out.println(uId);
String uPassword=request.getParameter("password");
String uName=request.getParameter("name");
String uNicheng=request.getParameter("w_name");
Date uDatebirth;
uDatebirth = new Date(Long.parseLong(request.getParameter("date")));
String uSex=request.getParameter("sex");
String uPhone=request.getParameter("phone");
System.out.println("参数解析完成");
SqlSession sqlSession = MySqlSession.getSession();
解释
我百度了一下直接转,尝试过了许多次没用,转换思路,先通过Long.parseLong()作为媒介最后转成data。🆗解决问题。
提醒一下
这是parseLong这个方法对参数是有要求的
/**
* Parses the string argument as a signed decimal {@code long}.
* The characters in the string must all be decimal digits, except
* that the first character may be an ASCII minus sign {@code '-'}
* ({@code \u005Cu002D'}) to indicate a negative value or an
* ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
* indicate a positive value. The resulting {@code long} value is
* returned, exactly as if the argument and the radix {@code 10}
* were given as arguments to the {@link
* #parseLong(java.lang.String, int)} method.
*
* <p>Note that neither the character {@code L}
* ({@code '\u005Cu004C'}) nor {@code l}
* ({@code '\u005Cu006C'}) is permitted to appear at the end
* of the string as a type indicator, as would be permitted in
* Java programming language source code.
*
* @param s a {@code String} containing the {@code long}
* representation to be parsed
* @return the {@code long} represented by the argument in
* decimal.
* @throws NumberFormatException if the string does not contain a
* parsable {@code long}.
*/
public static long parseLong(String s) throws NumberFormatException {
return parseLong(s, 10);
}
推荐自己学习源码。我的理解未必正确
总结
思路是软件开发的根本,没有清晰的思路做写出来的代码也不满意。string转data其实很简单,有时候卡住了就不要想。放松一下就好了。
遇到bug心烦意乱,自乱阵脚才是软件开发最大的bug。
最后留下我最耿直的微笑🤪