1. 程式人生 > >android-servlet-mysql實現登錄註冊功能

android-servlet-mysql實現登錄註冊功能

final 選擇 alt sta 姓名 delete byte[] dsta pstmt

安卓項目圖:

技術分享圖片

安卓端Get請求服務端登錄代碼:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;
import com.example.kkkkkkkkk.StreamTools;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
protected static final int ERROR = 1;
protected static final int SUCCESS = 2;
protected static final int SUCCESSS = 0;
BufferedReader bufferReader;
private EditText account;
private EditText password;
private Button register;
private Handler handler=new Handler(){
public void handleMessage(android.os.Message msg){
switch(msg.what){
case SUCCESS:
Toast.makeText(MainActivity.this,(String)msg.obj, 1).show();
break;
case ERROR:
Toast.makeText(MainActivity.this,"發送失敗", 1).show();
break;
}
};
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
account = (EditText)findViewById(R.id.account);
password=(EditText)findViewById(R.id.password);
register = (Button)findViewById(R.id.login);
}
public void register(View view){
Intent intent=new Intent(this, RegisterActivity.class);
startActivity(intent);
}
public void login(View view){
final String qq=account.getText().toString().trim();
final String pwd=password.getText().toString().trim();
if(TextUtils.isEmpty(qq)){
Toast.makeText(this,"用戶名為空登錄失敗", 0).show();
return;
}
if(TextUtils.isEmpty(pwd)){
Toast.makeText(this,"密碼為空登陸失敗", 0).show();
return;
}
new Thread(){
Map<String, Object> listItem = new HashMap<String, Object>();
List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
public void run(){
try{
String path="http://192.168.1.4:8080/xianfengYan/LoginAction?username="+qq+"&pswd="+pwd;
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; KB974487)");
int code=conn.getResponseCode();
if(code==200){
InputStream is=conn.getInputStream();
String result=StreamTools.readInputStream(is);
if(!result.equals("用戶名不存在請重新輸入,登陸失敗")&&!result.equals("密碼錯誤,登陸失敗")){
JSONObject demoJson = new JSONObject(result);
Intent intent=new Intent(MainActivity.this,Activity01.class);
intent.putExtra("用戶名",demoJson.getString("用戶名"));
System.out.println(demoJson.getString("用戶名"));
intent.putExtra("密碼",demoJson.getString("密碼"));
System.out.println(demoJson.getString("密碼"));
intent.putExtra("真實姓名",demoJson.getString("真實姓名"));
System.out.println(demoJson.getString("真實姓名"));
intent.putExtra("性別",demoJson.getString("性別"));
System.out.println(demoJson.getString("性別"));
//bundle.putSerializable("hh", (Serializable) msg.obj);
//intent.putExtras(bundle);
startActivity(intent);
}else{
Message msg=Message.obtain();
msg.what=SUCCESS;
msg.obj=result;
handler.sendMessage(msg);
}
}else{
Message msg=Message.obtain();
msg.what=ERROR;
handler.sendMessage(msg);
}
}catch(Exception e){
e.printStackTrace();
Message msg=Message.obtain();
msg.what=ERROR;
handler.sendMessage(msg);
}
};
}.start();

}
}

安卓端Get請求註冊代碼:

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
import com.example.kkkkkkkkk.MainActivity;
import com.example.kkkkkkkkk.StreamTools;
public class RegisterActivity extends Activity implements OnCheckedChangeListener{
protected static final int ERROR = 1;
protected static final int SUCCESS = 2;
private EditText et_pwd;
private EditText et_qq;
private EditText et_name;
private EditText et_apwd;
private RadioButton radio0;
private RadioButton radio1;
private Button Button1;
private RadioGroup rg;
String temp="";
private Handler handler=new Handler(){
public void handleMessage(android.os.Message msg){
switch(msg.what){
case SUCCESS:
Toast.makeText(RegisterActivity.this,(String)msg.obj, 1).show();
if(msg.obj.equals("註冊成功")){
//System.out.println("1111"+msg.obj);
Intent intent=new Intent(RegisterActivity.this,MainActivity.class);
startActivity(intent);
}
break;
case ERROR:
Toast.makeText(RegisterActivity.this,"登錄失敗", 1).show();
break;
}
};
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
et_qq = (EditText)findViewById(R.id.et_qq);
et_pwd=(EditText)findViewById(R.id.et_pwd);
et_name=(EditText)findViewById(R.id.et_name);
et_apwd=(EditText)findViewById(R.id.et_apwd);
rg=(RadioGroup) findViewById(R.id.radioGroup1) ;
rg.setOnCheckedChangeListener(this);
Button1=(Button)findViewById(R.id.button1);

}
public void Button1(View view){
Intent intent=new Intent(this, MainActivity.class);
startActivity(intent);
}
public void onCheckedChanged(RadioGroup group,int checkedId){
switch(checkedId){
case R.id.radio0:
temp="男";
break;
case R.id.radio1:
temp="女";
break;
}

}

public void regin(View view) throws UnsupportedEncodingException{

final String qq=et_qq.getText().toString().trim();
final String pwd=et_pwd.getText().toString().trim();
final String name=et_name.getText().toString().trim();
final String apwd=et_apwd.getText().toString().trim();
final String tem =URLEncoder.encode(URLEncoder.encode(temp, "UTF-8"), "UTF-8");
if(TextUtils.isEmpty(qq)){
Toast.makeText(this,"用戶名不能為空", 0).show();
return;
}
if(TextUtils.isEmpty(pwd)){
Toast.makeText(this,"密碼不能為空", 0).show();
return;
}
if(TextUtils.equals(pwd, apwd)==false){
Toast.makeText(this,"兩次輸入密碼不同", 0).show();
return;
}
if(pwd.length()<6){
Toast.makeText(this,"密碼位數小於6安全等級太低", 0).show();
return;
}
if(temp==""){
Toast.makeText(this,"請選擇性別", 0).show();
return;
}
new Thread(){
public void run(){
try{
String path="http://192.168.1.4:8080/xianfengYan/RegisterAction?username="+qq+"&realname="+name+"&pswd="+pwd+"&sex="+tem;
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; KB974487)");
int code=conn.getResponseCode();
if(code==200){
InputStream is=conn.getInputStream();
String result=StreamTools.readInputStream(is);
Message msg=Message.obtain();
msg.what=SUCCESS;
msg.obj=result;
handler.sendMessage(msg);
}else{
Message msg=Message.obtain();
msg.what=ERROR;
handler.sendMessage(msg);
}
}catch(Exception e){
e.printStackTrace();
Message msg=Message.obtain();
msg.what=ERROR;
handler.sendMessage(msg);
}
};
}.start();
}
}

輸入流工具類:

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamTools {
// 把輸入流的內容 轉化成 字符串
public static String readInputStream(InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
is.close();
baos.close();
byte[] result = baos.toByteArray();
// 試著解析 result 裏面的字符串.
String temp = new String(result);
return temp;
} catch (Exception e) {
e.printStackTrace();
return "獲取失敗";
}
}
}

服務端代碼:

JdbcUtils.java 數據庫連接類

package com.product.jdbc.dbutil;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JdbcUtils {

// 表示定義數據庫的用戶名
private final String USERNAME = "root";
// 定義數據庫的密碼
private final String PASSWORD = "123";
// 定義數據庫的驅動信息
private final String DRIVER = "com.mysql.jdbc.Driver";
// 定義訪問數據庫的地址
private final String URL = "jdbc:mysql://localhost:3306/jdbc_db";
// 定義數據庫的鏈接
private Connection connection;
// 定義sql語句的執行對象
private PreparedStatement pstmt;
// 定義查詢返回的結果集合
private ResultSet resultSet;
// 實現批處理操作的功能
private Statement stmt;

public JdbcUtils() {
try {
Class.forName(DRIVER);
System.out.println("註冊驅動成功!!");
} catch (Exception e) {
// TODO: handle exception
}
}

// 定義獲得數據庫的鏈接
public Connection getConnection() {
try {
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (Exception e) {
// TODO: handle exception
}
return connection;
}

public boolean deleteByBatch(String[] sql) throws SQLException{
boolean flag = false;
stmt = connection.createStatement();
if(sql!=null){
for(int i=0;i<sql.length;i++){
stmt.addBatch(sql[i]);
}
}
int[] count = stmt.executeBatch();
if(count!=null){
flag = true;
}
return flag;
}
/**
* 完成對數據庫的表的添加刪除和修改的操作
*
* @param sql
* @param params
* @return
* @throws SQLException
*/
public boolean updateByPreparedStatement(String sql, List<Object> params)
throws SQLException {
boolean flag = false;
int result = -1;// 表示當用戶執行添加刪除和修改的時候所影響數據庫的行數
pstmt = connection.prepareStatement(sql);
int index = 1;
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
result = pstmt.executeUpdate();
flag = result > 0 ? true : false;
return flag;
}

/**
* 查詢返回單條記錄
*
* @param sql
* @param params
* @return
* @throws SQLException
*/
public Map<String, Object> findSimpleResult(String sql, List<Object> params)
throws SQLException {
Map<String, Object> map = new HashMap<String, Object>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();// 返回查詢結果
ResultSetMetaData metaData = resultSet.getMetaData();
int col_len = metaData.getColumnCount();// 獲得列的名稱
while (resultSet.next()) {
for (int i = 0; i < col_len; i++) {
String cols_name = metaData.getColumnName(i + 1);
Object cols_value = resultSet.getObject(cols_name);
if (cols_value == null) {
cols_value = "";
}
map.put(cols_name, cols_value);
}
}
return map;
}

/**
* 查詢返回多行記錄
*
* @param sql
* @param params
* @return
* @throws SQLException
*/
public List<Map<String, Object>> findMoreResult(String sql,
List<Object> params) throws SQLException {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int cols_len = metaData.getColumnCount();
while (resultSet.next()) {
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < cols_len; i++) {
String cols_name = metaData.getColumnName(i + 1);
Object cols_value = resultSet.getObject(cols_name);
if (cols_value == null) {
cols_value = "";
}
map.put(cols_name, cols_value);
}
list.add(map);
}
return list;
}

// jdbc的封裝可以用反射機制來封裝:
public <T> T findSimpleRefResult(String sql, List<Object> params,
Class<T> cls) throws Exception {
T resultObject = null;
int index = 1;
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int cols_len = metaData.getColumnCount();
while (resultSet.next()) {
// 通過反射機制創建實例
resultObject = cls.newInstance();
for (int i = 0; i < cols_len; i++) {
String cols_name = metaData.getColumnName(i + 1);
Object cols_value = resultSet.getObject(cols_name);
if (cols_value == null) {
cols_value = "";
}
Field field = cls.getDeclaredField(cols_name);
field.setAccessible(true);// 打開javabean的訪問private權限
field.set(resultObject, cols_value);
}
}
return resultObject;
}

/**
* 通過反射機制訪問數據庫
*
* @param <T>
* @param sql
* @param params
* @param cls
* @return
* @throws Exception
*/
public <T> List<T> findMoreRefResult(String sql, List<Object> params,
Class<T> cls) throws Exception {
List<T> list = new ArrayList<T>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int cols_len = metaData.getColumnCount();
while (resultSet.next()) {
T resultObject = cls.newInstance();
for (int i = 0; i < cols_len; i++) {
String cols_name = metaData.getColumnName(i + 1);
Object cols_value = resultSet.getObject(cols_name);
if (cols_value == null) {
cols_value = "";
}
Field field = cls.getDeclaredField(cols_name);
field.setAccessible(true);
field.set(resultObject, cols_value);
}
list.add(resultObject);
}
return list;
}

public void releaseConn() {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

技術分享圖片

登錄的servlet:

LoginAction.java

package com.product.login.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.product.login.dao.LoginDao;
import com.product.login.service.LoginService;

public class LoginAction extends HttpServlet {
private static final long serialVersionUID = 1L;
private LoginService service;

/**
* Constructor of the object.
*/
public LoginAction() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);

}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String path = request.getContextPath();
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String pswd = request.getParameter("pswd");
System.out.println("username = " + username + " pswd = " + pswd);
List<Object> params = new ArrayList<Object>();
params.add(username);
params.add(pswd);

boolean flag = service.LoginUser(params);

boolean fla = service.LoginCat(params);
boolean fl = service.LoginDog(params);
List<String> list = service.user(params);

JSONObject jsonobj = new JSONObject();
if (list.size() != 0) {
jsonobj.put("用戶名", list.get(0));
jsonobj.put("密碼", list.get(1));
jsonobj.put("真實姓名", list.get(2));
jsonobj.put("性別", list.get(3));
}
if (flag == true) {
out.println(jsonobj);
// response.sendRedirect(path + "/index.jsp");
}
if (fla == true) {
out.print("用戶名不存在請重新輸入,登陸失敗");
}
if (fl == true) {
out.print("密碼錯誤,登陸失敗");
}

out.flush();
out.close();
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
service = new LoginDao();
}

}

LoginDao.java

數據庫的操作類

package com.product.login.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.product.jdbc.dbutil.JdbcUtils;
import com.product.login.service.LoginService;

public class LoginDao implements LoginService {
private JdbcUtils jdbcUtils = null;

public LoginDao() {
// TODO Auto-generated constructor stub
jdbcUtils = new JdbcUtils();
}

/*
* 完成用戶對註冊的Dao的編寫
*
* @see
* com.product.register.service.RegisterService#registerUser(java.util.List)
*/
public boolean LoginUser(List<Object> params) {
// TODO Auto-generated method stub
boolean flag = false;
jdbcUtils.getConnection();
String sql1 = "select * from userinfo where username=? and pswd=?";
try {
Map<String, Object> map = jdbcUtils.findSimpleResult(sql1, params);
flag = !map.isEmpty() ? true : false;
} catch (Exception e1) {
e1.printStackTrace();
} finally {
jdbcUtils.releaseConn();
}
return flag;
}

@SuppressWarnings("null")
public boolean LoginCat(List<Object> params) {
boolean fla = false;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
ResultSet rs1 = null;
conn = jdbcUtils.getConnection();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from userinfo where username=‘"
+ params.get(0) + "‘");
if (rs.next() == false) {
fla = true;
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
jdbcUtils.releaseConn();
}
return fla;
}

public boolean LoginDog(List<Object> params) {
boolean fl = false;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
ResultSet rs1 = null;
conn = jdbcUtils.getConnection();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from userinfo where username=‘"
+ params.get(0) + "‘");
if (rs.next() == true) {
rs1 = stmt.executeQuery("select * from userinfo where pswd=‘"
+ params.get(1) + "‘");
if (rs1.next() == false) {
fl = true;
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
jdbcUtils.releaseConn();
}
return fl;
}

// public List<User> user(List<Object> params) {
// Connection conn = null;
// Statement stmt = null;
// ResultSet rs = null;
// List<User> userList = new ArrayList<>();
// conn = jdbcUtils.getConnection();
//
// try {
// stmt = conn.createStatement();
// rs = stmt.executeQuery("select * from userinfo where username=‘"
// + params.get(0) + "‘");
// while (rs.next()) {
// String username = rs.getString("username");
// String password = rs.getString("password");
// String realname = rs.getString("realname");
// String sex = rs.getString("sex");
// User user = new User(username, password, realname, sex);
// userList.add(user);
// }
// } catch (Exception e1) {
// e1.printStackTrace();
// } finally {
// jdbcUtils.releaseConn();
// }
// return userList;
//
// }
public List<String> user(List<Object> params) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
conn = jdbcUtils.getConnection();
List<String> list = new ArrayList<String>();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from userinfo where username=‘"
+ params.get(0) + "‘");
System.out.println(params.get(0));
while (rs.next()) {
String username = rs.getString("username");
System.out.println(username);
String password = rs.getString("pswd");
System.out.println(password);
String realname = rs.getString("realname");
System.out.println(realname);
String sex = rs.getString("sex");
System.out.println(sex);
// User user = new User(username, password, realname, sex);
list.add(username);
list.add(password);
list.add(realname);
list.add(sex);
System.out.println(list);

}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
jdbcUtils.releaseConn();
}
return list;
}
}

LoginService.java

service接口類

package com.product.login.service;

import java.util.List;

public interface LoginService {
public boolean LoginUser(List<Object> params);

public boolean LoginCat(List<Object> params);

public boolean LoginDog(List<Object> params);

public List<String> user(List<Object> params);

}

註冊代碼

RegisterAction.java

package com.product.register.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.product.register.dao.RegisterDao;
import com.product.register.service.RegisterService;

public class RegisterAction extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;
private RegisterService service;

/**
* Constructor of the object.
*/
public RegisterAction() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

this.doPost(request, response);
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = request.getContextPath();
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String realname = request.getParameter("realname");
String pswd = request.getParameter("pswd");
// String sex = new
// String(request.getParameter("sex").getBytes("iso-8859-1"), "utf-8");
// String sex = request.getParameter("sex");
// String sex=java.net.URLDecoder.decode(request.getParameter("sex"),
// "UTF-8");
String sex = URLDecoder.decode(
URLDecoder.decode(request.getParameter("sex"), "UTF-8"),
"UTF-8");

System.out.println("username = " + username + " realname = "
+ realname + " pswd = " + pswd + " sex = " + sex);
List<Object> params = new ArrayList<Object>();
params.add(username);
params.add(pswd);
params.add(realname);
params.add(sex);
// params.add(b1);
// params.add(b2);
boolean flag = service.registerUser(params);
if (flag) {
// response.getOutputStream().write("register success".getBytes());
out.print("註冊成功");
// response.sendRedirect(path + "/index.jsp");
} else {
out.print("用戶名重復,註冊失敗");
}
out.flush();
out.close();
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
service = new RegisterDao();
}

}

RegisterDao.java

註冊功能的數據庫操作類:

package com.product.register.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;

import com.mysql.jdbc.PreparedStatement;
import com.product.jdbc.dbutil.JdbcUtils;
import com.product.register.service.RegisterService;

public class RegisterDao implements RegisterService {
private JdbcUtils jdbcUtils = null;

public RegisterDao() {
// TODO Auto-generated constructor stub
jdbcUtils = new JdbcUtils();
}

/* 完成用戶對註冊的Dao的編寫
* @see com.product.register.service.RegisterService#registerUser(java.util.List)
*/
@Override
public boolean registerUser(List<Object> params) {
// TODO Auto-generated method stub
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
boolean flag = false;

conn=jdbcUtils.getConnection();
try {
stmt=conn.createStatement();
rs = stmt.executeQuery("select * from userinfo where username=‘"+params.get(0)+"‘");
//System.out.println(params.get(0));
if(rs.next()==true){
flag=false;
}else{
flag = jdbcUtils.updateByPreparedStatement("insert into userinfo(username, pswd, realname,sex) values (?, ?, ?,?)", params);
}
} catch (Exception e1) {
e1.printStackTrace();
}
finally{
jdbcUtils.releaseConn();
}
return flag;
}
}

RegisterService.java

註冊服務接口類:

package com.product.register.service;

import java.util.List;


public interface RegisterService {
public boolean registerUser(List<Object> params);
}

實驗結果截圖:

技術分享圖片 技術分享圖片 技術分享圖片

轉載請註明出處:https://home.cnblogs.com/u/mmmmm/

有啥不懂私信我哦!

android-servlet-mysql實現登錄註冊功能