JavaWebServletBUG总结

1.jdk1.8和maven的tomcat6插件不兼容
因为maven默认tomcat插件版本是tomcat6我的jdk是1.8所以需要更换tomcat版本到7以上添加tomcat7插件
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                </plugin>

 添加JDK1.8插件

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>

使用tomcat7:run运行即可

2. tomcat7插件集成错误

 将web.xml旧版代码用以下代码替换

如果不替换web.xml和tomcat7的不兼容问题,导致tomcat7无法启动。

   <?xml version="1.0" encoding="UTF-8"?>
   <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
            version="4.0"
            metadata-complete="true">
 
   </web-app>

3.maven的servlet-api包冲突

 将maven的servlet-api依赖,设置为provided依赖。

provided依赖只在编译和测试的过程中有效,生成war包的时候不会加入,不写的话会,因为web服务器已经存在servlet-api和tomcat等服务了,会出现包冲突。

 4.解决Cookie不能存储中文问题,并且解决Cookie中文乱码问题。

设置cookie时,将cookie值使用utf-8格式进行编码。

        // 设置cookie
        Cookie cookie = new Cookie("username", URLEncoder.encode("老王","utf-8"));
        resp.addCookie(cookie);

获取cookie时,将cookie进行解码。

        resp.setContentType("text/html;charset=utf-8;");
        // 获取cookie
        Cookie[] cookies = req.getCookies();
        if(cookies != null){
            for (Cookie cookie : cookies) {
                resp.getWriter().println("COOKIE Name:"+cookie.getName());
                resp.getWriter().println("COOKIE Value:"+ URLDecoder.decode(cookie.getValue(), "utf-8"));
            }
        }

编码和解码操作需成对出现,否则将出现乱码情况。

  

原文地址:https://www.cnblogs.com/chao666/p/12807378.html