码迷,mamicode.com
首页 > 移动开发 > 详细

android-servlet-mysql实现登录注册功能

时间:2017-11-27 18:49:46      阅读:1019      评论:0      收藏:0      [点我收藏+]

标签:access   extends   roi   for   urlencode   doget   src   app   创建   

安卓项目图:

 

技术分享图片

 

安卓端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实现登录注册功能

标签:access   extends   roi   for   urlencode   doget   src   app   创建   

原文地址:http://www.cnblogs.com/mmmmm/p/7905344.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!