question_003-JAVA之Context???

本文介绍了一种使用Java通过JNDI查找数据源并获取数据库连接的方法。通过初始化上下文(Context)对象并查找指定的JNDI名称来获取DataSource,进而得到数据库连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JAVA之Context

???数据库连接

------------------------------------------------------------------------


public  Connection getConnectionforGIS() throws Exception {

Connection conn;
Context ctx = (Context) new InitialContext();
if (ctx == null) {
throw new Exception("Context is null.");
}else{
DataSource ds = (DataSource) ctx.lookup(JNDI_NameOfGIS); // ***???????
if (ds == null) {
throw new Exception("DataSource is null.");
}else{
    conn = ds.getConnection();
    System.out.println("get the connection of "+JNDI_NameOfGIS);
}
if (conn.isClosed()) {
throw new Exception("Jndi Connection is closed.");
}else{

}
  
}
return conn;
}



项目要求:1.三类角色,分别为提问者(学生)、回答者(教师)、潜水者(游客),子类(学生Student、教师Teacher)、父类(Person); 2.根据不同角色增加接口,每个角色一个(教师:回答接口Answerer, 学生:提问接口Questioner, 游客:公共接口Common); 3.任何人可以点“赞”,可以评论(公共接口Common); 4.教师类可以为回答打分(接口Answerer)、提问者可以为回答打分(接口Questioner); 5.必须用数据库(如SQLite)存储信息;//目前用户信息表已完成,问题及其相关信息(包括问题内容,提问者;该问题对应的回答(最多3个)及其回答者、点赞数等)待完善 6.重点代码注释; 7.界面设计参考之前的对话和附件。 请你帮我完善代码 package com.example.iask0; import android.content.Intent; import android.view.View; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import com.example.iask0.databinding.ActivityMainBinding; import com.google.android.material.snackbar.Snackbar; import android.view.Menu; import android.view.MenuItem; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.ListView; import android.widget.Toast; import db.DatabaseManager; public class MainActivity extends AppCompatActivity { public TextView identityTextView; public EditText searchEditText; public Button searchButton; private Button askButton; private Button mineButton; private DatabaseManager dbManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); identityTextView = findViewById(R.id.identityTextView); searchEditText = findViewById(R.id.searchEditText); searchButton = findViewById(R.id.searchButton); askButton = findViewById(R.id.askButton); mineButton=findViewById(R.id.mineButton); dbManager = new DatabaseManager(this); Intent intent = getIntent(); String username = intent.getStringExtra("username"); identityTextView.setText("身份:" + getCurrentIdentity());// 设置用户身份 // 搜索按钮点击事件 searchButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String query = searchEditText.getText().toString(); if (!query.isEmpty()) { // 执行搜索操作 Toast.makeText(MainActivity.this, "搜索: " + query, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "请输入搜索内容", Toast.LENGTH_SHORT).show(); } } }); // 提问按钮点击事件(仅学生可按) askButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 执行提问操作 String question = searchEditText.getText().toString(); dbManager.insertQuestion(question, username); Intent intent = new Intent(MainActivity.this, QuestionDetailActivity.class); intent.putExtra("username_asker", username); intent.putExtra("username", username); intent.putExtra("identity", getCurrentIdentity()); intent.putExtra("question_content",question); startActivity(intent); finish(); Toast.makeText(MainActivity.this, "提问", Toast.LENGTH_SHORT).show(); } }); //“我的”按钮 mineButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MyActivity.class); intent.putExtra("username", username); intent.putExtra("identity", getCurrentIdentity()); startActivity(intent); } }); // 根据当前用户身份显示或隐藏提问按钮 toggleAskButtonVisibility(); } private String getCurrentIdentity() { // 从Intent获取登录信息 Intent intent = getIntent(); String username = intent.getStringExtra("username"); String identity = intent.getStringExtra("identity"); // 设置身份和用户名 if (identity == null) { identity = "游客"; } return identity; } private void toggleAskButtonVisibility() { String identity = getCurrentIdentity(); if ("学生".equals(identity)) { askButton.setVisibility(View.VISIBLE); } else { askButton.setVisibility(View.GONE); } } } --- package com.example.iask0; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import db.DatabaseManager; public class QuestionDetailActivity extends AppCompatActivity { private TextView identityTextView; public TextView questionTextView; public TextView askerView; private EditText answerEditText; private Button submitAnswerButton; private ListView answerListView; private DatabaseManager dbManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_question_detail); identityTextView = findViewById(R.id.identityTextView); questionTextView =findViewById(R.id.questionText); askerView = findViewById(R.id.asker); answerEditText = findViewById(R.id.answerEditText); submitAnswerButton = findViewById(R.id.submitAnswerButton); answerListView = findViewById(R.id.answerListView); Button backButton = findViewById(R.id.backButton); Intent intent = getIntent(); String username = intent.getStringExtra("username"); String askername = intent.getStringExtra("username_asker"); String identity = intent.getStringExtra("identity"); String question = intent.getStringExtra("question_content"); // 设置身份和用户名 if (username != null && identity != null) { setIdentity(identity); } else { setIdentity("游客"); } questionTextView.setText("问题内容\n" + question); askerView.setText("提问者:"+ askername); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(QuestionDetailActivity.this, MainActivity.class); intent.putExtra("username", username); intent.putExtra("identity", identity); startActivity(intent); finish(); } }); submitAnswerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String answer = answerEditText.getText().toString(); // 提交回答逻辑 EditText answerContentEditText = findViewById(R.id.answerEditText); String answerContent = answerContentEditText.getText().toString(); String responder = username; long questionId = 1; // 示例问题ID,实际应用中应动态获取 long answerId = dbManager.insertAnswer(answerContent, responder, questionId); if (answerId != -1) { Toast.makeText(QuestionDetailActivity.this, "回答提交成功", Toast.LENGTH_SHORT).show(); } } }); } //界面显示 根据身份 private void setIdentity(String identity) { identityTextView.setText("身份:" + identity); identityTextView.setVisibility(View.VISIBLE); if ("教师".equals(identity)) { answerEditText.setVisibility(View.VISIBLE); submitAnswerButton.setVisibility(View.VISIBLE); } else { answerEditText.setVisibility(View.GONE); submitAnswerButton.setVisibility(View.GONE); } } } --- package db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.ArrayList; import java.util.List; public class DatabaseManager extends SQLiteOpenHelper{ private SQLiteDatabase database; private static final String DATABASE_NAME = "iAsk.db"; private static final int DATABASE_VERSION = 1; // 数据库版本 //user表 public static final String TABLE_NAME = "userss";// 表名 // 列名 public static final String COLUMN_ID = "id"; public static final String COLUMN_NAME = "username"; public static final String COLUMN_PASSWORD = "password"; public static final String COLUMN_IDENTIFY = "identity"; //问题和回答表 public static final String QUESTIONS_TABLE_NAME = "questions"; public static final String ANSWERS_TABLE_NAME = "answers"; public static final String QUESTION_ID = "question_id"; public static final String QUESTION_CONTENT = "question_content"; public static final String QUESTION_ASKER = "question_asker"; public static final String QUESTION_TIMESTAMP = "question_timestamp"; public static final String ANSWER_ID = "answer_id"; public static final String ANSWER_CONTENT = "answer_content"; public static final String ANSWER_RESPONDER = "answer_responder"; public static final String ANSWER_TIMESTAMP = "answer_timestamp"; public static final String ANSWER_LIKES = "answer_likes"; public static final String ANSWER_QUESTION_ID = "answer_question_id"; public DatabaseManager(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); Log.d("DB_DEBUG", "===== 进入 DB ====="); this.getWritableDatabase(); } // 创建表的SQL语句 private static final String TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT NOT NULL, " + COLUMN_PASSWORD + " TEXT NOT NULL, "+ COLUMN_IDENTIFY + " TEXT NOT NULL);";//用户表 private static final String CREATE_QUESTIONS_TABLE = "CREATE TABLE IF NOT EXISTS " + QUESTIONS_TABLE_NAME + " (" + QUESTION_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + QUESTION_CONTENT + " TEXT NOT NULL, " + QUESTION_ASKER + " TEXT NOT NULL, " + QUESTION_TIMESTAMP + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP" + ");";//问题表 private static final String CREATE_ANSWERS_TABLE = "CREATE TABLE IF NOT EXISTS " + ANSWERS_TABLE_NAME + " (" + ANSWER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ANSWER_CONTENT + " TEXT NOT NULL, " + ANSWER_RESPONDER + " TEXT NOT NULL, " + ANSWER_TIMESTAMP + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP, " + ANSWER_LIKES + " INTEGER DEFAULT 0, " + ANSWER_QUESTION_ID + " INTEGER, " + "FOREIGN KEY (" + ANSWER_QUESTION_ID + ") REFERENCES " + QUESTIONS_TABLE_NAME + "(" + QUESTION_ID + ")" + ");";//回答表 @Override public void onCreate(SQLiteDatabase db) { Log.d("DB_DEBUG", " ====== 创 建 表 ====== "); // 创建表 db.execSQL(TABLE_CREATE); db.execSQL(CREATE_QUESTIONS_TABLE); db.execSQL(CREATE_ANSWERS_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//数据库版本更新 // 删除旧表,创建新表(但会丢失数据) db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + QUESTIONS_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + ANSWERS_TABLE_NAME); onCreate(db); } // 打开数据库 public void open() { database=this.getWritableDatabase(); } // 检查用户名是否存在(查找数据-user) public boolean checkUsernameExists(String username) { SQLiteDatabase database = this.getReadableDatabase(); Cursor cursor = database.query(TABLE_NAME, new String[]{COLUMN_NAME}, COLUMN_NAME + "=?", new String[]{username}, null, null, null); boolean exists = cursor.getCount() > 0; cursor.close(); return exists; } // 注册(插入数据-user) public boolean insertUser(String username, String password, String identity) { SQLiteDatabase database = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_NAME, username); values.put(COLUMN_PASSWORD, password); values.put(COLUMN_IDENTIFY, identity); long result = database.insert(TABLE_NAME, null, values); return result != -1; } //登录(查找数据-user) public boolean checkPassword(String username, String password) { SQLiteDatabase readableDatabase = this.getReadableDatabase(); Cursor cursor = readableDatabase.query(//在TABLE_NAME表查询 用户名为 username 的密码 TABLE_NAME, new String[]{COLUMN_PASSWORD}, COLUMN_NAME + " = ?", new String[]{username}, null, null, null ); boolean isPasswordCorrect = false; if (cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndex(COLUMN_PASSWORD); // 获取密码列的索引 if (columnIndex != -1) { String storedPassword = cursor.getString(columnIndex); // 获取存储的密码 isPasswordCorrect = storedPassword.equals(password); //判断密码是否正确 } else { Log.e("DB_DEBUG", "COLUMN_PASSWORD column not found in the table."); } } cursor.close(); return isPasswordCorrect; } //获取身份(查找数据-user) public String getIdentity(String username) { SQLiteDatabase readableDatabase = this.getReadableDatabase(); Cursor cursor = readableDatabase.query( TABLE_NAME, new String[]{COLUMN_IDENTIFY}, COLUMN_NAME + " = ?", new String[]{username}, null, null, null ); String identity = ""; if (cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndex(COLUMN_IDENTIFY); if (columnIndex != -1) { identity = cursor.getString(columnIndex); } } cursor.close(); return identity; } //插入数据(提问和回答-question&answer) public long insertQuestion(String content, String asker) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(QUESTION_CONTENT, content); values.put(QUESTION_ASKER, asker); return db.insert(QUESTIONS_TABLE_NAME, null, values); } public long insertAnswer(String content, String responder, long questionId) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(ANSWER_CONTENT, content); values.put(ANSWER_RESPONDER, responder); values.put(ANSWER_QUESTION_ID, questionId); return db.insert(ANSWERS_TABLE_NAME, null, values); } //查找与更新数据(点赞-answer) public void updateAnswerLikes(long answerId, int likes) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(ANSWER_LIKES, likes); db.update(ANSWERS_TABLE_NAME, values, ANSWER_ID + " = ?", new String[]{String.valueOf(answerId)}); } // 更新数据 public int updateItem(long id, String username, String identify) { ContentValues values = new ContentValues(); values.put(COLUMN_NAME, username); values.put(COLUMN_IDENTIFY, identify); return database.update( TABLE_NAME, values, COLUMN_ID + " = ?", new String[]{String.valueOf(id)} ); } } --- package db; public interface Common { void comment();//评论 void like();//点赞 } --- package db; public interface Questioner { void ask();//提问 void score();//评分 } --- package db; public class Person implements Common{ private long id; private String username; private String password; private String identify; public Person(long id, String username, String password, String identify) { this.id = id; this.username = username; this.password = password; this.identify=identify; }} -- package db; public class Student extends Person implements Questioner{ public Student(long id, String username, String password, String identify,String question) { super(id, username, password, identify); } @Override public void like(){//点赞 } @Override public void comment(){//评论 } @Override public void ask() {//提问 } @Override public void score() {//评分 } }
最新发布
06-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值