今天主要说一下在URL 中使用?传值的问题。在显式的使用get方法获取特点数据时,一般会通过?传递参数值,sevlert根据参数在数据库中对应的查找内容。所以,SQL语句需要拼接,要加上后面的参数。参数的获取使用request.getParameter()方法,里面注明获得参数的名称。
import com.alibaba.fastjson.JSONObject; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.*;
import java.util.Date; @WebServlet("/hello")//注解,免于在xml注册,/hello表示在主页后加/hello访问此页面
public class test extends HttpServlet {
private String message;
public void init() throws ServletException{ }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {//相应不带参数的get String dbURL="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=S-T";
String userName="sa";
String userPwd="111";
List<student> students=new ArrayList<>();
Connection dbConn=null;
try {
String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(driverName);//反射JDBC包,这个一定要加,不然会报错
// 设置响应内容类型
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8"); dbConn= DriverManager.getConnection(dbURL,userName,userPwd);
String sql="select * from Student where Sage="+request.getParameter("age");//拼接SQL语句
System.out.println(sql);
Statement statement=dbConn.createStatement();
ResultSet resultSet=statement.executeQuery(sql);
while (resultSet.next()){
student st=new student();
st.setName(resultSet.getString("Sname"));
st.setId(resultSet.getString("Sno"));
st.setSex(resultSet.getString("Ssex"));
st.setAge(resultSet.getString("Sage"));
students.add(st);
}
response.getWriter().println(JSONObject.toJSONString(students));//注意这里不是控制台输出了,是HttpServletResponse,用于返回json给http请求方
//response.getWriter().println(request.getParameter("age"));
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
finally {
try
{//关闭连接
if(dbConn!=null)
{
dbConn.close();
dbConn=null;
}
}
catch(Exception ex)
{
}
} }
}
尝试查找年龄为20岁的学生信息
输出