jsp基礎--登入註冊建立
搞了一個周,總算成功了,現分享給大家,請多指教!
所需軟體:
myeclipse mysql資料庫, Navicat for MySQL(sqlyog視覺化軟體可替換Navicat for MySQL) Tomact7.x
①:首先建立一個WebService project,我命名是zuoye2
如圖:
②:將驅動(我用的是mysql-connector-java-5.0.8-bin)複製到建立的WebService project中WebRoot--WEB-INF-lib目錄下,如圖:
③:新建包xxxx.model,,,,,,新建類,如user(在user類中寫需要的方法,並同時寫set與get方法)
程式碼如下:
<span style="font-size:18px;">package zuoye2.model; public class user { private int username; private String password; private String code; public int getUsername() { return username; } public void setUsername(int username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getCode() { return code; } public void setCode() { this.code = code; } }</span>
④:新建包名 xxxx.util,,,,,新建類 如DBO(用於連線資料庫)
程式碼如下:
⑤:新建包名 xxxx.service(用於寫操作介面與實現介面的方法),,,,新建介面,如userManager(注意此處建的是介面Interface不是class),右擊service包,點開新建,找到Interface,點選建立,命名userManager,程式碼如下:package zuoye2.util; import java.sql.Connection; import java.sql.DriverManager; import com.mysql.jdbc.PreparedStatement; import com.mysql.jdbc.ResultSet; import com.mysql.jdbc.Statement; public class DBO { protected final static String driver = "com.mysql.jdbc.Driver"; protected final static String url = "jdbc:mysql://localhost:3306/建立資料庫的名稱" ; static { try{ Class.forName(driver);//載入驅動程式 }catch(Exception e) { e.printStackTrace(); } } public static Connection getConnection () { Connection conn = null; try{ String password; conn = (Connection)DriverManager.getConnection(url, “資料庫使用者名稱”,“資料庫密碼”); }catch(Exception e) { e.printStackTrace(); } return conn; } public static void close (Statement st,ResultSet rs,Connection conn) { try { if(st!=null) { st.close(); } if(rs!=null) { rs.close(); } if(conn!=null) { conn.close(); } }catch(Exception e) { e.printStackTrace(); } } public static void close(PreparedStatement pst,Connection conn) { try{ if(pst!=null) { pst.close(); } if(conn!=null) { conn.close(); } }catch(Exception e) { e.printStackTrace(); } } }
package zuoye2.service;
import zuoye2.model.user;
public interface userManger {
public boolean add(user u);
public boolean addm(int username,String password);
}
⑥:在xxxx.service包中新建類,如userManagerImpl(此類用於實現userManager介面中定義的方法)。
程式碼如下:
package zuoye2.service;
import java.sql.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;
import com.sun.tools.xjc.reader.xmlschema.bindinfo.BIConversion.User;
import zuoye2.model.user;
import zuoye2.util.DBO;
public class userMangerImpl implements userManger{
public boolean add(user u){
boolean flag = false;
Connection conn = null;
PreparedStatement pst = null;
try{
conn = DBO.getConnection();
String sql = "insert into a (username,password,code) value(1,22,333)";
pst=(PreparedStatement )conn.prepareStatement(sql);
pst.setInt(1, u.getUsername());
pst.setString(2,u.getPassword());
pst.setString(3, u.getCode());
int row = pst.executeUpdate();
if(row>0)
{
flag = true;
}
}
catch(Exception e)
{
e.printStackTrace();
}finally{
DBO.close(pst,conn);
}
return false;
}
public boolean addm (int username,String password)
{
boolean flag = false;
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try{
conn = DBO.getConnection();
String sql = "select * from a where username="+username;
st = (Statement) conn.createStatement();
rs = (ResultSet) st.executeQuery(sql);
while(rs.next())
{
if(rs.getString("password").equals(password));
{
flag = true;
}
}
}catch(Exception e)
{
e.printStackTrace();
}finally{
DBO.close(st,rs,conn);
}
return false;
}
}
⑦:建立JSP頁面,右點選WebRoot,新建JSP(Advaanced Templates)(PS :軟體在新建工程時預設第一個JSP頁面是index.jsp,),注意:在JSP頁面中,標紅出,確定是utf-8,若不是一定修改過來。
登入頁面程式碼:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<from action="addm" method="post" align="center">
<center><h1>網頁登陸</h1></center>
<center><b>使用者名稱:</b><input type ="password" name="Username" style="width: 193px; "><br>
<p></p>
<b>密 碼:</b><input type="password" name="Password" style="width: 193px; "><br>
<br/>
<font size="+1">
<p>
<input name="submit" type="submit" class="button" style="width:200px; height:35px " value="登入" />
</p>
<p>
<font size="-1" color="#000099"><a href="zhuce.jsp">註冊</a> </font> </p>
</font>
</center>
</from>
</body>
</html>
註冊頁面程式碼:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'zhuce.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1 align="center">新使用者註冊</h1>
<hr/>
<from action="add method="post" ><center>
<b>使用者名稱:</b><input name="Username" type="text" style="width: 193px"><br/>
<p></p>
<b>密 碼:</b><input name="Password" type="password" style="width: 193px; "/><br/>
<p></p>
<b>驗證碼:</b><input name="Code" type="text" style="width:193px;"><br/>
<p></p>
<input type="submit" style="width:180px; height:35px "value="註冊" target="0"/> <br/>
</form>
<br/>
<a href="index.jsp">返回 </a>
</center>
</body>
</html>
⑧:在JSP頁面中,可在<body></body>中寫form表單
<form action="xxxx"method="post" >,可參考步驟⑦中程式碼,
附xxx是對應的後臺程式的servlet,名字要相同,否則表單資料無法提交到servlet中。
⑨:新建包xxx.servlet,,,,,新建與操作相對應的servlet如新增add,addm,
注意此處新建的檔名字是 servlet 不是class,servlet用於接收from表單中傳來的資料。
建立方法:右點選包xxx.servlet,新建目錄下,點選Servlet,可建立兩個,一個命名add,一個命名addm,
add程式碼:
package zuoye2.servlet;
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 zuoye2.model.user;
import zuoye2.service.userManger;
import zuoye2.service.userMangerImpl;
public class add extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
int username = Integer.parseInt(request.getParameter("Username"));
String pswd = request.getParameter("Password");
String code = request.getParameter("Code");
userManger um =new userMangerImpl();
user u = new user();
u.setUsername(username);
u.setPassword(pswd);
u.setCode();
boolean flag= false;
try {
flag = um.add(u);
if(flag==true){
response.sendRedirect("index.jsp");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
addm程式碼:
package zuoye2.servlet;
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 zuoye2.model.user;
import zuoye2.service.userMangerImpl;
public class addm extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
int un = Integer.parseInt(request.getParameter("Username"));
String pswd = request.getParameter("Password");
String checkcode = request.getParameter("Checkcode");
String pickcode = (String) request.getSession().getAttribute("piccode");
userMangerImpl um = new userMangerImpl();
user u = new user();
boolean flag= false;
try {
flag = um.addm(un, pswd);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
if(flag&&checkcode.equals(pickcode)){
response.sendRedirect("logchegngong.jsp");
}
}
}
⑩:到此所有程式碼結束,接下來是執行,右點選建立的WebService project,在此目錄下找到Run As--MyEclipse Server Application,會彈出這個出口選擇Tomcat7.x,點選OK,執行!
另外,資料庫連線程式碼,及測試類程式碼,部落格空間裡有,在這裡就不多陳述了
最後,給大家分享一點體會,做這個一定要有耐心,也要足夠的細心,我在寫的時候,好幾次匯入包的時候,都導錯了,造成很大麻煩,還好有人指導,