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

安卓项目图:

 

安卓端Get请求服务端登录代码:

  1 package com.example.kkkkkkkkk;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.InputStream;
  5 import java.io.Serializable;
  6 import java.net.HttpURLConnection;
  7 import java.net.URL;
  8 import java.util.ArrayList;
  9 import java.util.HashMap;
 10 import java.util.List;
 11 import java.util.Map;
 12 import org.json.JSONObject;
 13 import com.example.kkkkkkkkk.StreamTools;
 14 import android.support.v7.app.ActionBarActivity;
 15 import android.text.TextUtils;
 16 import android.app.Activity;
 17 import android.content.Intent;
 18 import android.os.Bundle;
 19 import android.os.Handler;
 20 import android.os.Message;
 21 import android.view.Menu;
 22 import android.view.MenuItem;
 23 import android.view.View;
 24 import android.view.View.OnClickListener;
 25 import android.widget.Button;
 26 import android.widget.EditText;
 27 import android.widget.Toast;
 28 
 29 public class MainActivity extends Activity {
 30     protected static final int ERROR = 1;
 31     protected static final int SUCCESS = 2;
 32     protected static final int SUCCESSS = 0;
 33     BufferedReader bufferReader; 
 34     private EditText account;
 35     private EditText password;
 36     private Button   register;
 37     private Handler handler=new Handler(){
 38         public void handleMessage(android.os.Message msg){
 39             switch(msg.what){
 40             case SUCCESS:
 41                 Toast.makeText(MainActivity.this,(String)msg.obj, 1).show();                        
 42                 break;                
 43             case ERROR:
 44                 Toast.makeText(MainActivity.this,"发送失败", 1).show();
 45                 break;
 46             }    
 47     };        
 48 };
 49 protected void onCreate(Bundle savedInstanceState) {
 50     super.onCreate(savedInstanceState);
 51     setContentView(R.layout.activity_main);
 52     account = (EditText)findViewById(R.id.account);
 53     password=(EditText)findViewById(R.id.password);
 54     register = (Button)findViewById(R.id.login);        
 55 }
 56 public void register(View view){
 57     Intent intent=new Intent(this, RegisterActivity.class);
 58     startActivity(intent);    
 59 }
 60 public void login(View view){
 61     final String qq=account.getText().toString().trim();
 62     final String pwd=password.getText().toString().trim();
 63     if(TextUtils.isEmpty(qq)){
 64         Toast.makeText(this,"用户名为空登录失败", 0).show();    
 65         return;    
 66     }
 67     if(TextUtils.isEmpty(pwd)){
 68         Toast.makeText(this,"密码为空登陆失败", 0).show();    
 69         return;    
 70     }    
 71     new Thread(){
 72         Map listItem = new HashMap();
 73           List> listItems = new ArrayList>();
 74         public void run(){
 75             try{
 76                 String path="http://192.168.1.4:8080/xianfengYan/LoginAction?username="+qq+"&pswd="+pwd;
 77                 URL url=new URL(path);
 78                 HttpURLConnection conn=(HttpURLConnection) url.openConnection();
 79                 conn.setRequestMethod("GET");
 80                 conn.setRequestProperty("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; KB974487)");
 81                 int code=conn.getResponseCode();
 82                 if(code==200){
 83                     InputStream is=conn.getInputStream();
 84                     String result=StreamTools.readInputStream(is);        
 85                     if(!result.equals("用户名不存在请重新输入,登陆失败")&&!result.equals("密码错误,登陆失败")){
 86                         JSONObject demoJson = new JSONObject(result);                        
 87                         Intent intent=new Intent(MainActivity.this,Activity01.class);                    
 88                         intent.putExtra("用户名",demoJson.getString("用户名"));
 89                         System.out.println(demoJson.getString("用户名"));
 90                         intent.putExtra("密码",demoJson.getString("密码"));
 91                         System.out.println(demoJson.getString("密码"));
 92                         intent.putExtra("真实姓名",demoJson.getString("真实姓名"));
 93                         System.out.println(demoJson.getString("真实姓名"));
 94                         intent.putExtra("性别",demoJson.getString("性别"));
 95                         System.out.println(demoJson.getString("性别"));
 96                         //bundle.putSerializable("hh", (Serializable) msg.obj);                
 97                         //intent.putExtras(bundle);
 98                         
 99                         
100                         startActivity(intent);
101                     }else{                    
102                          Message msg=Message.obtain();
103                          msg.what=SUCCESS;
104                          msg.obj=result;
105                          handler.sendMessage(msg);
106                     }
107                }else{
108                     Message msg=Message.obtain();
109                     msg.what=ERROR;
110                     handler.sendMessage(msg);
111                }    
112         }catch(Exception e){
113             e.printStackTrace();
114             Message msg=Message.obtain();
115             msg.what=ERROR;
116             handler.sendMessage(msg);
117         }
118    };        
119    }.start();
120 
121    }
122 }
MainActivity.java

安卓端Get请求注册代码:

  1 package com.example.kkkkkkkkk;
  2 
  3 import java.io.InputStream;
  4 import java.io.UnsupportedEncodingException;
  5 import java.net.HttpURLConnection;
  6 import java.net.URL;
  7 import java.net.URLEncoder;
  8 import android.app.Activity;
  9 import android.content.Intent;
 10 import android.os.Bundle;
 11 import android.os.Handler;
 12 import android.os.Message;
 13 import android.text.TextUtils;
 14 import android.view.View;
 15 import android.widget.Button;
 16 import android.widget.EditText;
 17 import android.widget.RadioButton;
 18 import android.widget.RadioGroup;
 19 import android.widget.Toast;
 20 import android.widget.RadioGroup.OnCheckedChangeListener;
 21 import com.example.kkkkkkkkk.MainActivity;
 22 import com.example.kkkkkkkkk.StreamTools;
 23 public class RegisterActivity extends Activity implements OnCheckedChangeListener{    
 24     protected static final int ERROR = 1;
 25     protected static final int SUCCESS = 2;
 26     private EditText et_pwd;
 27     private EditText et_qq;
 28     private EditText et_name;
 29     private EditText et_apwd;
 30     private RadioButton radio0;
 31     private RadioButton radio1;
 32     private Button Button1;
 33     private RadioGroup rg;
 34     String temp="";
 35     private Handler handler=new Handler(){    
 36         public void handleMessage(android.os.Message msg){
 37             switch(msg.what){
 38             case SUCCESS:
 39                 Toast.makeText(RegisterActivity.this,(String)msg.obj, 1).show();
 40                 if(msg.obj.equals("注册成功")){
 41                 //System.out.println("1111"+msg.obj);
 42                 Intent intent=new Intent(RegisterActivity.this,MainActivity.class);
 43                 startActivity(intent);
 44                 }
 45                 break;
 46             case ERROR:
 47                 Toast.makeText(RegisterActivity.this,"登录失败", 1).show();
 48                 break;
 49             }
 50         };        
 51     };
 52     protected void onCreate(Bundle savedInstanceState) {
 53         super.onCreate(savedInstanceState);
 54         setContentView(R.layout.activity_register);
 55         et_qq = (EditText)findViewById(R.id.et_qq);
 56         et_pwd=(EditText)findViewById(R.id.et_pwd);
 57         et_name=(EditText)findViewById(R.id.et_name);
 58         et_apwd=(EditText)findViewById(R.id.et_apwd);
 59         rg=(RadioGroup) findViewById(R.id.radioGroup1) ;
 60         rg.setOnCheckedChangeListener(this);
 61         Button1=(Button)findViewById(R.id.button1);
 62              
 63     }
 64     public void Button1(View view){
 65         Intent intent=new Intent(this, MainActivity.class);
 66         startActivity(intent);    
 67     }
 68      public void onCheckedChanged(RadioGroup group,int checkedId){
 69          switch(checkedId){
 70          case R.id.radio0:
 71              temp="男"; 
 72             break;
 73         case R.id.radio1:
 74              temp="女";
 75              break;
 76         }
 77         
 78     }
 79         
 80         public void regin(View view) throws UnsupportedEncodingException{
 81             
 82             final String qq=et_qq.getText().toString().trim();
 83             final String pwd=et_pwd.getText().toString().trim();
 84             final String name=et_name.getText().toString().trim();
 85             final String apwd=et_apwd.getText().toString().trim();
 86             final String tem =URLEncoder.encode(URLEncoder.encode(temp, "UTF-8"), "UTF-8");            
 87             if(TextUtils.isEmpty(qq)){
 88                 Toast.makeText(this,"用户名不能为空", 0).show();
 89                 return;                    
 90             }
 91             if(TextUtils.isEmpty(pwd)){
 92                 Toast.makeText(this,"密码不能为空", 0).show();
 93                 return;                    
 94             }            
 95             if(TextUtils.equals(pwd, apwd)==false){
 96                 Toast.makeText(this,"两次输入密码不同", 0).show();
 97                 return;
 98             }
 99             if(pwd.length()<6){
100                 Toast.makeText(this,"密码位数小于6安全等级太低", 0).show();
101                 return;        
102             }
103             if(temp==""){
104                 Toast.makeText(this,"请选择性别", 0).show();
105                 return;
106                 }
107         new Thread(){
108             public void run(){
109                 try{
110                     String path="http://192.168.1.4:8080/xianfengYan/RegisterAction?username="+qq+"&realname="+name+"&pswd="+pwd+"&sex="+tem;
111                     URL url=new URL(path);
112                     HttpURLConnection conn=(HttpURLConnection) url.openConnection();
113                     conn.setRequestMethod("GET");
114                     conn.setRequestProperty("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; KB974487)");
115                     int code=conn.getResponseCode();
116                     if(code==200){
117                         InputStream is=conn.getInputStream();
118                         String result=StreamTools.readInputStream(is);
119                         Message msg=Message.obtain();
120                         msg.what=SUCCESS;
121                         msg.obj=result;
122                         handler.sendMessage(msg);
123                    }else{
124                         Message msg=Message.obtain();
125                         msg.what=ERROR;
126                         handler.sendMessage(msg);
127                    }    
128             }catch(Exception e){
129                 e.printStackTrace();
130                 Message msg=Message.obtain();
131                 msg.what=ERROR;
132                 handler.sendMessage(msg);
133             }
134     };        
135     }.start();
136    }
137 }
RegisterActivity.java

输入流工具类:

 1 package com.example.kkkkkkkkk;
 2 
 3 import java.io.ByteArrayOutputStream;
 4 import java.io.InputStream;
 5 
 6 public class StreamTools {
 7     // 把输入流的内容 转化成 字符串
 8     public static String readInputStream(InputStream is) {
 9         try {
10             ByteArrayOutputStream baos = new ByteArrayOutputStream();
11             int len = 0;
12             byte[] buffer = new byte[1024];
13             while ((len = is.read(buffer)) != -1) {
14                 baos.write(buffer, 0, len);
15             }
16             is.close();
17             baos.close();
18             byte[] result = baos.toByteArray();
19             // 试着解析 result 里面的字符串.
20             String temp = new String(result);
21             return temp;
22         } catch (Exception e) {
23             e.printStackTrace();
24             return "获取失败";
25         }
26     }
27 }
StreamTools.java

安卓端登录成功返回界面:返回用户的注册信息

 1 package com.example.kkkkkkkkk;
 2 
 3 import java.io.Serializable;
 4 
 5 import org.json.JSONObject;
 6 
 7 import android.app.Activity;
 8 import android.content.Intent;
 9 import android.os.Bundle;
10 import android.widget.EditText;
11 import android.widget.TextView;
12 
13 public class Activity01 extends Activity{
14 
15         private TextView tv_username; 
16         private TextView tv_realname;  
17         private TextView tv_password;  
18         private TextView tv_sex;  
19         @Override  
20         protected void onCreate(Bundle savedInstanceState) {  
21             // TODO Auto-generated method stub  
22             super.onCreate(savedInstanceState);  
23             setContentView(R.layout.activity_01);  
24             //提取数据  
25             Intent intent=getIntent(); 
26            // Bundle bundle = intent.getExtras();
27             //Serializable name=bundle.getSerializable("hh");
28       String name1=intent.getStringExtra("用户名");
29       String name2=intent.getStringExtra("密码");
30       String name3=intent.getStringExtra("真实姓名");
31       String name4=intent.getStringExtra("性别");
32         //JSONObject json = JSONObject.fromObject(name);
33      
34             tv_username=(TextView) findViewById(R.id.tv_username);
35             tv_realname=(TextView) findViewById(R.id.tv_realname);
36             tv_password=(TextView) findViewById(R.id.tv_password);
37             tv_sex=(TextView) findViewById(R.id.tv_sex);
38             tv_username.setText("用户名:"+name1);
39             tv_realname.setText("密码:"+name2);
40             tv_password.setText("真实姓名:"+name3);
41             tv_sex.setText("性别:"+name4);
42             //过滤的方法,在LogCat(deprecated)的Filter中输入--进行过滤,这不是标准的调试方法  
43             //System.out.println("--name->>"+name);              
44         }        
45     }  
Activity01.java

服务端项目图:

    

 

数据库连接类:

  1 package com.product.jdbc.dbutil;
  2 
  3 import java.lang.reflect.Field;
  4 import java.sql.Connection;
  5 import java.sql.DriverManager;
  6 import java.sql.PreparedStatement;
  7 import java.sql.ResultSet;
  8 import java.sql.ResultSetMetaData;
  9 import java.sql.SQLException;
 10 import java.sql.Statement;
 11 import java.util.ArrayList;
 12 import java.util.HashMap;
 13 import java.util.List;
 14 import java.util.Map;
 15 
 16 public class JdbcUtils {
 17 
 18     // 表示定义数据库的用户名
 19     private final String USERNAME = "root";
 20     // 定义数据库的密码
 21     private final String PASSWORD = "123";
 22     // 定义数据库的驱动信息
 23     private final String DRIVER = "com.mysql.jdbc.Driver";
 24     // 定义访问数据库的地址
 25     private final String URL = "jdbc:mysql://localhost:3306/jdbc_db";
 26     // 定义数据库的链接
 27     private Connection connection;
 28     // 定义sql语句的执行对象
 29     private PreparedStatement pstmt;
 30     // 定义查询返回的结果集合
 31     private ResultSet resultSet;
 32     // 实现批处理操作的功能
 33     private Statement stmt;
 34 
 35     public JdbcUtils() {
 36         try {
 37             Class.forName(DRIVER);
 38             System.out.println("注册驱动成功!!");
 39         } catch (Exception e) {
 40             // TODO: handle exception
 41         }
 42     }
 43 
 44     // 定义获得数据库的链接
 45     public Connection getConnection() {
 46         try {
 47             connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
 48         } catch (Exception e) {
 49             // TODO: handle exception
 50         }
 51         return connection;
 52     }
 53 
 54     public boolean deleteByBatch(String[] sql) throws SQLException{
 55         boolean flag = false;
 56         stmt = connection.createStatement();
 57         if(sql!=null){
 58             for(int i=0;i){
 59                 stmt.addBatch(sql[i]);
 60             }
 61         }
 62         int[] count = stmt.executeBatch();
 63         if(count!=null){
 64             flag = true;
 65         }
 66         return flag;
 67     }
 68     /**
 69      * 完成对数据库的表的添加删除和修改的操作
 70      * 
 71      * @param sql
 72      * @param params
 73      * @return
 74      * @throws SQLException
 75      */
 76     public boolean updateByPreparedStatement(String sql, List params)
 77             throws SQLException {
 78         boolean flag = false;
 79         int result = -1;// 表示当用户执行添加删除和修改的时候所影响数据库的行数
 80         pstmt = connection.prepareStatement(sql);
 81         int index = 1;
 82         if (params != null && !params.isEmpty()) {
 83             for (int i = 0; i < params.size(); i++) {
 84                 pstmt.setObject(index++, params.get(i));
 85             }
 86         }
 87         result = pstmt.executeUpdate();
 88         flag = result > 0 ? true : false;
 89         return flag;
 90     }
 91 
 92     /**
 93      * 查询返回单条记录
 94      * 
 95      * @param sql
 96      * @param params
 97      * @return
 98      * @throws SQLException
 99      */
100     public Map findSimpleResult(String sql, List params)
101             throws SQLException {
102         Map map = new HashMap();
103         int index = 1;
104         pstmt = connection.prepareStatement(sql);
105         if (params != null && !params.isEmpty()) {
106             for (int i = 0; i < params.size(); i++) {
107                 pstmt.setObject(index++, params.get(i));
108             }
109         }
110         resultSet = pstmt.executeQuery();// 返回查询结果
111         ResultSetMetaData metaData = resultSet.getMetaData();
112         int col_len = metaData.getColumnCount();// 获得列的名称
113         while (resultSet.next()) {
114             for (int i = 0; i < col_len; i++) {
115                 String cols_name = metaData.getColumnName(i + 1);
116                 Object cols_value = resultSet.getObject(cols_name);
117                 if (cols_value == null) {
118                     cols_value = "";
119                 }
120                 map.put(cols_name, cols_value);
121             }
122         }
123         return map;
124     }
125 
126     /**
127      * 查询返回多行记录
128      * 
129      * @param sql
130      * @param params
131      * @return
132      * @throws SQLException
133      */
134     public List> findMoreResult(String sql,
135             List params) throws SQLException {
136         List> list = new ArrayList>();
137         int index = 1;
138         pstmt = connection.prepareStatement(sql);
139         if (params != null && !params.isEmpty()) {
140             for (int i = 0; i < params.size(); i++) {
141                 pstmt.setObject(index++, params.get(i));
142             }
143         }
144         resultSet = pstmt.executeQuery();
145         ResultSetMetaData metaData = resultSet.getMetaData();
146         int cols_len = metaData.getColumnCount();
147         while (resultSet.next()) {
148             Map map = new HashMap();
149             for (int i = 0; i < cols_len; i++) {
150                 String cols_name = metaData.getColumnName(i + 1);
151                 Object cols_value = resultSet.getObject(cols_name);
152                 if (cols_value == null) {
153                     cols_value = "";
154                 }
155                 map.put(cols_name, cols_value);
156             }
157             list.add(map);
158         }
159         return list;
160     }
161 
162     // jdbc的封装可以用反射机制来封装:
163     public  T findSimpleRefResult(String sql, List params,
164             Class cls) throws Exception {
165         T resultObject = null;
166         int index = 1;
167         pstmt = connection.prepareStatement(sql);
168         if (params != null && !params.isEmpty()) {
169             for (int i = 0; i < params.size(); i++) {
170                 pstmt.setObject(index++, params.get(i));
171             }
172         }
173         resultSet = pstmt.executeQuery();
174         ResultSetMetaData metaData = resultSet.getMetaData();
175         int cols_len = metaData.getColumnCount();
176         while (resultSet.next()) {
177             // 通过反射机制创建实例
178             resultObject = cls.newInstance();
179             for (int i = 0; i < cols_len; i++) {
180                 String cols_name = metaData.getColumnName(i + 1);
181                 Object cols_value = resultSet.getObject(cols_name);
182                 if (cols_value == null) {
183                     cols_value = "";
184                 }
185                 Field field = cls.getDeclaredField(cols_name);
186                 field.setAccessible(true);// 打开javabean的访问private权限
187                 field.set(resultObject, cols_value);
188             }
189         }
190         return resultObject;
191     }
192 
193     /**
194      * 通过反射机制访问数据库
195      * 
196      * @param 
197      * @param sql
198      * @param params
199      * @param cls
200      * @return
201      * @throws Exception
202      */
203     public  List findMoreRefResult(String sql, List params,
204             Class cls) throws Exception {
205         List list = new ArrayList();
206         int index = 1;
207         pstmt = connection.prepareStatement(sql);
208         if (params != null && !params.isEmpty()) {
209             for (int i = 0; i < params.size(); i++) {
210                 pstmt.setObject(index++, params.get(i));
211             }
212         }
213         resultSet = pstmt.executeQuery();
214         ResultSetMetaData metaData = resultSet.getMetaData();
215         int cols_len = metaData.getColumnCount();
216         while (resultSet.next()) {
217             T resultObject = cls.newInstance();
218             for (int i = 0; i < cols_len; i++) {
219                 String cols_name = metaData.getColumnName(i + 1);
220                 Object cols_value = resultSet.getObject(cols_name);
221                 if (cols_value == null) {
222                     cols_value = "";
223                 }
224                 Field field = cls.getDeclaredField(cols_name);
225                 field.setAccessible(true);
226                 field.set(resultObject, cols_value);
227             }
228             list.add(resultObject);
229         }
230         return list;
231     }
232 
233     public void releaseConn() {
234         if (resultSet != null) {
235             try {
236                 resultSet.close();
237             } catch (SQLException e) {
238                 // TODO Auto-generated catch block
239                 e.printStackTrace();
240             }
241         }
242         if (stmt != null) {
243             try {
244                 stmt.close();
245             } catch (SQLException e) {
246                 // TODO Auto-generated catch block
247                 e.printStackTrace();
248             }
249         }
250         if (pstmt != null) {
251             try {
252                 pstmt.close();
253             } catch (SQLException e) {
254                 // TODO Auto-generated catch block
255                 e.printStackTrace();
256             }
257         }
258         if (connection != null) {
259             try {
260                 connection.close();
261             } catch (SQLException e) {
262                 // TODO Auto-generated catch block
263                 e.printStackTrace();
264             }
265         }
266     }
267 } 
     
    JdbcUtils.java 
    
   

 登录页面的servlet:

 1 package com.product.login.action;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 import java.util.ArrayList;
 6 import java.util.List;
 7 
 8 import javax.servlet.ServletException;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import javax.servlet.http.HttpSession;
13 
14 import com.product.login.dao.LoginDao;
15 import com.product.login.service.LoginService;
16 
17 public class LoginAction extends HttpServlet {
18     private static final long serialVersionUID = 1L;
19     private LoginService service;
20     public LoginAction() {
21         super();
22     }
23     public void destroy() {
24         super.destroy(); 
25     }
26     public void doGet(HttpServletRequest request, HttpServletResponse response)
27             throws ServletException, IOException {
28         this.doPost(request, response);
29 
30     }
31     public void doPost(HttpServletRequest request, HttpServletResponse response)
32             throws ServletException, IOException {
33         String path = request.getContextPath();
34         request.setCharacterEncoding("utf-8");
35         response.setContentType("text/html; charset=utf-8");
36         PrintWriter out = response.getWriter();
37         String username = request.getParameter("username");
38         String pswd = request.getParameter("pswd");
39         System.out.println("username = " + username + " pswd = " + pswd);
40         List params = new ArrayList();
41         params.add(username);
42         params.add(pswd);
43 
44         boolean flag = service.LoginUser(params);
45 
46         boolean fla = service.LoginCat(params);
47         boolean fl = service.LoginDog(params);
48         List list = service.user(params);
49 
50         // JSONObject jsonobj = new JSONObject();
51         // if (list.size() != 0) {
52         // jsonobj.put("用户名", list.get(0));
53         // jsonobj.put("密码", list.get(1));
54         // jsonobj.put("真实姓名", list.get(2));
55         // jsonobj.put("性别", list.get(3));
56         // }
57         HttpSession session = request.getSession();
58         if (list.size() != 0) {
59             session.setAttribute("uname", list.get(0));
60             session.setAttribute("realname", list.get(1));
61             session.setAttribute("pswd", list.get(2));
62             session.setAttribute("sex", list.get(3));
63         }
64         if (flag == true) {
65             response.sendRedirect(path + "/xinxi.jsp");
66         }
67         if (fla == true) {
68             out.print("用户名不存在请重新输入,登陆失败");
69         }
70         if (fl == true) {
71             out.print("密码错误,登陆失败");
72         }
73 
74         out.flush();
75         out.close();
76     }
77     public void init() throws ServletException {
78         // Put your code here
79         service = new LoginDao();
80     }
81 
82 } 
     
    LoginAction.java 
    
   

登录页面的数据操作层:

  1 package com.product.login.dao;
  2 
  3 import java.sql.Connection;
  4 import java.sql.ResultSet;
  5 import java.sql.Statement;
  6 import java.util.ArrayList;
  7 import java.util.List;
  8 import java.util.Map;
  9 
 10 import com.product.jdbc.dbutil.JdbcUtils;
 11 import com.product.login.service.LoginService;
 12 
 13 public class LoginDao implements LoginService {
 14     private JdbcUtils jdbcUtils = null;
 15 
 16     public LoginDao() {
 17         // TODO Auto-generated constructor stub
 18         jdbcUtils = new JdbcUtils();
 19     }
 20 
 21     /*
 22      * ����û���ע���Dao�ı�д
 23      * 
 24      * @see
 25      * com.product.register.service.RegisterService#registerUser(java.util.List)
 26      */
 27     public boolean LoginUser(List params) {
 28         // TODO Auto-generated method stub
 29         boolean flag = false;
 30         jdbcUtils.getConnection();
 31         String sql1 = "select * from userinfo where username=? and pswd=?";
 32         try {
 33             Map map = jdbcUtils.findSimpleResult(sql1, params);
 34             flag = !map.isEmpty() ? true : false;
 35         } catch (Exception e1) {
 36             e1.printStackTrace();
 37         } finally {
 38             jdbcUtils.releaseConn();
 39         }
 40         return flag;
 41     }
 42 
 43     @SuppressWarnings("null")
 44     public boolean LoginCat(List params) {
 45         boolean fla = false;
 46         Connection conn = null;
 47         Statement stmt = null;
 48         ResultSet rs = null;
 49         ResultSet rs1 = null;
 50         conn = jdbcUtils.getConnection();
 51         try {
 52             stmt = conn.createStatement();
 53             rs = stmt.executeQuery("select * from userinfo where username='"
 54                     + params.get(0) + "'");
 55             if (rs.next() == false) {
 56                 fla = true;
 57             }
 58         } catch (Exception e1) {
 59             e1.printStackTrace();
 60         } finally {
 61             jdbcUtils.releaseConn();
 62         }
 63         return fla;
 64     }
 65 
 66     public boolean LoginDog(List params) {
 67         boolean fl = false;
 68         Connection conn = null;
 69         Statement stmt = null;
 70         ResultSet rs = null;
 71         ResultSet rs1 = null;
 72         conn = jdbcUtils.getConnection();
 73         try {
 74             stmt = conn.createStatement();
 75             rs = stmt.executeQuery("select * from userinfo where username='"
 76                     + params.get(0) + "'");
 77             if (rs.next() == true) {
 78                 rs1 = stmt.executeQuery("select * from userinfo where pswd='"
 79                         + params.get(1) + "'");
 80                 if (rs1.next() == false) {
 81                     fl = true;
 82                 }
 83             }
 84         } catch (Exception e1) {
 85             e1.printStackTrace();
 86         } finally {
 87             jdbcUtils.releaseConn();
 88         }
 89         return fl;
 90     }
 91 
 92     // public List user(List params) {
 93     // Connection conn = null;
 94     // Statement stmt = null;
 95     // ResultSet rs = null;
 96     // List userList = new ArrayList<>();
 97     // conn = jdbcUtils.getConnection();
 98     //
 99     // try {
100     // stmt = conn.createStatement();
101     // rs = stmt.executeQuery("select * from userinfo where username='"
102     // + params.get(0) + "'");
103     // while (rs.next()) {
104     // String username = rs.getString("username");
105     // String password = rs.getString("password");
106     // String realname = rs.getString("realname");
107     // String sex = rs.getString("sex");
108     // User user = new User(username, password, realname, sex);
109     // userList.add(user);
110     // }
111     // } catch (Exception e1) {
112     // e1.printStackTrace();
113     // } finally {
114     // jdbcUtils.releaseConn();
115     // }
116     // return userList;
117     //
118     // }
119     public List user(List params) {
120         Connection conn = null;
121         Statement stmt = null;
122         ResultSet rs = null;
123         conn = jdbcUtils.getConnection();
124         List list = new ArrayList();
125         try {
126             stmt = conn.createStatement();
127             rs = stmt.executeQuery("select * from userinfo where username='"
128                     + params.get(0) + "'");
129             System.out.println(params.get(0));
130             while (rs.next()) {
131                 String username = rs.getString("username");
132                 System.out.println(username);
133                 String password = rs.getString("pswd");
134                 System.out.println(password);
135                 String realname = rs.getString("realname");
136                 System.out.println(realname);
137                 String sex = rs.getString("sex");
138                 System.out.println(sex);
139                 // User user = new User(username, password, realname, sex);
140                 list.add(username);
141                 list.add(password);
142                 list.add(realname);
143                 list.add(sex);
144                 System.out.println(list);
145 
146             }
147         } catch (Exception e1) {
148             e1.printStackTrace();
149         } finally {
150             jdbcUtils.releaseConn();
151         }
152         return list;
153     }
154 } 
     
    LoginDao.java 
    
   

登录页面的服务层:

 1 package com.product.login.service;
 2 
 3 import java.util.List;
 4 
 5 public interface LoginService {
 6     public boolean LoginUser(List params);
 7 
 8     public boolean LoginCat(List params);
 9 
10     public boolean LoginDog(List params);
11 
12     public List user(List params);
13 
14 } 
     
    LoginService.java 
    
   

注册页面的servlet:

  1 package com.product.register.action;
  2 
  3 import java.io.IOException;
  4 import java.io.PrintWriter;
  5 import java.util.ArrayList;
  6 import java.util.List;
  7 
  8 import javax.servlet.ServletException;
  9 import javax.servlet.http.HttpServlet;
 10 import javax.servlet.http.HttpServletRequest;
 11 import javax.servlet.http.HttpServletResponse;
 12 
 13 import com.product.register.dao.RegisterDao;
 14 import com.product.register.service.RegisterService;
 15 
 16 public class RegisterAction extends HttpServlet {
 17 
 18     /**
 19      * 
 20      */
 21     private static final long serialVersionUID = 1L;
 22     private RegisterService service;
 23 
 24     /**
 25      * Constructor of the object.
 26      */
 27     public RegisterAction() {
 28         super();
 29     }
 30 
 31     /**
 32      * Destruction of the servlet. 
33 */ 34 public void destroy() { 35 super.destroy(); // Just puts "destroy" string in log 36 // Put your code here 37 } 38 39 /** 40 * The doGet method of the servlet.
41 * 42 * This method is called when a form has its tag value method equals to get. 43 * 44 * @param request 45 * the request send by the client to the server 46 * @param response 47 * the response send by the server to the client 48 * @throws ServletException 49 * if an error occurred 50 * @throws IOException 51 * if an error occurred 52 */ 53 public void doGet(HttpServletRequest request, HttpServletResponse response) 54 throws ServletException, IOException { 55 56 this.doPost(request, response); 57 } 58 59 /** 60 * The doPost method of the servlet.
61 * 62 * This method is called when a form has its tag value method equals to 63 * post. 64 * 65 * @param request 66 * the request send by the client to the server 67 * @param response 68 * the response send by the server to the client 69 * @throws ServletException 70 * if an error occurred 71 * @throws IOException 72 * if an error occurred 73 */ 74 public void doPost(HttpServletRequest request, HttpServletResponse response) 75 throws ServletException, IOException { 76 String path = request.getContextPath(); 77 request.setCharacterEncoding("utf-8"); 78 response.setContentType("text/html; charset=utf-8"); 79 PrintWriter out = response.getWriter(); 80 String username = request.getParameter("username"); 81 String realname = request.getParameter("realname"); 82 String pswd = request.getParameter("pswd"); 83 String pswds = request.getParameter("pswds"); 84 // String sex = new 85 // String(request.getParameter("sex").getBytes("iso-8859-1"), "utf-8"); 86 // String sex = request.getParameter("sex"); 87 // String sex=java.net.URLDecoder.decode(request.getParameter("sex"), 88 // "UTF-8"); 89 // String sex = URLDecoder.decode( 90 // URLDecoder.decode(request.getParameter("sex"), "UTF-8"), 91 // "UTF-8"); 92 // String sex = new String(request.getParameter("name").getBytes( 93 // "ISO-8859-1"), "UTF-8"); 94 String sex = request.getParameter("sex"); 95 96 System.out.println("username = " + username + " realname = " 97 + realname + " pswd = " + pswd + " sex = " + sex); 98 List params = new ArrayList(); 99 params.add(username); 100 params.add(pswd); 101 params.add(realname); 102 params.add(sex); 103 // params.add(b1); 104 // params.add(b2); 105 boolean flag = service.registerUser(params); 106 if (flag) { 107 // response.getOutputStream().write("register success".getBytes()); 108 out.print("注册成功"); 109 response.sendRedirect(path + "/hh.jsp"); 110 } else { 111 out.print("用户名重复,注册失败"); 112 } 113 out.flush(); 114 out.close(); 115 } 116 117 /** 118 * Initialization of the servlet.
119 * 120 * @throws ServletException 121 * if an error occurs 122 */ 123 public void init() throws ServletException { 124 // Put your code here 125 service = new RegisterDao(); 126 } 127 128 } RegisterAction.java

注册页面的数据操作层:

 1 package com.product.register.dao;
 2 
 3 import java.sql.Connection;
 4 import java.sql.ResultSet;
 5 import java.sql.SQLException;
 6 import java.sql.Statement;
 7 import java.util.List;
 8 import java.util.Map;
 9 
10 import com.mysql.jdbc.PreparedStatement;
11 import com.product.jdbc.dbutil.JdbcUtils;
12 import com.product.register.service.RegisterService;
13 
14 public class RegisterDao implements RegisterService {
15     private JdbcUtils jdbcUtils = null;
16 
17     public RegisterDao() {
18         // TODO Auto-generated constructor stub
19         jdbcUtils = new JdbcUtils();
20     }
21 
22     /* 完成用户对注册的Dao的编写
23      * @see com.product.register.service.RegisterService#registerUser(java.util.List)
24      */
25     @Override
26     public boolean registerUser(List params) {
27         // TODO Auto-generated method stub
28         Connection conn=null;
29         Statement stmt=null;
30         ResultSet rs=null;
31         boolean flag = false;
32     
33         conn=jdbcUtils.getConnection();
34         try {
35             stmt=conn.createStatement();
36             rs = stmt.executeQuery("select * from userinfo where username='"+params.get(0)+"'");
37             //System.out.println(params.get(0));
38             if(rs.next()==true){        
39                 flag=false;
40             }else{
41                 flag = jdbcUtils.updateByPreparedStatement("insert into userinfo(username, pswd, realname,sex) values (?, ?, ?,?)", params);                    
42             }
43         } catch (Exception e1) {
44             e1.printStackTrace();
45         }        
46             finally{
47                     jdbcUtils.releaseConn();
48                    }                
49         return flag;
50     }
51 } 
     
    RegisterDao.java 
    
   

注册页面的服务层:

1 package com.product.register.service;
2 
3 import java.util.List;
4 
5 
6 public interface RegisterService {
7     public boolean registerUser(List params);
8 } 
     
    RegisterService.java 
    
   

jsp页面:

登录界面:hh.jsp

  1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8" %>
  2 <%
  3     String path = request.getContextPath();
  4 %>
  5 
  6 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  7 <html>
  8 <head>
  9 <title>后台管理系统title>
 10 <meta http-equiv=Content-Type content="text/html; charset=utf-8">
 11 
 12 <meta http-equiv="pragma" content="no-cache">
 13 <meta http-equiv="cache-control" content="no-cache">
 14 <meta http-equiv="expires" content="0">
 15 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 16 <meta http-equiv="description" content="This is my page">
 17 <style type="text/css">
 18 .neon {
 19     FILTER: glow(color = #002E60, strength    = 3)
 20 }
 21 
 22 DIV {
 23     WIDTH: 70px
 24 }
 25 
 26 BODY {
 27     MARGIN: 0px
 28 }
 29 
 30 BODY {
 31     MARGIN-TOP: 0px;
 32     SCROLLBAR-FACE-COLOR: #005fc5;
 33     FONT-SIZE: 12px;
 34     BACKGROUND: #ffffff;
 35     SCROLLBAR-HIGHLIGHT-COLOR: #799ae1;
 36     SCROLLBAR-SHADOW-COLOR: #799ae1;
 37     SCROLLBAR-3DLIGHT-COLOR: #005fc5;
 38     SCROLLBAR-ARROW-COLOR: #ffffff;
 39     SCROLLBAR-TRACK-COLOR: #aabfec;
 40     SCROLLBAR-DARKSHADOW-COLOR: #799ae1
 41 }
 42 STYLE>
 43 <LINK href="<%=path%>/images/duan_1.css" type=text/css rel=stylesheet>
 44 <META content="MSHTML 6.00.2800.1106" name=GENERATOR>
 45 <style type="text/css">
 46 .style6 {
 47     COLOR: #0000ff
 48 }
 49 
 50 .STYLE7 {
 51     COLOR: #003366;
 52     font-size: 12px;
 53 }
 54 style>
 55 <script type="text/javascript">
 56     function dosubmit() {
 57         var th = document.form2;
 58         if (th.username.value == "") {
 59             alert("用户名不能为空");
 60             th.username.focus();
 61             return;
 62         }
 63         
 64         if (th.pswd.value == "") {
 65             alert("密码不能为空");
 66             th.pswd.focus();
 67             return;
 68         }
 69         th.action="<%=path%>/select"
 70         th.submit();
 71     }
 72 script>
 73 head>
 74 
 75 <body bgColor=#ffffff
 76     onload="MM_preloadImages('<%=path%>/images/ok_2.jpg', '<%=path%>/images/fh_2.jpg')">
 77     <form action="LoginAction" name="form2" method="Post">
 78         <table height=470 cellSpacing=0 cellPadding=0 width=580 aligen=center
 79             border=0>
 80             <tbody>
 81                 <tr>
 82                     <td colSpan=3 height=9 />
 83                 tr>
 84                 <tr>
 85                     <td vAlign=top width=8 background="<%=path%>/images/dhpddw.gif"
 86                         rowSpan=2>
 87                           td>
 88                     <td background="<%=path%>/images/h-1.gif" height=9>td>
 89                     <td width=9 height=9><IMG height=9
 90                         src="<%=path%>/images/jiao.gif" width=9>
 91                     td>
 92                 tr>
 93                 <tr>
 94                     <td vAlign=top align=right width=743 height=452>
 95                         <table cellSpacing=0 cellPadding=0 width=556 border=0>
 96                             
 97                             <tbody>
 98                                 <tr>
 99                                     <td vAligh=bottom width=548 height=27><IMG height=10
100                                         src="<%=path%>/images/jt2.gif" width=10> <span
101                                         class="1bt">用户登录span>
102                                     td>
103                                     <td width=8 rowSpan=3> td>
104                                 tr>
105                                 <tr>
106                                     <td bgColor="#ffffff" height=22>td>
107                                 tr>
108                                 <tr>
109                                     <td class=unnamed1 vAligh=top height=9>
110                                         <table width="99%" border=0 cellPadding=4 cellSpacing=1
111                                             bgColor="#0867b3">
112                                             <tbody>
113                                                 <TR bgColor=#ffffff height=20>
114                                                     <TD width=14% noWrap class="STYLE7">用户名TD>
115                                                     <TD width=24% valign="top" noWrap><INPUT class=text2
116                                                         maxLength=20 size=18 name="username" minLength="1">
117                                                     TD>
118                                                     <TD width=62% noWrap><span class="STYLE7">必须填写!span>
119                                                     TD>
120                                                 TR>
121                                                 
122                                                 <TR bgColor=#ffffff height=20>
123                                                     <TD height="2" noWrap><span class="STYLE7">密码 span>
124                                                     TD>
125                                                     <TD height="2" valign="top" noWrap><INPUT
126                                                         type="password" class=text2 maxLength=20 size=18
127                                                         name="password" minLength="1">
128                                                     TD>
129                                                     <TD height="2" noWrap><span class="STYLE7">必填项span>             <br>
130                                                     TD>
131                                                 TR>
132                                             tbody>                                        
133                                         table><br>                                                        
134                                 tr>
135                                 <TR>
136                                     <TD height=20 align="center"><a
137                                         href="javascript:dosubmit();"> <img
138                                             src="<%=path%>/images/hh2.jpg" name="Image8" width="60"
139                                             height="22" border="0">a>  <a
140                                             href="<%=path%>/pass.jsp"><img
141                                             src="<%=path%>/images/hh1.jpg" name="Image9" width="60"
142                                             height="22" border="0"> a>
143                                     TD>
144                                     <TD>TD>
145                                 TR>
146                             tbody>
147                         table>
148                     td>
149                     <TD width=9 background="<%=path%>/images/s-1.gif">TD>
150                 tr>
151             tbody>
152         table>
153     form>
154 body>
155 html>
hh.jsp

注册界面:login.jsp

 1 <%
 2     String path = request.getContextPath();
 3 %>
 4 <html>  
 5   <head>  
 6     <title>用户登录title>  
 7  
 8     <meta http-equiv=Content-Type content="text/html; charset=utf-8">
 9     <meta http-equiv="pragma" content="no-cache">
10     <meta http-equiv="cache-control" content="no-cache">
11     <meta http-equiv="expires" content="0">
12     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
13     <meta http-equiv="description" content="This is my page">
14       
17   head> 
18   <script type="text/javascript">
19     function dosubmit() {
20         var th = document.form2;
21         if (th.username.value == "") {
22             alert("用户名不能为空");
23             th.username.focus();
24             return;
25         }
26 
27         if (th.password.value == "") {
28             alert("密码不能为空");
29             th.password.focus();
30             return;
31         }
32     
33         th.action="/LoginAction";
34         th.submit();
35 
36     }
37 script>  
38  <body bgcolor="#e3e3e3"> 
39   
40 
41 <form action="LoginAction"name="form2" method="Post"> 
42 
43 <table> 
44    <caption>用户登录caption>  
45    <tr><td>用户名:td><td><input type="text" name="username" size="20"/>td>tr>  
46    <tr><td>密码:td><td><input type="password" name="password" size="21"/>td>tr>  
47    <tr><td><a href="javascript:dosubmit();"><input type="submit" value="登录"/>a>td><td><input type="button" value="注册" onclick="window.location='pass.jsp'">td>tr>  
48    table>  
49    form>  
50    body>  
51 html>  
login.jsp

用户信息返回页面:xinxi.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 
 3 DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 4 
 5 <html>
 6   <head>
 7     <title>My JSP 'xinxi.jsp' starting pagetitle>
 8 
 9     <meta http-equiv="pragma" content="no-cache">
10     <meta http-equiv="cache-control" content="no-cache">
11     <meta http-equiv="expires" content="0">    
12     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
13     <meta http-equiv="description" content="This is my page">
14     
17 <script type="text/javascript">
18      
19      
20      
21 script>
22   head>
23  
24   
25   <body>
26     <%
27     String name = "";
28     String realname = "";
29     String pswd = "";
30     String sex = "";
31     if(session != null){
32         name = (String) session.getAttribute("uname");
33         pswd = (String) session.getAttribute("pswd");
34         realname = (String) session.getAttribute("realname");
35         sex = (String) session.getAttribute("sex");
36       //  if(uname != null && !uname.equals("") && pword != null && !pword.equals("")){
37             out.println("Input UserName: "+ name +"
"); 38 out.println("Input PassWord: "+ pswd +"
"); 39 out.println("Input realname: "+ realname +"
"); 40 out.println("Input sex: "+ sex +"
"); 41 42 } 43 %> 44 body> 45 html>
xinxi.jsp

服务端登录注册页面:

mysql数据库:

实验结果截图:

      

转载请注明出处:https://home.cnblogs.com/u/mmmmm/

本代码实现安卓端注册登录用户名密码到mysql数据库,服务端通过jsp页面也能实现网页登录注册,如果出现乱码才采用GBK编码格式不懂私信我哦!

 

转载于:https://www.cnblogs.com/mmmmm/p/7905344.html

你可能感兴趣的:(android-servlet-jsp-mysql实现登录注册功能)