日期:2014-05-20 浏览次数:20810 次
import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.servlet.*; import javax.servlet.http.*; public class dosearch extends HttpServlet { private static final String CONTENT_TYPE = "text/html; charset=GBK"; public void init(ServletConfig config) throws ServletException { super.init(config); } public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>dosearch</title></head>"); out.println("<body>"); request.setCharacterEncoding("gbk"); String search=request.getParameter("content"); search=search.trim(); String sql=null; String[] lookup=search.split(" "); ServletContext ctx=request.getSession().getServletContext(); //获取Web应用程序初始化参数 String url=ctx.getInitParameter("dbURL"); String driver=ctx.getInitParameter("jdbcDriver"); for(int i=0;i<lookup.length;i++){ //out.print(lookup[i]+"<br />"); sql=sql+"title like '%"+lookup[i].trim()+"%' or "; sql=sql+"some_text like '%"+lookup[i].trim()+ "%' or "; } sql=sql.substring(4,sql.length()-3) ; sql=sql+" order by id desc"; Connection conn; Statement stmt; ResultSet rs; try{ Class.forName(driver); conn=DriverManager.getConnection(url); stmt=conn.createStatement(); sql="select * from test where "+sql; //out.print(sql+"<br />"); //rs=stmt.executeQuery("select * from content where content like '反'"); rs=stmt.executeQuery(sql); /*int count=rs.getRow(); if(count==0){ out.print(count); }else{*/ while(rs.next()){ String title=rs.getString("title"); String content=rs.getString("some_text"); //out.print(content+" "+title+"<br />"); String title1=null; String content2=null; for(int i=0;i<lookup.length;i++){ title1 = title.replace(lookup[i],"<font color = red>"+lookup[i].trim()+"</font>"); //out.print(lookup[i]+"<br />"); //out.print(title1+"<br />"); content2 = content.replace(lookup[i],"<font color=red>"+lookup[i].trim()+"</font>"); //out.print(content2+"<br /><br /><br />"); } out.print(title1+"<br />"); out.print(content2+"<br /><br /><br />"); } // } }catch(Exception ex){ out.print("<p align=center><font size=5 color=red>数据库访问出错!</font></p>"+ex.getMessage()); ex.printStackTrace(); } out.println("</body></html>"); out.close(); } }