把Servlet.java升级成JSP
文章目录
修改时记得删掉Tomcat server里面web.xml的相关配置,context.xml不要修改。 新建header.jsp,footer.jsp,MessageArchiever.jsp,删除原来的MessageArchiever.java。 将Entry.html修改成Entry.jsp,然后分别在首尾使用以下代码包含header.jsp和footer.jsp。 {% codeblock lang:jsp %} <%@ include file=”/header.jsp” %> <%@ include file="footer.jsp” %> {% endcodeblock %} 同时修改form的action操作,修改为 {% codeblock lang:jsp %}
footer.jsp
{% codeblock lang:jsp %} <%@page pageEncoding="utf-8”%>
MessageArchiever.jsp
{% codeblock lang:jsp %} <%@ page language="java” contentType="text/html; charset=utf-8” pageEncoding="utf-8”%> <%@ page import="java.io.IOException, java.sql.SQLException, java.text.SimpleDateFormat, javax.naming.Context, javax.naming.InitialContext, javax.naming.NamingException, javax.sql.DataSource, org.apache.commons.dbutils.QueryRunner, koi.StringUtil”%> <%@ include file=”/header.jsp”%> <% int result = 0;
// 设置编码
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");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Object[] param = { name, email, phone, topic, content, sdf.format(new java.util.Date()) };
try {
// 初始化上下文环境,可以从这个环境中取出数据源对象
Context context = new InitialContext();
// 从上下文环境中取出数据源对象,其中jdbc/mysql就是我们在DBCP中配置的数据库源,这个数据库受DBCP的管理
DataSource dSource = (DataSource) context.lookup("java:/comp/env/jdbc/mysql");
QueryRunner qRunner = new QueryRunner(dSource);
result = qRunner.update(sql, param);
response.getWriter().append(Integer.toString(result));
} catch (NamingException | SQLException e) {
e.printStackTrace();
}
%> <%@ include file=”/footer.jsp”%> {% endcodeblock %}