这是html中的代码
<body>
<p>
<form action="findServlet" method="post">
请输入你要查询的商品编号:<input type="text" id="shopId"/>
<input type="submit" value="查询"/>
</form>
</p>
</body>
这是web.xml中的代码
<servlet>
<servlet-name>findServlet</servlet-name>
<servlet-class>com.huaten.findServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>findServlet</servlet-name>
<url-pattern>/findServlet</url-pattern>
</servlet-mapping>
</web-app>
这是BaseDAO.java:
package com.huaten;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.jsp.jstl.sql.Result;
import javax.servlet.jsp.jstl.sql.ResultSupport;
//实现这个接口表示Serializable可以被序列划
public class BaseDAO implements Serializable {
private static final String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String url="jdbc:sqlserver://localhost:1433;databasename=jspT02";
//获取新的连接
public static Connection getConnection()
{
Connection con=null;
try {
Class.forName(driver);
con=DriverManager.getConnection(url,"sa","123456");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
//运行有结果,有参数的sql语句
public static Result runSelectsql(String sql,Object[]params)
{
Connection con=null;
PreparedStatement ps=null;
ResultSet res=null;
Result result=null;
try {
//调用方法得到连接
con=getConnection();
ps=con.prepareStatement(sql);
//循环设置参数
for(int i=0;i<params.length;i++)
{
ps.setObject(i+1, params[i]);
}
//获取resultSet对象
res=ps.executeQuery();
//通过ResultSupport对象的toResult方法获取result对象
result=ResultSupport.toResult(res);
} catch (Exception e) {
e.printStackTrace();
}finally
{
try {
res.close();
ps.close();
con.close();
} catch (Exception e2) {
e2.printStackTrace();
}
//返回result
return result;
}
}
}
这是findServlet.java
package com.huaten;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.jstl.sql.Result;
public class findServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=gbk");
PrintWriter out=resp.getWriter();
int id=Integer.parseInt(req.getParameter("shopId"));
//构造Sql语句
String sql="select * from tb_shop where id=?";
Object [] params={id};
//调用BaseDAO方法返回Result对象
Result result=BaseDAO.runSelectsql(sql, params);
//resut对象的getRowCount方法用于获取返回的记录条数
if(result.getRowCount()==1)
{
out.print("存在");
}
else
{
out.print("找不到对应的商品");
}
}
}
数据库中有对应的数据,可从html页面点击提交后出现服务器端出错错误 500 |