首先我想说一下我要实现的东西,其实是相当简单,在一个JSP页面通过FORM表单查询ID号的数据信息,将ID号提交给一个Servlet,然后由servlet返回到当前的JSP
页面.具体的代码如下:
//JSP表单页面代码如下
<%@ page language="java" import="java.util.*,database.*" contentType="text/html;charset=gb2312" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'dtudata.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="dtu,dtu,dtu">
<meta http-equiv="description" content="This is my dtudata.jsp">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form method="get" action="DTUServlet" >
<table>
<tr><td><input type="text" name="id"/></td><td><input type="submit" value="提交"/></td></tr>
</table>
</form>
<%
if(request.getParameter("ID")!=null){
String data=request.getParameter("ID");
out.println("<center><p style=color:#3300FF;font-size:18px>ID"+data+"无查询结果,请确认输入的Modem编号</p></center>");
}else{
out.println("");
}
%>
<%
if(session.getAttribute("modemdata")!=null){
response.setContentType("text/html");
out.println(" <table align=left><tr align=center><td width=80 align=center>模板ID</td><td width=100>接收数据长度</td><td width=180>接收数
据时间</td><td >接收的数据</td></tr>");
ArrayList al=(ArrayList)session.getAttribute("modemdata");
for(int i=0;i<al.size();i++){
ModemDataBean md=new ModemDataBean();
md=(ModemDataBean)al.get(i);
out.println("<tr><td align=center width=80>"+md.getID()+"</td>");
out.println("<td width=100 align=center>"+md.getlength()+"</td>");
out.println("<td width=180>"+md.getReceiveTime()+"</td>");
out.println("<td>"+md.getData()+"</td></tr>");
}
}
%>
</body>
</html>
//=======servlet页面代码如下
package servletPackage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import database.DataDeal;
public class DTUServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public DTUServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String id=request.getParameter("id");
System.out.println("id========="+id);
ArrayList al=DataDeal.getDTUIDData(id);
System.out.println("arraylist=========="+al);
if(al.size()!=0){
HttpSession hs=request.getSession();
hs.setAttribute("modemdata",al);
//request.getRequestDispatcher("dtudata.jsp").forward(request,response);
response.sendRedirect("dtudata.jsp");
}else{
response.sendRedirect("dtudata.jsp?ID="+id);
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
}
//===CONN
package database;
import java.io.File;
import java.sql.*;
import java.util.logging.*;
public class Conn {
private static Connection conn;
public static Connection getDBConn(){
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/kydata?
user=root&password=123456&useUnicode=true&characterEncoding=GBK");
} catch (Exception e) {
Logger logger=Logger.getLogger(Conn.class.getName());
logger.fine("===数据库异常===="+e);
}
return conn;
}
}
//===数据库处理
package database;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.logging.Logger;
import test.ServerTest;
import ky.ModemData;
public class DataDeal{
//写入数据
public static void insertData(ModemData md) {
PreparedStatement ps = null;
Connection conn=null;
try {
conn=Conn.getDBConn();
SimpleDateFormat newk = new SimpleDateFormat ("yyyy.MM.dd hh:mm:ss");
String time=newk.format(md.ReceiveTime);
String sql="insert into dtu(dtu_modemid,dtu_length,dtu_time,dtu_data) values('"+md.ID+"',"+md.length+",'"+time.trim()
+"','"+ServerTest.ByteToHexString(md.Data).trim()+"')";
ps=conn.prepareStatement(sql);
ps.executeUpdate();
} catch (Exception e) {
Logger logger=Logger.getLogger(DataDeal.class.getName());
logger.fine("数据库添加数据失败"+e);
e.printStackTrace();
}finally{
if(ps!=null){
try {
ps.close();
} catch (Exception e) {
Logger logger=Logger.getLogger(DataDeal.class.getName());
logger.fine("数据库链接关闭失败"+e);
}
ps=null;
}if(conn!=null){
try {
conn.close();
} catch (Exception e) {
Logger logger=Logger.getLogger(DataDeal.class.getName());
logger.fine("数据库链接关闭失败"+e);
}
conn=null;
}
}
}
//读取数据
public static ArrayList getDTUIDData(String id){
PreparedStatement ps = null;
Connection conn=null;
ResultSet rs=null;
ArrayList al=new ArrayList();;
try {
conn=Conn.getDBConn();
String sql="select dtu_modemid,dtu_length,dtu_time,dtu_data from dtu where dtu_modemid="+id;
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
ModemDataBean md=new ModemDataBean();
md.setID(rs.getString(1));
md.setlength(rs.getInt(2));
md.setReceiveTime(rs.getString(3));
md.setData(rs.getString(4));
al.add(md);
}
} catch (Exception e) {
Logger logger=Logger.getLogger(DataDeal.class.getName());
logger.fine("数据库查询数据失败"+e);
}finally{
if(rs!=null){
try {
rs.close();
} catch (Exception e) {
Logger logger=Logger.getLogger(DataDeal.class.getName());
logger.fine("数据库链接关闭失败"+e);
}
rs=null;
}
if(ps!=null){
try {
ps.close();
} catch (Exception e) {
Logger logger=Logger.getLogger(DataDeal.class.getName());
logger.fine("数据库链接关闭失败"+e);
}
ps=null;
}if(conn!=null){
try {
conn.close();
} catch (Exception e) {
Logger logger=Logger.getLogger(DataDeal.class.getName());
logger.fine("数据库链接关闭失败"+e);
}
conn=null;
}
}
return al;
}
}
刚开始的时候 我在Servlet使用的是转发request.getRequestDispatcher("dtudata.jsp").forward(request,response); 提交之前dtudata.jsp页面中的提交按钮
文显示正常,但把ArrayList传递到dtudata.jsp页面时,提交按钮和从数据库读取的数据也都是乱码,刚开始以为是读取数据库时发生乱码,就修改了链接
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/kydata?user=root&password=123456&useUnicode=true&characterEncoding=GBK");用来处
理中文乱码问题,可是显示时还是一样乱码.而且提交按钮也是乱码,这下我肯定不是数据库的问题了,接下来 我就分析了转发和跳转的区别,查阅了一些资料也没有
发现什么关于这二者之间有关中文乱码的问题.求人不如求己,我试着将request.getRequestDispatcher("dtudata.jsp").forward(request,response);修改为:
response.sendRedirect("dtudata.jsp");竟然成功了 !乱码现象解决了,问题是解决了,但是其原理我还是不是很理解,希望能得到各位的指点.