2014年工作中遇到的20个问题:81-100

81.MySQL执行sql命令的时候,总是报一个陈旧的sql脚本错误。只要一致性,就崩溃,搞的我也要崩溃了。

先后尝试了 重新安装MySQL-Front,完全清除MySQL-Front再重新安装,都不行。

最后又尝试了,删除那个错误命令相关的数据库,还是不行。

最后的最后,在系统数据目录“C:UsersAdministratorAppDataRoaming”删除了Mysql-front的会话记录,最终解决了这个问题。


82.Freemarker遍历map和list搞混了,另外FTL语法和Java的遍历也有点晕。

Freemarker

   <#list page.params?keys as key>

          ${key} ${data.params[key]}

    </#list>


错误的写法:

  <#list page.params as key>

          ${key} ${data.params[key]}

  </#list>

Java

for (Map.Entry<String, String> entry : params.entrySet()) {

entry.getKey();

entry.getValue();

}

83.Windows系统可以配置“本地的DNS域名解析”

  C:WindowsSystem32driversetchosts。

  

  好处是可以模拟 域名访问,比如fansunion.cn 127.0.0.1,其中的一个功能是Cookie和域名绑定。

  早上,某同事说服务器访问不了,但是我查看了服务器是正常的,而且我也可以访问,因此断定

  他的hosts被修改了。

  

  果不其然,他晚上进行了“杀毒”,把这个给注释了。

  

  杀毒软件为什么会注释host的一些配置呢?我分析下,发现这个是“劫持网站访问”的一种手段,

  比如你访问淘宝的时候,把你“引导到”假的,然后你就坑了。

  

84.FreeMarker的插值有如下两种类型:

    1.通用插值${expr};

2.数字格式化插值:#{expr}或#{expr;format} 


85.Http空参数和Null参数,Java字符串空与Null。

   Java后端接收参数定义

/** 排序字段 */

private String orderBy;

/** 升序还是降序 asc,desc */

private String order;

http://localhost:8080/news/list.html?pageNo=2&pageSize=10&orderBy=&order=

   后端接收的orderBy和order都是Java字符串的"",不是null

http://localhost:8080/news/list.html?pageNo=2&pageSize=10

   orderBy和order都是null(如果没有默认值的话)

   

另外,Java的String 的 "" 不等于 null。

StringUtils.isEmpty()更常用额。


86.Maven中的DependencyManagement和Dependencies。

里介绍一个在父项目中的根结点中声明dependencyManagement和dependencies的区别

dependencyManagement

Maven 使用dependencyManagement 元素来提供了一种管理依赖版本号的方式。通常会在一个组织或者项目的最顶层的父POM 中看到dependencyManagement 元素。使用pom.xml 中的dependencyManagement 元素能让

所有在子项目中引用一个依赖而不用显式的列出版本号。Maven 会沿着父子层次向上走,直到找到一个拥有dependencyManagement 元素的项目,然后它就会使用在这个dependencyManagement 元素中指定的版本号。

参考:http://liugang594.iteye.com/blog/1687781



87.Freemarker打印日期时间,不能直接打印java.util.Date.

${news.create_time?datetime}


Can't convert the date to string, because it's not known which parts of the date variable are in use.


Tip: Use ?time, ?date or ?datetime to tell FreeMarker which parts of the date is used.

Tip: For programmers: Use java.sql.Date/Time/Timestamp instead of java.util.Date in the data-model to avoid this ambiguity.


The failing instruction (FTL stack trace):

----------

==> ${create_time}  [in template "news/add_succeed.html" at line 12, column 107]


数据库DateTime类型的日期字段,默认会被Mybatis转换为java.sql.Timestap,这种可以直接被Freemarker直接打印。


java.util.Date可行方法:${create_time?string("yyyy-MM-dd HH:mm:ss")}


88.SpringMVC与Freemarker拦截。

Freemarker配置

<bean id="viewResolver"

class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">

<property name="viewClass"

value="cn.fansunion.raikou.base.controller.BaseFreeMarkerView" />

<property name="cache" value="true" />

<property name="order" value="0" />

<property name="prefix" value="" />

<property name="suffix" value=".html" />

<property name="contentType" value="text/html;charset=UTF-8"></property>

<property name="requestContextAttribute" value="request" />

<property name="exposeSpringMacroHelpers" value="true" />

<property name="exposeRequestAttributes" value="true" />

<property name="exposeSessionAttributes" value="true" />

</bean>

@RequestMapping("/ueditor/config")

public void config(HttpServletRequest request,

HttpServletResponse response, String action) {

//response.setContentType("text/html"); 会被Freemarker拦截,渲染html页面;打不跟踪发现,SpringMVC会再次寻找视图文件,getModelAndView

response.setContentType("application/json");//不会被Freemarker再次渲染

String rootPath = request.getSession().getServletContext()

.getRealPath("/");

try {

String exec = new ActionEnter(request, rootPath).exec();

PrintWriter writer = response.getWriter();

writer.write(exec);

writer.flush();

writer.close();

} catch (IOException e) {

e.printStackTrace();

}

}


89.SpringMVC配置路径语法问题

<mvc:resources mapping="/static/**" location="/static/" />

    <mvc:resources mapping="/ueditor/**" location="${setting.upload_root_path}/ueditor/**" />

SpringMVC的Resource有一套自己的语法,“file:c:/img”,"classpath:config/config.properties"

根据前缀,选择不同的Resource实现。

我想把访问图片的静态资源,直接请求到某个静态资源目录,不再走Controller。

有个问题需要注意:"file:"这种语法,是SpringMVC特有的语法,其它API是不支持的。

比如Java.util.FIle 不支持 file:C:/img。

操作系统方面,Windows系统,“file:C:/img”等价于“C:/img”都可以访问,

而Linux系统“file:/home/img”是不能访问的。

因此,我们建议在 .properties最原始的配置文件中,按照最标准的语法配置,setting.upload_root_path=file:C:\img。

在SpringMVC的特殊配置里,加上特有的“配置信息”,即

   <mvc:resources mapping="/ueditor/**" location="file:${setting.upload_root_path}/ueditor/**" />

   

 "file:","classpath:"只出现在SpringMVC自己的配置中,.properties配置的变量用最标准的语法,保证属性可以通用。


90. 百度UEditor-Java版的java源码有问题,

  com.baidu.ueditor.upload.Base64Uploader。

  

  原来错误的Eclipse会报错的写法:

  private static byte[] decode(String content) {

return Base64.decodeBase64(content);

}

  Apache的org.apache.commons.codec.binary.Base64的decodeBase64方法只接收byte[]这种参数,而非String。

  正确的写法:

  private static byte[] decode(String content) {

return Base64.decodeBase64(content.getBytes());

}

91.UEditor的JSP版本,需要直接访问/ueditor/jsp/controller.jsp,不够灵活。

   我把这个jsp改造成了Controller,并且在Controller里设置了图片上传等目录,源代码原来用的是“网站的根目录”,

   这样服务器如果重启,上传的图片可能就没有了。

   用户或者说自己的数据还是非常关键的。

   

92.数据库空日期。

随手向数据库的日期update_time方了个“0000-00-00 00:00:00”,结果系统报错了。

“ java.sql.SQLException: Value '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp ”

Mybatis默认把mysql的date-time转换成java.sql.Timestamp,但是“0000-00-00 00:00:00”不合法。

解法:数据库连接字符串,增加zeroDateTimeBehavior=convertToNull

jdbc.url=jdbc:mysql://localhost:3306/raikou?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull


93.SpringMVC的JSON请求和JSON响应。

  <bean

class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">

<property name="defaultContentType" value="application/json" />

<property name="mediaTypes">

<map>

<entry key="html" value="text/html" />

<entry key="json" value="application/json" />

<entry key="xml" value="application/xml" />

</map>

</property>

<property name="defaultViews">

<list>

<bean

class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">

</bean>

<bean id="marshallingView"

class="org.springframework.web.servlet.view.xml.MarshallingView">

<property name="marshaller">

<bean id="xStreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">

<property name="autodetectAnnotations" value="true" />

</bean>

</property>

<property name="contentType" value="application/xml" />

</bean>

</list>

</property>

</bean>

有了以上配置,.json请求的响应就是json格式,数据直接放到model中,例如:

// 增加一条News

@RequestMapping(value = "/doadd")

public void doAdd(@RequestParam Map<String, Object> params,

HttpServletRequest request, Model model) {

newsService.add(params);

model.addAttribute("code", 1);

model.addAttribute("id", params.get("id"));

}

但是下面的用法能够接收和响应,但不会有任何输出:

@RequestMapping(value = "/doadd")

public void doAdd(@RequestParam Map<String, Object> params,

HttpServletRequest request,HttpServletResponse response, Model model) {

newsService.add(params);

model.addAttribute("code", 1);

model.addAttribute("id", params.get("id"));

}

即配置JSON响应,不能再有HttpServletResponse response,应该会覆盖配置文件中的。



94.HTML转义。

   页面中直接显示HTML,很可能会破坏页面的布局,应该对可视化编辑工具生成的内容,进行转义。

   Freemarker内置了xhtml函数,可以转换。

   ${article.summary?xhtml}


95.PDF生成内容乱码。

  XMLWorkerHelper instance = XMLWorkerHelper.getInstance();

  instance.parseXHtml(writer, document, stream, null,Charset.forName("UTF-8"), new MyFontProvider());

  最后一个参数中,设置字体,

public Font getFont(String fontname, String encoding, boolean embedded,

float size, int style, BaseColor color) {

BaseFont bfChinese;

try {

bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",

BaseFont.NOT_EMBEDDED);

Font keyfont = new Font(bfChinese, 16);

return keyfont;

} catch (DocumentException | IOException e) {

e.printStackTrace();

}

return null;

}

记得下载亚洲字体:itext-asian.jar。


96.下载文件名称乱码。

直接使用 中文:IE、Firefox都是乱码。

URL编码:java.net.URLEncoder.encode(fileName, "UTF-8"));  IE好,Firefox都是编码的字母。

最好的办法,用ISO8859-1编码。

new String( title.toString().getBytes("utf-8"), "ISO8859-1" );

参考:http://lj830723.iteye.com/blog/1415479



97.PDF下载弹出下载对话框

#弹出下载对话框,进行下载

res.addHeader("Content-type", "application/pdf;charset=utf-8");

res.addHeader("Content-Disposition", "attachment;filename=" + goodTitle+ ".pdf");


比较奇怪的问题是,QQ、IE、Firefox都可以正常下载,而Chrome却不行,控制台报错:

Resource interpreted as Document but transferred with MIME type application/pdf: "http://localhost:8080/article/download/pdf?id=100103".

为什么会被结识成“Document”呢?


修改:“application/octet-stream pdf”也不行

使用HTML5 download属性也不行<a href="" download />


#flush和close HttpServletResponse还是不行

res.getOutputStream().flush();

res.getOutputStream().close();


参考一个老外的答案:

After looking at the header coming from the IIs server I noticed that one of the headers was Transfer Encoding was chunked. Looking deeper into the issue. It seems that Google Chrome doesn’t handle that chunked encoding well. So it just cancels the download.

The fix on the server was to add the Content-Length header to the code.

Response.AddHeader(“Content-Length”, drDocument["size"].ToString());

After adding the Content-Length header Google Chrome properly downloaded the file and displayed it normally.

I would of thought Google would of done a better job of handling that. However, it is what it is. And we are able to fix it via code.


增加Content-Length头,不行

http://www.s-t-f-u.com/2011/06/13/google-chrome-resource-interpreted-as-document-but-transferred-with-mime-type-applicationpdf/


#终极解决方案

我的Chrome版本是33.0.1750.154 m,同事小甲的Chrome版本是38.0,可以正常下载并打开。

说明,这个是Chrome版本问题,不再针对这个特殊版本做处理。


#直接在浏览器内打开PDF

attachment;filename=inline8.Maven项目,jar包通过pom.xml配置,部分jar包放到web-inf/lig目录下,可能有问题。


99.注册之后跳转到登录系统进行校验,根据用户名+种子+日期进行校验,

为了偷懒只比较 两个Date日期是同一天,比较两个日期格式串是否一样就可以了“yyyy-MM-dd”格式。

这种检验Token是否有效的方式,存在一个“漏洞”,存在着“跨天登陆”的可能性。

最准确的方法是,比较2个日期相差在5秒之内。

date.getTime();两个时间相减,相差在5000之内就可以了。


100.Spring与Freemarker整合的时候,不能配置多个FreemarkerConfig、

<bean id="freemarkerMailConfig"

        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">

<bean id="freemarkeronfig"

        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">

项目启动的时候不会报错,但是在渲染页面的时候,会报错。

Must define a single FreeMarkerConfig bean in this web application context (may be inherited): FreeMarkerConfigurer is the usual implementation. This bean may be given any name.; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.web.servlet.view.freemarker.FreeMarkerConfig] is defined: expected single matching bean but found 2: freemarkerConfig,freemarkerMailConfig

at org.springframework.web.servlet.view.freemarker.FreeMarkerView.autodetectConfiguration(FreeMarkerView.java:177)

Freemarker从Spring上下文“获取唯一的FreeMarkerConfig”,有多个的时候就报错了。


我倒是觉得,对于Freemarker邮件模版生成HTML的方式,使用独立于Spring的方式更佳。

某个项目需要发送模版邮件,引入工具包就可以了,不用再配置Spring的Bean。


原文首发:http://fansunion.cn/article/detail/49.html

原文地址:https://www.cnblogs.com/qitian1/p/6463168.html