B/S登陆例子(JSP+JavaBean+MYSQL)

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
  <display-name>jspLogin</display-name>
</web-app>

 index.jsp

 

 <%
 if(session.getAttribute("passed")==null){
  response.sendRedirect("login.jsp");
  return;
 }
%>
passed!

 login.jsp

 <%@ page contentType="text/html; charset=utf-8" %>
<html>
<head>
<title>
login
</title>
</head>
<body bgcolor="#ffffff">
<%
String flag=request.getParameter("flag");
if(flag!=null&&flag.equals("0")){
  out.println("Pls input valid username and password!<br><br>");
}
%>
<form name="form1" method="post" action="loginSuccess.jsp">
<input name="username" type="text"><br/>
<input name="password" type="password"><br/>
<input name="reset" type="reset" value="reset">
<input name="submit" type="submit" value="submit">
</form>
</body>
</html>

 

loginSuccess.jsp

<%@ page import="test.LoginCheck"%>
<%
String username=request.getParameter("username");
String password=request.getParameter("password");
boolean flag=false;

LoginCheck lc=new LoginCheck();
if(lc.check(username,password)){
    flag = true ;
 out.print("passed!");
}else{
  out.print("failed!");
}
if(flag){
  session.setAttribute("passed","true");
  response.sendRedirect("index.jsp");
}else{
  response.sendRedirect("login.jsp?flag=0");
}
%>


 

LoginCheck.java

package  test;
import  java.sql. * ;

public   class  LoginCheck  {
  
public static boolean check(String username,String password) {
    
boolean flag = false;
    
try {
      String sql 
= "select * from user where username='" + username +
          
"' and password='" + password + "'";
//
      Class.forName("com.mysql.jdbc.Driver");
      Connection conn 
= DriverManager.getConnection(
          
"jdbc:mysql://localhost:3306/test?user=cwb&password=cwb123&useUnicode=true");
      Statement pstmt 
= conn.prepareStatement(sql);
      ResultSet rs 
= pstmt.executeQuery(sql);
      
if (rs.next()) {
        flag 
= true;
      }

//
      rs.close();
      pstmt.close();
      conn.close();
    }
catch(Exception ex){
      ex.printStackTrace();
    }

    
return flag;
  }

}

你可能感兴趣的:(mysql,jsp,String,application,input,import)