搞简单一点就:先写数据库连接类,再写实体类JavaBean,再写一个Servlet,就ok!
1.数据库连接类:Dbbase类
public class DBbase {
private static Connection con =null;
private static ResultSet rs=null;
private static Connection getCon(){
String classStr="com.microsoft.sqlserver.jdbc.SQLServerDriver";
String conStr="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=newsdb";
try {
Class.forName(classStr);
con=DriverManager.getConnection(conStr,"sa","sasa");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static CachedRowSet getRs(userBean ubean){
String sql = "select * from userinfo where username='%s' and userpwd='%s'";
sql = String.format(sql, ubean.getUname(), ubean.getUpwd());
try {
if(con==null || con.isClosed()){
con=getCon();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
CachedRowSet cr=null;
try {
cr = new CachedRowSetImpl();
} catch (SQLException e) {
e.printStackTrace();
}
try {
PreparedStatement pstmt =con.prepareStatement(sql);
rs=pstmt.executeQuery();
cr.populate(rs);
//
rs.close();
//
pstmt.close();
//
con.close();
} catch (Exception e) {
e.printStackTrace();
}
return cr;
}
}
2.实体类:
public class userBean {
private String uname;
private String upwd;
public userBean() {
super();
// TODO Auto-generated constructor stub
}
public userBean(String uname, String upwd) {
super();
this.uname = uname;
this.upwd = upwd;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpwd() {
return upwd;
}
public void setUpwd(String upwd) {
this.upwd = upwd;
}
}
3.写servlet:
String uname = request.getParameter("uname");
String upwd = request.getParameter("upwd");
userBean
ubean=new userBean();
String bname=ubean.setUname(uname);
String bpwd=ubean.setUname(upwd);
DBbase dao = new DBbase ();
boolean f = dao.Checklogin(bname, bpwd);
if (f) {
request.getSession().setAttribute("name", uname);
request.getRequestDispatcher("back.jsp").forward(request,
response);
} else {
request.getSession().setAttribute("err", "登陆失败,用户名或密码错误");
response.sendRedirect("err.jsp");
}