want to update my database using my servlet and then diplay it - servlets

the data is not getting updated in the database .
im developing a login functionality where im also registering the user. After the registration, i want to display the details that was used during registration.
im posting my code for the servlet that im using :
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class UserController extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int Id = 0;
private static final String Password = null;
private static final String Username = null;
private static final int Userid = 0;
private static String INSERT_OR_EDIT = "/user.jsp";
private static String LIST_USER = "/listUser.jsp";
public static String PARAM_USERNAME = "uname";
public static String PARAM_PASSWORD = "pass";
private UserDao dao;
private Connection connection;
public UserController() {
super();
dao = new UserDao();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String forward="";
String act = request.getParameter("act");
if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("login")) {
forward= "/Login.jsp";
}
else if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("delete"))
{
int userId = Integer.parseInt(request.getParameter("userId"));
dao.deleteUser(userId);
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("edit")){
forward = INSERT_OR_EDIT;
int userId = Integer.parseInt(request.getParameter("userId"));
User user1 = dao.getUserById(userId);
request.setAttribute("user", user1);
} else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("listUser")){
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("register")){
forward = "/reg.jsp";
// request.setAttribute("users", dao.getAllUsers());
} else
forward = "/Login.jsp";
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String act = request.getParameter("act");
if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("login")) {
String str=request.getParameter("username");
String str1=request.getParameter("password");
if(str.equalsIgnoreCase("shreya")&&str1.equalsIgnoreCase("singh"))
{
System.out.println("Login!");
request.setAttribute("users",dao.getAllUsers());
request.getRequestDispatcher("/listUser.jsp").forward(request, response);
}else
{
System.out.println("Login failed!");
}
}
else
{
}
User user = new User();
Details details = new Details();
user.setFirstName(request.getParameter("firstName"));
user.setLastName(request.getParameter("lastName"));
details.setUsername(request.getParameter("uname"));
details.setPassword(request.getParameter("pass"));
if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("register"))
{
String userid=request.getParameter("userid");
String username=request.getParameter("username");
String password=request.getParameter("password");
String id=request.getParameter("id");
if(userid.equals("") || username.equals("") || password.equals("") || id.equals(""))
{
out.println("Please insert valid data");
}
RequestDispatcher rd = request.getRequestDispatcher("/listUser.jsp");
rd.include(request, response);
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("/listUser.jsp");
rd.include(request, response);
try {
PreparedStatement preparedStatement = connection.
prepareStatement("select * from details where id=?");
preparedStatement.setInt(1, Id);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
details.setUserid(rs.getInt("userid"));
details.setUsername(rs.getString("username"));
details.setPassword(rs.getString("password"));
details.setId(rs.getInt("id"));
}
PreparedStatement preparedStatement1 = connection.
prepareStatement( "insert into details values(?,?,?,?)");
preparedStatement1.setInt(1, Userid);
preparedStatement1.setString(2, Username);
preparedStatement1.setString(3, Password);
preparedStatement1.setInt(4, Id);
int i=preparedStatement1.executeUpdate();
if(i>0)
{
System.out.println("Data update sucessfully");
System.out.print("Student record successfully inserted");
RequestDispatcher rd1 = request.getRequestDispatcher("/registration.jsp");
rd1.include(request, response);
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
}
ive been stuck on this since i dont remember when . help would be appreciated.

Related

Sending GET and POST methods from server to client side (JavaFX)

I have a simple login servlet which checks the email and password if the user is registered or not , now I'm trying to work on a JavaFX app which does the same job by reading from the servlet the information, my servlet works perfect but I don't know how to interact with my servlet from JavaFX , how can I send a response from the servlet to JavaFX ? I've searched a lot but couldn't find anything
Here's my servlet :
import java.io.*;
import java.security.Principal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
#WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
//int attempts = 3;
Date date;
/**
*
*/
private static final long serialVersionUID = -5498866193863633001L;
/**
* HashMap to store all users credentials
*/
private final Map<String, String> credentialsPairs = new HashMap<>();
#Override
public void init(ServletConfig config) throws ServletException {
String delimiter = ",";
String line = "";
/**
* Credentials file will be there in WEB-INF directory as it provide secured
* access only.
*/
String credentialFile = "/WEB-INF/accounts.txt";
/**
* Read the file and prepare Map with username as key and password as value We
* have put this code in init method as it is called once only that will avoid
* overhead of iterating values from file for each request
*/
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
ServletContext context = config.getServletContext();
try {
/**
* Open stream of file
*/
is = context.getResourceAsStream(credentialFile);
if (is != null) {
/**
* Read the file line by line and store email as a key and password as value
*/
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
String[] credentials = line.split(delimiter);
// credentials[0] is email and credentials[1] is password
credentialsPairs.put(credentials[0], credentials[1]);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void service(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException {
/**
* Get user entered credentials
*/
String userEmail = request.getParameter("email");
String userPassword = request.getParameter("password");
PrintWriter out = response.getWriter();
boolean isValidUser = false;
/**
* Get value from Map for user entered email address.
*/
String password = credentialsPairs.get(userEmail);
/**
* If User with entered email address found then we will get password for that
* user
*/
if (password != null) {
/**
* Compare password entered by user with one that is retrieved from file
*/
if (password.equals(userPassword)) {
isValidUser = true;
}
}
}
HttpSession session = request.getSession();
if (isValidUser) {
//HttpSession session = request.getSession();
session.setAttribute("email", userEmail);
//request.getRequestDispatcher("welcome.jsp").include(request, response);
response.sendRedirect("welcome.jsp");
//response.setContentType("text/html");
//response.sendError(HttpServletResponse.SC_FOUND,"Hello");
}
else {
int loginAttempt;
if (session.getAttribute("loginCount") == null)
{
session.setAttribute("loginCount", 0);
loginAttempt = 0;
}
else
{
loginAttempt = (Integer) session.getAttribute("loginCount");
}
//this is 3 attempt counting from 0,1,2
if (loginAttempt >= 2 )
{
long lastAccessedTime = session.getLastAccessedTime();
date = new Date();
long currentTime = date.getTime();
long timeDiff = currentTime - lastAccessedTime;
// 20 minutes in milliseconds
if (timeDiff >= 1200000)
{
//invalidate user session, so they can try again
session.invalidate();
}
else
{
// Error message
session.setAttribute("message","You have exceeded the 3 failed login
attempt. Please try loggin in in 20 minutes.");
//request.getRequestDispatcher("fail.jsp");
out.println("You have exceeded the 3 failed login attempt. Please
try loggin in in 20 minutes.");
}
}
else
{
loginAttempt++;
int allowLogin = 3-loginAttempt;
session.setAttribute("message","loginAttempt= "+loginAttempt+". Invalid
username or password. You have "+allowLogin+" attempts remaining. Please try again!");
out.println("Invalid email or password , please try again");
final String message = "The requested page not found";
response.sendError(HttpServletResponse.SC_NOT_FOUND,message);
}
session.setAttribute("loginCount",loginAttempt);
}
}
public void destroy() {
/**
* Free up the map
*/
credentialsPairs.clear();
}
}
Here's my JavaFX code :
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HelloApplication extends Application {
TextField tName;
TextField tPassword;
ComboBox comboBox;
Button login;
VBox vBox;
BorderPane borderPane;
URL url = null;
HttpURLConnection con = null;
int flag =0;
#Override
public void start(Stage stage) throws IOException {
stage.setTitle("login Page");
stage.setResizable(false);
setDesign();
comboBox.setOnAction(e->{
if(comboBox.getSelectionModel().isSelected(0)){
flag =0;
}else if (comboBox.getSelectionModel().isSelected(1)){
flag =1;
}
});
login.setOnAction(e->{
if(flag==0){
try {
System.out.println("get");
String name =tName.getText();
String password =tPassword.getText();
url = new URL("http://localhost:8080/try8_war_exploded/login?
email="+name+"&password="+password);
con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type","text/html");
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
} catch(Exception c) {
c.printStackTrace();
}
}
else {
}
int status = 0;
StringBuffer data = new StringBuffer();
try {
status = con.getResponseCode();
if(status > 299) {
System.out.println("error "+status);
System.out.println(con.getErrorStream());
return;
}
BufferedReader in = new BufferedReader(new
InputStreamReader(con.getInputStream()));
String str = null;
while((str=in.readLine()) != null) data.append(str);
System.out.println("here");
System.out.println(str);
in.close();
con.disconnect();
} catch(Exception c) {
c.printStackTrace();
}
});
Scene scene =new Scene(borderPane,350,180);
stage.setScene(scene);
stage.show();
}
public void setDesign(){
borderPane = new BorderPane();
borderPane.setPadding(new Insets(20,20,20,20));
vBox = new VBox(10);
vBox.setAlignment(Pos.CENTER);
HBox hBox1 =new HBox(5);
hBox1.setAlignment(Pos.CENTER);
HBox hBox2 =new HBox(5);
hBox2.setAlignment(Pos.CENTER);
Label label1= new Label("E-mail");
tName = new TextField();
tName.setMaxWidth(150);
hBox1.getChildren().addAll(label1,tName);
Label label2= new Label("Password");
tPassword = new TextField();
tPassword.setMaxWidth(150);
hBox2.getChildren().addAll(label2,tPassword);
comboBox = new ComboBox();
comboBox.getItems().add("Get");
comboBox.getItems().add("Post");
comboBox.getSelectionModel().selectFirst();
login = new Button("Login");
vBox.getChildren().addAll(hBox1,hBox2,comboBox,login);
borderPane.setTop(vBox);
}
public static void main(String[] args) {
launch();
}
}
I'm posting the entire codes so that everything is clear

Image Uploading to firebase successfully but not showing in phone

I am trying to build a messenger type app. And for this, I have uploaded an image from my phone to firebase. And the image is successfully stored in firebase storage. And I am trying to show the image on my phone. And I use Picasso to retrieve the image from firebase. But my picture isn't showing. But when I add placeholder I can see the default image that is set by a placeholder. How can I solve this problem? My code is given below:
package com.example.whatsapp2;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.IOException;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingsActivity extends AppCompatActivity {
private Button UpdateAccountSetting;
private EditText userName, userStatus;
private CircleImageView userProfileImage;
private String currentUserId;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;
private Toolbar SettingsToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
FirebaseApp.initializeApp(this);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
InitializeFields();
userName.setVisibility(View.INVISIBLE);
UpdateAccountSetting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpdateSettings();
}
});
RetrieveUserInfo();
userProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GalleryPick);
}
});
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(currentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")) && (dataSnapshot.hasChild("image"))){
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
//Picasso.get().load(retrieveProfileImage).placeholder(R.drawable.profile_image).resize(100,100).centerCrop().into(userProfileImage);
}
else if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))){
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveStatus);
}
else {
userName.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(),"Please set & update your profile information...",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void UpdateSettings() {
String setUserName = userName.getText().toString();
String setStatus = userStatus.getText().toString();
if (TextUtils.isEmpty(setUserName)) {
Toast.makeText(this,"Please write your user name first....",Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setStatus)) {
Toast.makeText(this,"Please write your status....",Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("uid", currentUserId);
profileMap.put("name", setUserName);
profileMap.put("status", setStatus);
RootRef.child("Users").child(currentUserId).updateChildren(profileMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(getApplicationContext(),"Profile Updated Successfully...",Toast.LENGTH_SHORT).show();
}
else {
String message = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error : "+message,Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void InitializeFields() {
UpdateAccountSetting = findViewById(R.id.update_settings_button);
userName = findViewById(R.id.set_user_name);
userStatus =findViewById(R.id.set_profile_status);
userProfileImage = findViewById(R.id.set_profile_image);
loadingBar = new ProgressDialog(this);
SettingsToolbar = findViewById(R.id.settings_toolbar);
setSupportActionBar(SettingsToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setTitle("Account Settings");
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(this,MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GalleryPick && resultCode == RESULT_OK && data != null){
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
//userProfileImage.setImageURI(ImageUri);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
loadingBar.setTitle("Set Profile Image");
loadingBar.setMessage("Please wait, your profile image is updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImagesRef.child(currentUserId+".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Profile Image uploaded Successfully...",Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
RootRef.child("Users").child(currentUserId).child("image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Image save in Database Successfully...",Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else{
String message = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error:"+message,Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else{
String message = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error:"+message,Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
}
}
You can resolve this issue by simply adding 1 line of code:
//in this block
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null ) {
Uri ImageUri = data.getData();
userProfileImage.setImageURI(ImageUri); //add this line

Error copying database using a preloaded database for sqlite

Please i am trying to create a login from a preloaded database. But i am having problems copying database. Below is my debug error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.babbangona.preloadedtestingagain, PID: 11863
java.lang.Error: Error copying database
at com.babbangona.preloadedtestingagain.DBHandler.createDatabase(DBHandler.java:42)
at com.babbangona.preloadedtestingagain.DBcopyActivity$1.onClick(DBcopyActivity.java:28)
at android.view.View.performClick(View.java:6199)
at android.view.View$PerformClick.run(View.java:23235)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1073)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934) I/art:
Enter while loop. I/art: Enter while loop. Disconnected from the
target VM, address: 'localhost:8600', transport: 'socket'
My DBHandler java file:
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class DBHandler extends SQLiteOpenHelper{
String DB_PATH = null;
private static String DB_NAME = "rehoboth.db";
private SQLiteDatabase myDatabase;
private final Context myContext;
public DBHandler(Context context){
super(context, DB_NAME, null, 2);
this.myContext = context;
this.DB_PATH = "/data/data" + context.getPackageName() + "/databases/";
Log.e("Path 1", DB_PATH);
}
public void createDatabase() throws IOException {
boolean dbExist = checkDatabase();
if(dbExist){
/* openDatabase();
int cVersion = myDatabase.getVersion();
if(cVersion != 2){
onUpgrade(myDatabase, myDatabase.getVersion(),2);
close();
}*/
}else{
this.getReadableDatabase();
try{
copyDatabase();
}catch (IOException e){
throw new Error("Error copying database");
}
}
}
private boolean checkDatabase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDatabase() throws IOException{
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[10];
int length;
while((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDatabase() throws SQLException{
String myPath = DB_PATH + DB_NAME;
myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close(){
if(myDatabase != null)
myDatabase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db){
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
if(newVersion > oldVersion)
try{
copyDatabase();
}catch (IOException e){
e.printStackTrace();
}
}
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy){
return myDatabase.query("rehoboth", null, null, null, null, null, null);
}
}
My main Activity:
import android.app.Activity;
import android.database.Cursor;
import android.database.SQLException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
public class DBcopyActivity extends Activity {
Cursor c = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dbcopy);
((Button) findViewById(R.id.button1)).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
DBHandler myDbHelper = new DBHandler(DBcopyActivity.this);
try{
myDbHelper.createDatabase();
}catch(IOException ioe){
throw new Error("Unable to create database");
}try{
myDbHelper.openDatabase();
}catch(SQLException sqle){
throw sqle;
}
Toast.makeText(DBcopyActivity.this, "Successfully Imported", Toast.LENGTH_SHORT).show();
c = myDbHelper.query("rehoboth", null, null, null, null, null, null);
if(c.moveToFirst()){
do{
Toast.makeText(DBcopyActivity.this,
"_id: " + c.getString(0) + "\n" +
"NAME: " + c.getString(1) + "\n" +
"PASSWORD: " + c.getString(2),
Toast.LENGTH_LONG).show();
}while (c.moveToNext());
}
}
});
}
}

error when trying to execute the login servlet

it says that : HTTP method POST is not supported by this URL.
The specified HTTP method is not allowed for the requested resource.
here's my servlet code:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class UserController extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int Id = 0;
private static final String Password = null;
private static final String Username = null;
private static final int Userid = 0;
private static String INSERT_OR_EDIT = "/user.jsp";
private static String LIST_USER = "/listUser.jsp";
public static String PARAM_USERNAME = "uname";
public static String PARAM_PASSWORD = "pass";
private UserDao dao;
private Connection connection;
public UserController() {
super();
dao = new UserDao();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String forward="";
String act = request.getParameter("act");
if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("login")) {
forward= "/Login.jsp";
}
else if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("delete"))
{
int userId = Integer.parseInt(request.getParameter("userId"));
dao.deleteUser(userId);
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("edit")){
forward = INSERT_OR_EDIT;
int userId = Integer.parseInt(request.getParameter("userId"));
User user1 = dao.getUserById(userId);
request.setAttribute("user", user1);
} else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("listUser")){
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("register")){
forward = "/reg.jsp";
// request.setAttribute("users", dao.getAllUsers());
}else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("update")){
forward = "/welcome.jsp";
} else
forward = "/Login.jsp";
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response, Details details) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String act = request.getParameter("act");
if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("login")) {
String str=request.getParameter("username");
String str1=request.getParameter("password");
if(str.equalsIgnoreCase("shreya")&&str1.equalsIgnoreCase("singh"))
{
System.out.println("Login!");
request.setAttribute("users",dao.getAllUsers());
request.getRequestDispatcher("/listUser.jsp").forward(request, response);
}else
{
System.out.println("Login failed!");
}
}
if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("register"))
{
String userid1=request.getParameter("userid");
String username=request.getParameter("username");
String password=request.getParameter("password");
String id=request.getParameter("id");
if(userid1.equals("") || username.equals("") || password.equals("") || id.equals(""))
{
out.println("Please insert valid data");
}
RequestDispatcher rd = request.getRequestDispatcher("/listUser.jsp");
rd.include(request, response);
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("/listUser.jsp");
rd.include(request, response);
try {
PreparedStatement preparedStatement = connection.
prepareStatement("select * from details where id=?");
preparedStatement.setInt(1, Id);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
details.setUserid(rs.getInt("userid"));
details.setUsername(rs.getString("username"));
details.setPassword(rs.getString("password"));
details.setId(rs.getInt("id"));
}
PreparedStatement preparedStatement1 = connection.
prepareStatement( "insert into details values(?,?,?,?)");
preparedStatement1.setInt(1, Userid);
preparedStatement1.setString(2, Username);
preparedStatement1.setString(3, Password);
preparedStatement1.setInt(4, Id);
int i=preparedStatement1.executeUpdate();
if(i>0)
{
System.out.println("Data updated sucessfully");
System.out.print("Student record successfully inserted");
RequestDispatcher rd1 = request.getRequestDispatcher("/registration.jsp");
rd1.include(request, response);
}
}
catch (Exception e)
{
System.out.println(e);
}
if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("update"))
{
String userid=request.getParameter("userid");
String username=request.getParameter("username");
String password=request.getParameter("password");
String id=request.getParameter("id");
try
{
Statement stmt = connection.createStatement();
String sql = "UPDATE details SET username='hi',password='hello' where id=1";
stmt.executeUpdate(sql);
dao.saveData(details, sql);
System.out.println("Data update sucessfully");
}
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally{
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
}
earlier it was working properly . I guess there's something wrong with the post method
The HttpServlet doPost(HttpServletRequest req, HttpServletResponse resp) method is
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_post_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
Which immediately responds with METHOD_NOT_ALLOWED. You haven't overriden this method. You have overloaded it to add a Details parameter. It's therefore not being called
protected void doPost(HttpServletRequest request, HttpServletResponse response, Details details) throws ServletException, IOException {
Where do you expect these Details to come from? If anything, override the doPost method and make it call your method.
Change
protected void doPost(HttpServletRequest request, HttpServletResponse response,
Details details) throws ServletException, IOException
To
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
doPost

Unable to send the value of two attributes to JSP from servlet using requestdispatcher

Please help . Below is my code to redirect the request with two attributes to JSP but both of the below two attributes returns the value of passWord .
1)user_Name
2)Pass_word
for example , ABC is my username and XYZ is my password which is get from the "FORM" but my second value i.e the value of the passWord variable is appears in both of the attribute.
printing inside the jsp page :
user_Name: XYS (Should be ABC instead of XYZ)
pass_Word: XYZ
servlet :
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class JndiConn extends HttpServlet implements Servlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String userName=request.getParameter("Username");
String passWord=request.getParameter("password");
String user_Name="";
request.setAttribute(user_Name,userName);
String pass_Word="";
request.setAttribute(pass_Word,passWord);
RequestDispatcher rd=request.getRequestDispatcher ("GetParameter.jsp");
System.out.println(userName);
System.out.println(passWord);
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
Connection connection = getConnection();
if (connection != null) {
String sql = "SELECT count(1) FROM scott.login_user where login_id ='"+userName+"' and password='"+passWord+"'";
String sql1 = "select SYSDATE from dual";
System.out.println(sql);
try{
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
int number=rs.getInt("count(1)");
System.out.println("Result value is "+number);
if(number==1)
{
System.out.println("THE LOGIN SUCCESS FOR::"+userName);
String sql2 = "INSERT INTO SCOTT.LOGIN_USER VALUES(3,'VINOTH','vinoth55','SCOTT',to_date('08/06/13','DD/MM/RR'),105)";
PreparedStatement statement1 = connection.prepareStatement(sql2);
ResultSet rs1 = statement1.executeQuery();
rd.forward(request, response);
}
else{
System.out.println("THE LOGIN FAILURE FOR "+userName);
rd.forward(request, response);
}
}
connection.close();
}catch(Exception e){
System.out.println(e);
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
private Connection getConnection() {
Connection connection = null;
try {
InitialContext context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("vinothprd");
connection = dataSource.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
Below is my JSP to print the user_Name and pass_Word :
JSP:
String user_Name="";
String userName=(String)request.getAttribute(user_Name);
String pass_Word="";
String passWord=(String)request.getAttribute(pass_Word);
System.out.println("user_Name: "+userName);
System.out.println("pass_Word: "+passWord);
Thanks for your help in advance...
In Servlet you are setting, attributes using empty value.
String user_Name="";
request.setAttribute(user_Name,userName);
String pass_Word="";
request.setAttribute(pass_Word,passWord);
First of all, this is wrong and I don't know why you are doing this.
In JSP, When you access request.getAttribute(user_Name); // which is empty "",
you will get the value of password as username was overridden.
Solution:
You should set attribute like
EDIT Servlet
String userName=request.getParameter("Username");
String passWord=request.getParameter("password");
String user_Name="userName";
request.setAttribute(user_Name, userName);
String pass_Word="passWord";
request.setAttribute(pass_Word, passWord);
then in JSP
String user_Name="userName"
String userName=(String) request.getAttribute(user_Name);
String pass_Word="passWord";
String passWord=(String)request.getAttribute(pass_Word);
See: http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#setAttribute

Resources