修改Servers目录下Tomcat的web.xml和context.xml两个配置文件

web.xml

增加如下代码: {% codeblock lang:xml %} DB Connection jdbc/mysql javax.sql.DataSource Container {% endcodeblock %}

context.xml

增加如下代码: {% codeblock lang:xml %} <Resource name=“jdbc/mysql” auth=“Container” type=“javax.sql.DataSource” maxIdle=“30” maxWait=“10000” maxActive=“10” username=“root” password=“123456” driverClassName=“com.mysql.jdbc.Driver” url=“jdbc:mysql://localhost:3306/ma?useSSL=false” /> {% endcodeblock %}

MessageArchievr.java

连接的sevlet实例 {% codeblock lang:java %} import java.io.IOException; import java.sql.*; import java.text.SimpleDateFormat;

import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import javax.naming.Context; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

/**

  • Servlet implementation class MessageArchiever */ @WebServlet(description = “Stores all valid users’ message.”, urlPatterns = { “/MessageArchiever” }) public class MessageArchiever extends HttpServlet { private static final long serialVersionUID = 1L;

    /**

    • @see HttpServlet#HttpServlet() */ public MessageArchiever() { super(); // TODO Auto-generated constructor stub }

    /**

    • @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
    •  response)
      

    */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append(“Served at: “).append(request.getContextPath()); }

    /**

    • @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    •  response)
      

    */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

     // jdbc变量提前声明
     Connection conn = null;
     PreparedStatement pStatement = null;
    
     // 提示表单是否提交成功        
     int result;
    
     try {
     	//初始化上下文环境,可以从这个环境中取出数据源对象
     	Context context = new InitialContext();
     	//从上下文环境中取出数据源对象,其中jdbc/mysql就是我们在DBCP中配置的数据库源,这个数据库受DBCP的管理
     	DataSource dSource = (DataSource)context.lookup("java:/comp/env/jdbc/mysql");
     	conn = dSource.getConnection();
     } catch (NamingException | SQLException e1) {
     	// TODO Auto-generated catch block
     	e1.printStackTrace();
     }
    
    
     //设置编码
     request.setCharacterEncoding("utf-8");
     // 要执行的SQL语句
     String sql = "insert into book(name,email,phone,title,content,publishtime) values(?,?,?,?,?,?)";
    
     String name = request.getParameter("name");
     String email = request.getParameter("email");
     String phone = request.getParameter("phone");
     String topic = request.getParameter("topic");
     String content = request.getParameter("content");
    
     try {
     	// pStatement用来执行SQL语句
     	pStatement = conn.prepareStatement(sql);
     	pStatement.setString(1, StringUtil.filterHtml(name));
     	pStatement.setString(2, StringUtil.filterHtml(email));
     	pStatement.setString(3, StringUtil.filterHtml(phone));
     	pStatement.setString(4, StringUtil.filterHtml(topic));
     	pStatement.setString(5, StringUtil.filterHtml(content));
     	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
     	pStatement.setString(6, sdf.format(new java.util.Date()));
     	result = pStatement.executeUpdate();
     	response.getWriter().append(Integer.toString(result));
    
     //} catch (ClassNotFoundException e) {
     	//System.out.println("Sorry,can`t find the Driver!");
     	//e.printStackTrace();
     } catch (SQLException e) {
     	e.printStackTrace();
     } catch (Exception e) {
     	e.printStackTrace();
     } finally {
     	// 再次try catch抓异常
     	try {
     		if (pStatement != null) {
     			pStatement.close();
     		}
     		if (conn != null) {
     			conn.close();
     		}
     	} catch (SQLException e) {
     		e.printStackTrace();
     	}
     }
    
     doGet(request, response);
    

    }

}

{% endcodeblock %}

StringUtil.java

字符串处理工具类: {% codeblock lang:java %} public class StringUtil { /* * 判断输入的字符串参数是否为空 * * @param args 输入的字符串 * * @return true/false */ public static boolean validateNull(String args) { if (args == null || args.length() == 0) { return true; } else { return false; } }

/*
 * 判断输入的字符串是否为空或“null”字符,若是,返回target,若否,返回source参数
 */
public static String chanageNull(String source, String target) {
	if (source==null||source.length()==0||source.equalsIgnoreCase("null")) {
		return target;
	} else {
		return source;
	}
}

/*
 * 过滤<,>,\n字符
 * @param input需要过滤的字符
 * @return 完成过滤后的字符串
 */
public static String filterHtml(String input) {
	if (input==null) {
		return null;
	}
	if (input.length()==0) {
		return input;
	}
	input=input.replaceAll("&", "&amp;");
	input=input.replaceAll("<", "&lt;");
	input=input.replaceAll(">", "&gt;");
	input=input.replaceAll(" ", "&nbsp");
	input=input.replaceAll("'", "&#39;");
	input=input.replaceAll("\"", "&quot;");
	input=input.replaceAll("\n", "<br>");
	return input;
}

} {% endcodeblock %}

Entry.html

{% codeblock lang:html %}

                    <tr>
                        <td>
                            Email:
                        </td>
                        <td>
                            <input type="text" name="email" id="email">
                        </td>
                    </tr>
        
                    <tr>
                        <td>
                            Mobile:
                        </td>
                        <td>
                                <input type="text" name="phone" id="phone">
                        </td>
                    </tr>
        
                    <tr>
                        <td>
                            Topic:
                        </td>
                        <td>
                            <input type="text" name="topic" id="topic">
                        </td>
                    </tr>
        
                    <tr>
                        <td valign="top">
                            Content:
                        </td>
                        <td>
                                <textarea name="content" id="content"></textarea> 
                        </td>
                    </tr>
        
                    <tr>
                        <td>
        
                        </td>
                        <td>
                            <input type="submit" value="Submit" name="submit" id="submit">
                            <input type="reset" value="Reset" name="reset" id="reset">
                        </td>
                    </tr>
        </table>
    </form>
</div>

Entry.css

{% codeblock lang:css %} @charset “UTF-8”;

body{background-color: #85C8E7;}

#title{font-size: 96;text-align: center;}

#MAlink{font-size: 72;text-align: center;}

#content{width: 400px;height: 240px;} {% endcodeblock %}