问:
Display the result of a registration page on top of the registration form
I know little about coding.
This is relating to a registration form i am creating. I have created the form. It is adding the form to database. But it want it to be displaying the result, for example - 'Passwords not matching, please try again' on top of the form. How to get that?
Thanks in advance

Here my code:

```<code><?php

$conn = mysqli_connect("localhost","root","");
if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
mysqli_select_db($conn, 'registration');

    if(isset($_POST['submitbutton'])){

        if ($_POST['password'] == $_POST['confirm_password']) {
            $email = mysqli_real_escape_string($conn, $_POST['email']);
            $password = mysqli_real_escape_string($conn, $_POST['password']);
            $gender = mysqli_real_escape_string($conn, $_POST['gender']);
            $fname = mysqli_real_escape_string($conn, $_POST['fname']);
            $lname = mysqli_real_escape_string($conn, $_POST['lname']);
            $firm = mysqli_real_escape_string($conn, $_POST['firm']);

            $check_email_exists = mysqli_query($conn, "SELECT email FROM users WHERE email = '$email'");
            $count = mysqli_num_rows($check_email_exists);
            if ($count == 0) {
                $sql = "INSERT INTO users(email, password, gender, fname, lname, firm) VALUES('$email', '$password', '$gender', '$fname', '$lname', '$firm')";

                if(mysqli_query($conn, $sql)){
                    echo "Records added successfully.";
                } else{
                    echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
                }

                // close connection
                mysqli_close($conn);
            } else {
                die('Email exists, Please use a different email');
            }
        }
        else {
            die('Passwords not matching, please try again');
        }
    }
</code>```

and here my html

```<code><div class="registration-container">
    <div class="registrationpage-heading">
        <h2>Kostenlos und ohne Installation testen</h2>
        <p>Nutzen Sie den kostenlosen Funktionumfang von bmgenerator zeitlich uneingeschränkt. Weder Bankdaten noch Kreditkarte notwendig.</p>
    </div>

    <div class="user-login">
        <form class="login-form" action="user_login.php" method="post">
            <input required type="email" name="email" id="user_email" style="color:#888" size="35" value="E-mail"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>

            <input required type="password" name="password" id="user_password" style="color:#888" size="35" placeholder="Passwort"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>

            <input required type="password" name="confirm_password" id="user_confirm_password" style="color:#888" size="35" placeholder="Passwort wiederholen"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>

            <select name="gender">
            <option>Herr</option>
            <option>Frau </option>
            </select><br><br>

            <input required type="text" name="fname" id="user_firstname" style="color:#888" size="35" placeholder="Vorname"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>

            <input required type="text" name="lname" id="user_lastname" style="color:#888" size="35" placeholder="Nachname"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>

            <input required type="text" name="firm" id="user_companyname" style="color:#888" size="35" placeholder="Firmenname"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>

            <input type="submit" name="submitbutton" id="submit" value="Kostenlos registrieren">
        </form>
    </div>

    <div class="register-terms">
        <p>Mit der Registrierung stimmen Sie den Datenschutzbestimmungen und den AGB zu.</p>
    </div>
</div>
</code>```

答:
First of all it is not recommended to place the form and the processor page on the same page to void redundant insert via refresh. However, in the processor section you have to use any mean of redirect after any end of the process, in your code die() and echo should be replaced with the redirect with a parameter of pre specified message. for instance, you have four ends in your processor, so your code should look like:

```<code><?php

$conn = mysqli_connect("localhost","root","");
if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
mysqli_select_db($conn, 'registration');

    if(isset($_POST['submitbutton'])){

        if ($_POST['password'] == $_POST['confirm_password']) {
            $email = mysqli_real_escape_string($conn, $_POST['email']);
            $password = mysqli_real_escape_string($conn, $_POST['password']);
            $gender = mysqli_real_escape_string($conn, $_POST['gender']);
            $fname = mysqli_real_escape_string($conn, $_POST['fname']);
            $lname = mysqli_real_escape_string($conn, $_POST['lname']);
            $firm = mysqli_real_escape_string($conn, $_POST['firm']);

            $check_email_exists = mysqli_query($conn, "SELECT email FROM users WHERE email = '$email'");
            $count = mysqli_num_rows($check_email_exists);
            if ($count == 0) {
                $sql = "INSERT INTO users(email, password, gender, fname, lname, firm) VALUES('$email', '$password', '$gender', '$fname', '$lname', '$firm')";

                if(mysqli_query($conn, $sql)){
                    header("Location: user_login.php?msg=1");
                    exit();
                } else{
                    header("Location: user_login.php?msg=2");
                    exit();
                }

                // close connection
                mysqli_close($conn);
            } else {
                header("Location: user_login.php?msg=3");
                exit();
            }
        }
        else {
            header("Location: user_login.php?msg=4");
            exit();
        }
    }

$msg = [
  "Records added successfully.",
   "SQL Error",
   "Email exists, Please use a different email",
   "Passwords not matching, please try again"
];

if (isset($_GET['msg']) && isset($msg[($_GET['msg']-1)])){
 $message = $msg[($_GET['msg']-1)];
}

// In your form
....
</div>
 <?php if (isset($message)): ?>
 <div class="message"><?=$message;?></div>
<?php endif; ?>
    <div class="user-login">
        <form class="login-form....
</code>```

Body:
I know little about coding.
This is relating to a registration form i am creating. I have created the form. It is adding the form to database. But it want it to be displaying the result, for example - 'Passwords not matching, please try again' on top of the form. How to get that?
Thanks in advance

Here my code:

<?php

$conn = mysqli_connect("localhost","root","");
if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
mysqli_select_db($conn, 'registration');

    if(isset($_POST['submitbutton'])){

        if ($_POST['password'] == $_POST['confirm_password']) {
            $email = mysqli_real_escape_string($conn, $_POST['email']);
            $password = mysqli_real_escape_string($conn, $_POST['password']);
            $gender = mysqli_real_escape_string($conn, $_POST['gender']);
            $fname = mysqli_real_escape_string($conn, $_POST['fname']);
            $lname = mysqli_real_escape_string($conn, $_POST['lname']);
            $firm = mysqli_real_escape_string($conn, $_POST['firm']);

            $check_email_exists = mysqli_query($conn, "SELECT email FROM users WHERE email = '$email'");
            $count = mysqli_num_rows($check_email_exists);
            if ($count == 0) {
                $sql = "INSERT INTO users(email, password, gender, fname, lname, firm) VALUES('$email', '$password', '$gender', '$fname', '$lname', '$firm')";

                if(mysqli_query($conn, $sql)){
                    echo "Records added successfully.";
                } else{
                    echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
                }

                // close connection
                mysqli_close($conn);
            } else {
                die('Email exists, Please use a different email');
            }
        }
        else {
            die('Passwords not matching, please try again');
        }
    }

and here my html

Kostenlos und ohne Installation testen

Nutzen Sie den kostenlosen Funktionumfang von bmgenerator zeitlich uneingeschränkt. Weder Bankdaten noch Kreditkarte notwendig.

        <form class="login-form" action="user_login.php" method="post">
            <input required type="email" name="email" id="user_email" style="color:#888" size="35" value="E-mail"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" >

            <input required type="password" name="password" id="user_password" style="color:#888" size="35" placeholder="Passwort"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" >

            <input required type="password" name="confirm_password" id="user_confirm_password" style="color:#888" size="35" placeholder="Passwort wiederholen"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" >

            <select name="gender">
            <option>Herr</option>
            <option>Frau </option>
            </select>

            <input required type="text" name="fname" id="user_firstname" style="color:#888" size="35" placeholder="Vorname"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" >

            <input required type="text" name="lname" id="user_lastname" style="color:#888" size="35" placeholder="Nachname"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" >

            <input required type="text" name="firm" id="user_companyname" style="color:#888" size="35" placeholder="Firmenname"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" >

            <input type="submit" name="submitbutton" id="submit" value="Kostenlos registrieren">
        </form>

Mit der Registrierung stimmen Sie den Datenschutzbestimmungen und den AGB zu.

Body:
First of all it is not recommended to place the form and the processor page on the same page to void redundant insert via refresh. However, in the processor section you have to use any mean of redirect after any end of the process, in your code die() and echo should be replaced with the redirect with a parameter of pre specified message. for instance, you have four ends in your processor, so your code should look like:

<?php

$conn = mysqli_connect("localhost","root","");
if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
mysqli_select_db($conn, 'registration');

    if(isset($_POST['submitbutton'])){

        if ($_POST['password'] == $_POST['confirm_password']) {
            $email = mysqli_real_escape_string($conn, $_POST['email']);
            $password = mysqli_real_escape_string($conn, $_POST['password']);
            $gender = mysqli_real_escape_string($conn, $_POST['gender']);
            $fname = mysqli_real_escape_string($conn, $_POST['fname']);
            $lname = mysqli_real_escape_string($conn, $_POST['lname']);
            $firm = mysqli_real_escape_string($conn, $_POST['firm']);

            $check_email_exists = mysqli_query($conn, "SELECT email FROM users WHERE email = '$email'");
            $count = mysqli_num_rows($check_email_exists);
            if ($count == 0) {
                $sql = "INSERT INTO users(email, password, gender, fname, lname, firm) VALUES('$email', '$password', '$gender', '$fname', '$lname', '$firm')";

                if(mysqli_query($conn, $sql)){
                    header("Location: user_login.php?msg=1");
                    exit();
                } else{
                    header("Location: user_login.php?msg=2");
                    exit();
                }

                // close connection
                mysqli_close($conn);
            } else {
                header("Location: user_login.php?msg=3");
                exit();
            }
        }
        else {
            header("Location: user_login.php?msg=4");
            exit();
        }
    }

$msg = [
  "Records added successfully.",
   "SQL Error",
   "Email exists, Please use a different email",
   "Passwords not matching, please try again"
];

if (isset($_GET['msg']) && isset($msg[($_GET['msg']-1)])){
 $message = $msg[($_GET['msg']-1)];
}

// In your form
....
</div>
 <?php if (isset($message)): ?>
 <div class="message"><?=$message;?></div>
<?php endif; ?>
    <div class="user-login">
        <form class="login-form....


来源: stackexchange

问:
iPhone application crash on launch
We are receiving a crash log from iTunes connect that is a little strange.

We were preivously having problems with our app taking to long to return from ApplicationDidFinishLaunching. This was caused by doing a too much work inside of applicationDidFinishLaunching and we exceeded the 20 second time out on slower devices.

To fix this we moved all of our setup code out of ApplicationDidFinishLaunching and moved it into a special secondaryLoadingController. On top of that we moved the setup code inside of that controller to a separate thread.

However, we are still seeing crash logs that say our app failed to launch in time even though the crash log shows a call to [UIApplication _reportAppLaunchFinished]. To me, this indicates that the app has finished launching and we should be free to take as long as we want to run our setup code.  Below is the crash log.

Thanks for any help you can offer.

```<code>Incident Identifier: 429360D5-6B02-49BE-9A0F-164DC521BE36
Hardware Model:      iPod2,1
Process:         XYZ [357]
Path:            /var/mobile/Applications/D5038F26-CC5B-48E5-824E-090163B5C0C4/XYZ.app/XYZ
Identifier:      XYZ
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2010-09-28 13:35:25.138 -0700
OS Version:      iPhone OS 4.0 (8A293)
Report Version:  104

Exception Type:  00000020
Exception Codes: 0x8badf00d
Highlighted Thread:  0

Application Specific Information:
com.xyz.xyz failed to launch in time
elapsed total CPU time (seconds): 20.180 (user 15.910, system 4.270), 100% CPU
elapsed application CPU time (seconds): 10.960, 54% CPU

Thread 0:
0   libobjc.A.dylib                   0x3523a50c objc_msgSend + 44
1   CoreFoundation                    0x363bf568 -[__NSArrayM addObject:]
2   XYZ                        0x0000a152 -[Database fetchDrinks:] + 290
3   XYZ                        0x0000677c -[Database getAllDrinks] + 136
4   XYZ                        0x0003a164 -[SecondaryLoadingViewController viewDidLoad] + 208
5   UIKit                             0x323e582c -[UIViewController view]
6   UIKit                             0x323f9628 -[UIViewController viewControllerForRotation]
7   UIKit                             0x323f9574 -[UIViewController _visibleView]
8   UIKit                             0x323f94fc -[UIViewController rotatingContentViewForWindow:]
9   UIKit                             0x3249a514 -[UIClientRotationContext initWithClient:toOrientation:duration:andWindow:]
10  UIKit                             0x32499314 -[UIWindow _setRotatableClient:toOrientation:duration:force:]
11  UIKit                             0x32497d78 -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:]
12  UIKit                             0x32497534 -[UIViewController presentModalViewController:withTransition:]
13  UIKit                             0x324977fc -[UIViewController _tryRecursivelyPresentModalViewController:withTransition:]
14  UIKit                             0x324977c0 -[UIViewController _tryRecursivelyPresentModalViewController:withTransition:]
15  UIKit                             0x32496e00 -[UIViewController presentModalViewController:withTransition:]
16  UIKit                             0x3249699c -[UIViewController presentModalViewController:animated:]
17  XYZ                        0x000044a2 -[HomeViewController viewDidLoad] + 82
18  UIKit                             0x323e582c -[UIViewController view]
19  UIKit                             0x323fd68c -[UIViewController contentScrollView]
20  UIKit                             0x323fd4ac -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:]
21  UIKit                             0x323fd358 -[UINavigationController _layoutViewController:]
22  UIKit                             0x323fccb8 -[UINavigationController _startTransition:fromViewController:toViewController:]
23  UIKit                             0x323fca1c -[UINavigationController _startDeferredTransitionIfNeeded]
24  UIKit                             0x323fc90c -[UINavigationController viewWillLayoutSubviews]
25  UIKit                             0x323fc43c -[UILayoutContainerView layoutSubviews]
26  UIKit                             0x32370ab0 -[UIView(CALayerDelegate) _layoutSublayersOfLayer:]
27  CoreFoundation                    0x363c85ba -[NSObject(NSObject) performSelector:withObject:]
28  QuartzCore                        0x30c8c61c 0x30c82000 + 42524
29  QuartzCore                        0x30c8c2a4 0x30c82000 + 41636
30  QuartzCore                        0x30c8bbb0 0x30c82000 + 39856
31  QuartzCore                        0x30c8b7d8 0x30c82000 + 38872
32  QuartzCore                        0x30c8b684 0x30c82000 + 38532
33  UIKit                             0x323d99d4 -[UIApplication _reportAppLaunchFinished]
34  UIKit                             0x3251d77c -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:]
35  UIKit                             0x323d87b8 -[UIApplication handleEvent:withNewEvent:]
36  UIKit                             0x323d7eb4 -[UIApplication sendEvent:]
37  UIKit                             0x323d77e8 _UIApplicationHandleEvent
38  GraphicsServices                  0x33c4dedc PurpleEventCallback
39  CoreFoundation                    0x364142ac __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__
40  CoreFoundation                    0x364161d6 __CFRunLoopDoSource1
41  CoreFoundation                    0x3641718e __CFRunLoopRun
42  CoreFoundation                    0x363be0bc CFRunLoopRunSpecific
43  CoreFoundation                    0x363bdfca CFRunLoopRunInMode
44  UIKit                             0x32363b18 -[UIApplication _run]
45  UIKit                             0x32361fb8 UIApplicationMain
46  XYZ                        0x00002b20 main + 36
47  XYZ                        0x00002af0 start + 32
</code>```

UPDATE
I am attempting to run the time consuming import code (only happens on an application update) on a separate thread. I am even updating the GUI using an AlertView with an embedded progress bar so the user knows something is still happening. During our testing process this works fine. Below is the thread code that seems to not be working. The crash log seems to indicate that all work is being done on the main thread.

```<code>    if ([database appDidUpdate] == YES) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    dbImportThread = [[NSThread alloc] initWithTarget:self selector:@selector(import) object:nil];
    [dbImportThread start];
    [pool release];

- (void)import {
 //do importing work and update the gui with the progress
}
</code>```

答: Although I don't have direct experience with this, after reading your crash log, it appears that the device noticed your app taking 100% CPU time for slightly longer than 20 seconds after launch. It would appear that even though this CPU usage isn't inside the applicationDidFinishLaunching: method, the operating system isn't fooled and terminates your app.

ContentLicense: CC BY-SA 2.5

Title: iPhone application crash on launch

Body:
We are receiving a crash log from iTunes connect that is a little strange.

We were preivously having problems with our app taking to long to return from ApplicationDidFinishLaunching. This was caused by doing a too much work inside of applicationDidFinishLaunching and we exceeded the 20 second time out on slower devices.

To fix this we moved all of our setup code out of ApplicationDidFinishLaunching and moved it into a special secondaryLoadingController. On top of that we moved the setup code inside of that controller to a separate thread.

However, we are still seeing crash logs that say our app failed to launch in time even though the crash log shows a call to [UIApplication _reportAppLaunchFinished]. To me, this indicates that the app has finished launching and we should be free to take as long as we want to run our setup code.  Below is the crash log.

Thanks for any help you can offer.

Incident Identifier: 429360D5-6B02-49BE-9A0F-164DC521BE36
Hardware Model:      iPod2,1
Process:         XYZ [357]
Path:            /var/mobile/Applications/D5038F26-CC5B-48E5-824E-090163B5C0C4/XYZ.app/XYZ
Identifier:      XYZ
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2010-09-28 13:35:25.138 -0700
OS Version:      iPhone OS 4.0 (8A293)
Report Version:  104

Exception Type:  00000020
Exception Codes: 0x8badf00d
Highlighted Thread:  0

Application Specific Information:
com.xyz.xyz failed to launch in time
elapsed total CPU time (seconds): 20.180 (user 15.910, system 4.270), 100% CPU
elapsed application CPU time (seconds): 10.960, 54% CPU

Thread 0:
0   libobjc.A.dylib                   0x3523a50c objc_msgSend + 44
1   CoreFoundation                    0x363bf568 -[__NSArrayM addObject:]
2   XYZ                        0x0000a152 -[Database fetchDrinks:] + 290
3   XYZ                        0x0000677c -[Database getAllDrinks] + 136
4   XYZ                        0x0003a164 -[SecondaryLoadingViewController viewDidLoad] + 208
5   UIKit                             0x323e582c -[UIViewController view]
6   UIKit                             0x323f9628 -[UIViewController viewControllerForRotation]
7   UIKit                             0x323f9574 -[UIViewController _visibleView]
8   UIKit                             0x323f94fc -[UIViewController rotatingContentViewForWindow:]
9   UIKit                             0x3249a514 -[UIClientRotationContext initWithClient:toOrientation:duration:andWindow:]
10  UIKit                             0x32499314 -[UIWindow _setRotatableClient:toOrientation:duration:force:]
11  UIKit                             0x32497d78 -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:]
12  UIKit                             0x32497534 -[UIViewController presentModalViewController:withTransition:]
13  UIKit                             0x324977fc -[UIViewController _tryRecursivelyPresentModalViewController:withTransition:]
14  UIKit                             0x324977c0 -[UIViewController _tryRecursivelyPresentModalViewController:withTransition:]
15  UIKit                             0x32496e00 -[UIViewController presentModalViewController:withTransition:]
16  UIKit                             0x3249699c -[UIViewController presentModalViewController:animated:]
17  XYZ                        0x000044a2 -[HomeViewController viewDidLoad] + 82
18  UIKit                             0x323e582c -[UIViewController view]
19  UIKit                             0x323fd68c -[UIViewController contentScrollView]
20  UIKit                             0x323fd4ac -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:]
21  UIKit                             0x323fd358 -[UINavigationController _layoutViewController:]
22  UIKit                             0x323fccb8 -[UINavigationController _startTransition:fromViewController:toViewController:]
23  UIKit                             0x323fca1c -[UINavigationController _startDeferredTransitionIfNeeded]
24  UIKit                             0x323fc90c -[UINavigationController viewWillLayoutSubviews]
25  UIKit                             0x323fc43c -[UILayoutContainerView layoutSubviews]
26  UIKit                             0x32370ab0 -[UIView(CALayerDelegate) _layoutSublayersOfLayer:]
27  CoreFoundation                    0x363c85ba -[NSObject(NSObject) performSelector:withObject:]
28  QuartzCore                        0x30c8c61c 0x30c82000 + 42524
29  QuartzCore                        0x30c8c2a4 0x30c82000 + 41636
30  QuartzCore                        0x30c8bbb0 0x30c82000 + 39856
31  QuartzCore                        0x30c8b7d8 0x30c82000 + 38872
32  QuartzCore                        0x30c8b684 0x30c82000 + 38532
33  UIKit                             0x323d99d4 -[UIApplication _reportAppLaunchFinished]
34  UIKit                             0x3251d77c -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:]
35  UIKit                             0x323d87b8 -[UIApplication handleEvent:withNewEvent:]
36  UIKit                             0x323d7eb4 -[UIApplication sendEvent:]
37  UIKit                             0x323d77e8 _UIApplicationHandleEvent
38  GraphicsServices                  0x33c4dedc PurpleEventCallback
39  CoreFoundation                    0x364142ac __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__
40  CoreFoundation                    0x364161d6 __CFRunLoopDoSource1
41  CoreFoundation                    0x3641718e __CFRunLoopRun
42  CoreFoundation                    0x363be0bc CFRunLoopRunSpecific
43  CoreFoundation                    0x363bdfca CFRunLoopRunInMode
44  UIKit                             0x32363b18 -[UIApplication _run]
45  UIKit                             0x32361fb8 UIApplicationMain
46  XYZ                        0x00002b20 main + 36
47  XYZ                        0x00002af0 start + 32

UPDATE
I am attempting to run the time consuming import code (only happens on an application update) on a separate thread. I am even updating the GUI using an AlertView with an embedded progress bar so the user knows something is still happening. During our testing process this works fine. Below is the thread code that seems to not be working. The crash log seems to indicate that all work is being done on the main thread.

    if ([database appDidUpdate] == YES) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    dbImportThread = [[NSThread alloc] initWithTarget:self selector:@selector(import) object:nil];
    [dbImportThread start];
    [pool release];

- (void)import {
 //do importing work and update the gui with the progress
}


问:
Trying to validate the form in angular js
i was trying to validate fields of a form in angularjs  but it shows the error-message with out clicking the button. i can't figure out what is the problem in my code. when i click on button i will display the error message but the problem is its shows error message on page load

My code is

HTML

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Layout</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.6.4/angular-messages.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/mediaStyle.css">

<script type="text/javascript">
    $(document).ready(function () {
    $(document).on("click", ".square-radio", function () {
        $(this).toggleClass("square-radio--clicked");
    });
});
</script>
</head>
<body ng-app="myApp">

<div class="container">
    <header id="logoHeader">
        <h1>Logo</h1><span class="fa fa-times" aria-hidden="true"></span>
    </header>
    <div class="emailSupportPanel">
        <div class="mainContainer">
            <h1 class="panel-contentHeader">UK & Ireland Email Support</h1>
            <p>Step1:Tell us your issue > Step2: Tell us your issue<span> > Step3:Tell us your issue</span></p>
        </div>
    </div>
    <div class="mainContainer">
        <h4 class="imaportantNote">Feilds marked with an astrick  <span class="fa fa-asterisk" aria-hidden="true star-icon"></span>  are required</h4>
        <form name ="myform"  ng-submit="sumsung-form.$valid" novalidate ng-init="disabled=false">
        <div class="form-container mb15" ng-class="{true: 'error'}[submitted && sumsung-form.userSubject.$invalid]">
            <label class="form-label">Subject <span class="fa fa-asterisk" aria-hidden="true star-icon"></span></label>
             <input type="text" class="form-input" name="userSubject"
                    ng-model="userSubject" id="subject" ng-required="!disabled" ng-disabled="disabled"
                    ng-required="true"
                    placeholder="Enter Subject" ng-class="{error: showMsgs && myform.name.$error.required}">
            <p ng-show="showMsgs && myform.name.$error.required">This field is required</p>
           <!-- <div ng-messages="sumsung-form.userSubject.$error"
            ng-show="sumsung-form.userSubject.$touched || sumsung-form.$submitted">
                <div ng-message="required" class="state-error"><i class="fa fa-exclamation-circle" aria-hidden="true" ng-show="submitted"></i>This field is required</div>
            </div>-->
        </div>
        <div class="form-container">
            <label class="form-label" ng-class="{ 'state-error': sumsung-form.message.$invalid && (sumsung-form.message.$touched || sumsung-form.$submitted)}">Message <span class="fa fa-asterisk" aria-hidden="true star-icon"></span></label>
             <textarea class="form-input" name="userMessage" ng-model="message" rows="5"
                        id="message" style="border-radius:0;"
                       ng-required="true"
                       placeholder="Enter Message"></textarea>
         <!--   <div ng-messages="sumsung-form.userMessage.$error"
                 ng-show="sumsung-form.userMessage.$touched || sumsung-form.$submitted">
                <div ng-message="required" class="state-error"><i class="fa fa-exclamation-circle" aria-hidden="true"></i>This field is required</div>
                <div ng-message="minlength" class="state-error">Message must be over 100 characters</div>
                <div ng-message="maxlength" class="state-error">Message must not exceed 1000 characters</div>
            </div>-->
             <!-- <p class="error-message">Please enter more then 50 charcters.</p>-->
        </div>

       <div class="footer">
           <button type="submit" ng-click="send('myform')" class="btn">SEND</button>
       </div>
        </form>
</div>

</body>
</html>
</code>```

JS:

```<code>var myApp = angular.module('myApp', ['ngMessages']);
myApp.controller("myController",function($scope){
    $scope.name=undefined;
    $scope.showMsgs = false;
   $scope.send = function(){
       if ($scope[form].$valid) {
           $scope.showMsgs = false;
       } else {
           $scope.showMsgs = true;
       }

   }
});
</code>```

css:

```<code> body{
        font-size:12px;
        color:#333;
        font-family: 'Raleway', sans-serif;
        margin:0;
        padding: 0;
    }
    .mb15{
        margin-bottom: 15px;
    }
    .container{
        position: relative;
        width: 100%;

    }

    #logoHeader{
        width: 100%;
        height:70px;
        line-height: 70px;
        max-height: 70px;
        border-bottom: 1px solid #eee;
        text-align: center;

    }
    #logoHeader>h1{
        margin: 0 !important;
        color: #1428A0;
    }
    #logoHeader>span{
        display: inline;
        position: relative;
        right: -45%;
        top: -60px;
        font-size: x-large;
        color: #ccc;
    }
    .emailSupportPanel{
        position: relative;
        width: 100%;
        height: 80px;
        padding: 12px 0;
        background: rgba(238, 238, 238, 0.5);
        box-sizing: border-box;
    }
    .panel-contentHeader{
        margin: 0;
        font-weight: bold;
    }
    .panel-contentHeader ~p>span{
        color:#1428A0;
    }
    .mainContainer{
        position: relative;
        margin: 0 auto;
        max-width: 80%;
    }
    .mainContainer .imaportantNote{
        font-weight: bolder;
        font-size: 15px;
        color:#777;
    }
    .fa-asterisk:before {
        color: red;
        font-size: 8px;
        vertical-align: super;
    }
    .form-container{
        width: 100%;
        height:auto;
        padding-bottom: 12px;
    }
    .form-label{
        font-weight: bold;
        margin-bottom: 10px;
        font-size: 15px;
        display: block;
        color:#000;
    }
    .form-input{
        display: block;
        width: 96%;
        height: 32px;
        padding: 6px 12px;
        font-size: 14px;
        line-height: 1.42857143;
        color: #555;
        background-color: #fff;
        background-image: none;
        border: 1px solid #ccc;
        border-radius: 0;
        -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
        box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
        -webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;
        -o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
        transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
    }
    textarea.form-input{
        height: auto;
    }
    .error-message{
        display: none;
        width: 96.8%;
        margin-top: 0px;
        background-color: red;
        color: #fff;
        padding: 8px;
    }
    .information-form{
        width: 100%;
        padding-top: 15px;
        position: relative;
        /* height: calc(100vh - 540px); */
        min-height: 344px;

    }
    .information-form>h3{
        font-weight: bolder;
    }
    .left-info,.right-info{
        width: 50%;
        padding-top: 14px;
        box-sizing: border-box;
        float: left;
        padding-right: 33px;
        position: relative;

    }
    .privacy-container{
        width: 100%;
        height:auto;
        position: relative;
    }
    .square-radio {
        border: 1px solid black;
        margin: 2px;
        width: 20px;
        height: 20px;
        position: relative;

    }
    .square-radio--clicked .square-radio--content{
        margin: auto;
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        background-color: black;
        width: 16px;
        height: 16px;
    }
    .square-radio--clicked ~.privacy-text,.square-radio ~.privacy-text{
        display: inline-block;
        width: 100%;
        margin-left: 39px;
        font-size: 14px;
        position: relative;
        top: -21px;
        color:#000;
        font-weight: bold;
    }
    .privacy-text a{
        text-decoration: none;
        color: #1428A0;
    }
    .product-info{
        position: relative;
        width: 100%;
        padding-top: 20px;
        box-sizing: border-box;
    }
   .confirmation-part{
        width:48%;
        display: inline-block;
   }

    .captcha-box{
        width: 100px;
        height: 45px;
        border: 1px solid #333;
        display: inline-block;
        position: relative;
        top: -39px;
        left: 20px;
        margin-right: 19px;
        text-align: center;

    }
    .captcha-box.cross-box{
        width: 50px;
        height: 50px;
        text-align: center;
    }
    .captcha-box .img-cross-icon{
        font-size: xx-large;
        padding: 7px;
    }
    .captcha-box h2{
        color: blue;
        margin-top: 11px;
        letter-spacing: 4px;
        font-weight: bolder;
    }
    .footer{
        width:100%;
        position: relative;
        min-height: 100px;
        text-align: center;
        padding-top: 20px;
    }
    .btn{
        padding: 12px 38px;
        border-radius: 45px;
        background-color: #1428A0;
        color:#fff;
    }
    hr{
        border-color: rgba(204, 204, 204, 0.18);
    }
    p{
        color:#777;
    }
    ::-webkit-input-placeholder { /* Chrome/Opera/Safari */
        color: #bbb;
        padding: 5px;
    }
    .error {
        border-color: red;
        color:red;
    }
</code>```

答:
My initial observation is you are using both ng-submit and ng-click to submit the form details which results in duplicate submission of same form causing this issue. try to use one of them and it should work fine. below is the warning from angularjs team

Warning: Be careful not to cause "double-submission" by using both the ngClick and ngSubmit handlers together. See the form directive documentation for a detailed discussion of when ngSubmit may be triggered.

Here is the link to the documentation for your reference submitting-a-form-and-preventing-the-default-action

Hope it helps:)

ContentLicense: CC BY-SA 3.0

Body:
i was trying to validate fields of a form in angularjs  but it shows the error-message with out clicking the button. i can't figure out what is the problem in my code. when i click on button i will display the error message but the problem is its shows error message on page load

My code is

HTML

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Layout</title>

     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/mediaStyle.css">

Logo

UK & Ireland Email Support

Step1:Tell us your issue > Step2: Tell us your issue > Step3:Tell us your issue

Feilds marked with an astrick    are required

        <form name ="myform"  ng-submit="sumsung-form.$valid" novalidate ng-init="disabled=false">

            Subject
             <input type="text" class="form-input" name="userSubject"
                    ng-model="userSubject" id="subject" ng-required="!disabled" ng-disabled="disabled"
                    ng-required="true"
                    placeholder="Enter Subject" ng-class="{error: showMsgs && myform.name.$error.required}">

This field is required

            Message
             <textarea class="form-input" name="userMessage" ng-model="message" rows="5"
                        id="message" style="border-radius:0;"
                       ng-required="true"
                       placeholder="Enter Message"></textarea>

           <button type="submit" ng-click="send('myform')" class="btn">SEND</button>

        </form>

JS:

var myApp = angular.module('myApp', ['ngMessages']);
myApp.controller("myController",function($scope){
    $scope.name=undefined;
    $scope.showMsgs = false;
   $scope.send = function(){
       if ($scope[form].$valid) {
           $scope.showMsgs = false;
       } else {
           $scope.showMsgs = true;
       }

   }
});

css:

 body{
        font-size:12px;
        color:#333;
        font-family: 'Raleway', sans-serif;
        margin:0;
        padding: 0;
    }
    .mb15{
        margin-bottom: 15px;
    }
    .container{
        position: relative;
        width: 100%;

    }

    #logoHeader{
        width: 100%;
        height:70px;
        line-height: 70px;
        max-height: 70px;
        border-bottom: 1px solid #eee;
        text-align: center;

    }
    #logoHeader>h1{
        margin: 0 !important;
        color: #1428A0;
    }
    #logoHeader>span{
        display: inline;
        position: relative;
        right: -45%;
        top: -60px;
        font-size: x-large;
        color: #ccc;
    }
    .emailSupportPanel{
        position: relative;
        width: 100%;
        height: 80px;
        padding: 12px 0;
        background: rgba(238, 238, 238, 0.5);
        box-sizing: border-box;
    }
    .panel-contentHeader{
        margin: 0;
        font-weight: bold;
    }
    .panel-contentHeader ~p>span{
        color:#1428A0;
    }
    .mainContainer{
        position: relative;
        margin: 0 auto;
        max-width: 80%;
    }
    .mainContainer .imaportantNote{
        font-weight: bolder;
        font-size: 15px;
        color:#777;
    }
    .fa-asterisk:before {
        color: red;
        font-size: 8px;
        vertical-align: super;
    }
    .form-container{
        width: 100%;
        height:auto;
        padding-bottom: 12px;
    }
    .form-label{
        font-weight: bold;
        margin-bottom: 10px;
        font-size: 15px;
        display: block;
        color:#000;
    }
    .form-input{
        display: block;
        width: 96%;
        height: 32px;
        padding: 6px 12px;
        font-size: 14px;
        line-height: 1.42857143;
        color: #555;
        background-color: #fff;
        background-image: none;
        border: 1px solid #ccc;
        border-radius: 0;
        -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
        box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
        -webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;
        -o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
        transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
    }
    textarea.form-input{
        height: auto;
    }
    .error-message{
        display: none;
        width: 96.8%;
        margin-top: 0px;
        background-color: red;
        color: #fff;
        padding: 8px;
    }
    .information-form{
        width: 100%;
        padding-top: 15px;
        position: relative;
        /* height: calc(100vh - 540px); */
        min-height: 344px;

    }
    .information-form>h3{
        font-weight: bolder;
    }
    .left-info,.right-info{
        width: 50%;
        padding-top: 14px;
        box-sizing: border-box;
        float: left;
        padding-right: 33px;
        position: relative;

    }
    .privacy-container{
        width: 100%;
        height:auto;
        position: relative;
    }
    .square-radio {
        border: 1px solid black;
        margin: 2px;
        width: 20px;
        height: 20px;
        position: relative;

    }
    .square-radio--clicked .square-radio--content{
        margin: auto;
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        background-color: black;
        width: 16px;
        height: 16px;
    }
    .square-radio--clicked ~.privacy-text,.square-radio ~.privacy-text{
        display: inline-block;
        width: 100%;
        margin-left: 39px;
        font-size: 14px;
        position: relative;
        top: -21px;
        color:#000;
        font-weight: bold;
    }
    .privacy-text a{
        text-decoration: none;
        color: #1428A0;
    }
    .product-info{
        position: relative;
        width: 100%;
        padding-top: 20px;
        box-sizing: border-box;
    }
   .confirmation-part{
        width:48%;
        display: inline-block;
   }

    .captcha-box{
        width: 100px;
        height: 45px;
        border: 1px solid #333;
        display: inline-block;
        position: relative;
        top: -39px;
        left: 20px;
        margin-right: 19px;
        text-align: center;

    }
    .captcha-box.cross-box{
        width: 50px;
        height: 50px;
        text-align: center;
    }
    .captcha-box .img-cross-icon{
        font-size: xx-large;
        padding: 7px;
    }
    .captcha-box h2{
        color: blue;
        margin-top: 11px;
        letter-spacing: 4px;
        font-weight: bolder;
    }
    .footer{
        width:100%;
        position: relative;
        min-height: 100px;
        text-align: center;
        padding-top: 20px;
    }
    .btn{
        padding: 12px 38px;
        border-radius: 45px;
        background-color: #1428A0;
        color:#fff;
    }
    hr{
        border-color: rgba(204, 204, 204, 0.18);
    }
    p{
        color:#777;
    }
    ::-webkit-input-placeholder { /* Chrome/Opera/Safari */
        color: #bbb;
        padding: 5px;
    }
    .error {
        border-color: red;
        color:red;
    }


问:
Rails Hours:Minutes Dropdowns
I'm new to Rails and I want to create a simple time calculator:
User is presented with 2 dropdown menus that capture user inputs “hour” and “minutes”, so I can get time like 7:15. Then after some math on this time the user is given several “hour:minute” time options. What is the best way to build this logic and what helper to use? Should I create models for hours and minutes?  </p>

答: You can use time_select to get hours and minutes from user.</p>

Title: Rails Hours:Minutes Dropdowns


问:
Implement JQuery UI autocomplete feature in CKeditor
I am trying to implement the JQuery UI autocomplete feature in the CKEditor, but it is not working. I saw some examples and solution where if the user types "#" the drop-down list shows up with options. What I want is the user to get autocomplete suggestions on the fly like in text editors while typing, from a list of words. I want something like the code under but in CKeditor, rather than a textarea.</p>

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Autocomplete - Multiple values</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script src="https://cdn.ckeditor.com/4.6.2/standard/ckeditor.js"></script>
</head>
<body>

<div class="ui-widget">
    <!--<input id="tags" size="50">-->
    <textarea id="tags"></textarea>
</div>
<script>
//    CKEDITOR.replace( 'tags' );
    $( function() {
        var availableTags = [
            "ActionScript",
            "AppleScript",
            "Asp",
            "BASIC",
            "C",
            "C++",
            "Clojure",
            "COBOL",
            "ColdFusion",
            "Erlang",
            "Fortran",
            "Groovy",
            "Haskell",
            "Java",
            "JavaScript",
            "Lisp",
            "Perl",
            "PHP",
            "Python",
            "Ruby",
            "Scala",
            "Scheme"
        ];
        function split( val ) {
            return val.split( / \s*/ );
        }
        function extractLast( term ) {
            return split( term ).pop();
        }

        $( "#tags" )
        // don't navigate away from the field on tab when selecting an item
            .on( "keydown", function( event ) {
                if ( event.keyCode === $.ui.keyCode.TAB &&
                    $( this ).autocomplete( "instance" ).menu.active ) {
                    event.preventDefault();
                }
            })
            .autocomplete({
                minLength: 0,
                source: function( request, response ) {
                    // delegate back to autocomplete, but extract the last term
                    response( $.ui.autocomplete.filter(
                        availableTags, extractLast( request.term ) ) );
                },
                focus: function() {
                    // prevent value inserted on focus
                    return false;
                },
                select: function( event, ui ) {
                    var terms = split( this.value );
                    // remove the current input
                    terms.pop();
                    // add the selected item
                    terms.push( ui.item.value );
                    // add placeholder to get the comma-and-space at the end
                    terms.push( "" );
                    this.value = terms.join( " " );
                    return false;
                }
            });
    } );
</script>

</body>
</html>
</code>```

答: If you aren't limited by the autocomplete library, At.js was written to work with a specific tag - using @ for user references, or : for emoji. There is also a wiki page on how to integrate it with CKEditor.

Body:
I am trying to implement the JQuery UI autocomplete feature in the CKEditor, but it is not working. I saw some examples and solution where if the user types "#" the drop-down list shows up with options. What I want is the user to get autocomplete suggestions on the fly like in text editors while typing, from a list of words. I want something like the code under but in CKeditor, rather than a textarea.

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Autocomplete - Multiple values</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

    <textarea id="tags"></textarea>


问:
How to change the header color of csv in java using ICsvBeanWriter
I am using ICsvBeanWriter to generate the CSV file over the REST API, my code looks like

```<code>// uses the Super CSV API to generate CSV data from the model data
    ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(),
    CsvPreference.STANDARD_PREFERENCE);

    String[] header = { "Title", "Description", "Author", "Publisher",
                    "isbn", "PublishedDate", "Price" };

    csvWriter.writeHeader(header);
</code>```

I want to set the header color to some different color rather than the default one. Please tell me how i can do this?

答: As per definition, CSV is comma-separated values stored as plain text. It's a plain text file after all. So no, there is no way of adding colour via Java nor via any editor.</p>

Body:
I am using ICsvBeanWriter to generate the CSV file over the REST API, my code looks like

// uses the Super CSV API to generate CSV data from the model data
    ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(),
    CsvPreference.STANDARD_PREFERENCE);

    String[] header = { "Title", "Description", "Author", "Publisher",
                    "isbn", "PublishedDate", "Price" };

    csvWriter.writeHeader(header);

I want to set the header color to some different color rather than the default one. Please tell me how i can do this?


问:
Display all results queried on PostgreSQL where the JOINING value is missing
I have two tables on PostgreSQL, namely: employees and employers.
There is data in each of these tables.

```<code>Columns in employees: employee_id, employee_name, employer_id.

Columns in employers: employer_id, employer_name.
</code>```

I want to display all employee_name's that don't have an associating employer_name.

I used the below query:

```<code>    SELECT DISTINCT a.employee_name, b.employer_name
    FROM employees a
    NATURAL JOIN employers b
    WHERE a.employee_name LIKE 'Jack';
</code>```

NB!
I have also tried adding in the below to my query:
COALESCE(b.employer_name, '') = ''

Problem:
If there is no record in the employer table containing the associating employee_id value, the query returns nothing all. I am assuming this is because there is nothing for the two tables to join on?... But I would like to at least find all employees that don't have an employer. I would ideally like the employer_name value in my result to either return: blank/''/NULL.

Your assistance is greatly appreciated.

答:
Your table name employees table is a little odd, IMO. There is a design 'rule of thumb' that says a table models either an entity or the relationship between entities but not both. To demonstrate this oddness, consider the relational operation is

```<code>employees MINUS employers
</code>```

...which suggests something is off.

Another symptom of this design problem is that the employer_id in the employees table must have some kind of placeholder to represent the predicate employee has no employer, possibly a null (and nulls are to be avoided, IMO).

I suggest you fix this design by introducing a third table to model the relationship between an employee and their employer. Herein lies another design problem: shouldn't this new table be named employees? In other words, isn't the very definition of an employee a person who has an employer?

Consider this design instead:

```<code>People: person_id, person_name
Employers: employer_id, employer_name
Employees: employer_id, person_id
</code>```

To find the names of people who are not employees in pseudo-relational notation:

```<code>People MINUS Employees { person_name }
</code>```

SQL is quite a bit more verbose:

```<code>SELECT DISTINCT person_name
  FROM People
       NATURAL JOIN
       ( SELECT person_id FROM People
         EXCEPT
         SELECT person_id FROM Employees ) t;
</code>```

Note your original query needlessly uses range variables a and b. One of the benefits of NATURAL JOIN is the elminiation of duplicate column names. Range variables with NATURAL JOIN always looks odd to me!

Body:
I have two tables on PostgreSQL, namely: employees and employers.
There is data in each of these tables.

Columns in employees: employee_id, employee_name, employer_id.

Columns in employers: employer_id, employer_name.

I want to display all employee_name's that don't have an associating employer_name.

I used the below query:

    SELECT DISTINCT a.employee_name, b.employer_name
    FROM employees a
    NATURAL JOIN employers b
    WHERE a.employee_name LIKE 'Jack';

NB!
I have also tried adding in the below to my query:
COALESCE(b.employer_name, '') = ''

Problem:
If there is no record in the employer table containing the associating employee_id value, the query returns nothing all. I am assuming this is because there is nothing for the two tables to join on?... But I would like to at least find all employees that don't have an employer. I would ideally like the employer_name value in my result to either return: blank/''/NULL.

Your assistance is greatly appreciated.

Body:
Your table name employees table is a little odd, IMO. There is a design 'rule of thumb' that says a table models either an entity or the relationship between entities but not both. To demonstrate this oddness, consider the relational operation is

employees MINUS employers

...which suggests something is off.

Another symptom of this design problem is that the employer_id in the employees table must have some kind of placeholder to represent the predicate employee has no employer, possibly a null (and nulls are to be avoided, IMO).

I suggest you fix this design by introducing a third table to model the relationship between an employee and their employer. Herein lies another design problem: shouldn't this new table be named employees? In other words, isn't the very definition of an employee a person who has an employer?

Consider this design instead:

People: person_id, person_name
Employers: employer_id, employer_name
Employees: employer_id, person_id

To find the names of people who are not employees in pseudo-relational notation:

People MINUS Employees { person_name }

SQL is quite a bit more verbose:

SELECT DISTINCT person_name
  FROM People
       NATURAL JOIN
       ( SELECT person_id FROM People
         EXCEPT
         SELECT person_id FROM Employees ) t;

Note your original query needlessly uses range variables a and b. One of the benefits of NATURAL JOIN is the elminiation of duplicate column names. Range variables with NATURAL JOIN always looks odd to me!


问:
Validating POST data class
This is an extension of a question I asked earlier that was deemed to be unsafe practise, due to the use of eval(). So I went for another approach but I have run into a problem. I do not know how to convert it to a class. My attempt ends with an error when I try to use call_user_func_array. it can't find the function in the class. Can you give me some hint so I get going? Thanks!

The error message I get when I try to run my code is Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'testlength' not found or invalid function name but on all validation methods. This is what I don't understand. This is what I want help to understand why it does not work.

```<code>class ruleValidator
{

    protected $postData = array();
    protected $ruleSet  = array();
    var $exceptions = 'Å,Ä,Þ,å,ä,þ,Ø,Ö,Ð,ø,ö,ð,Æ,Ü,æ,ü,á,é,í,ñ,ó,ú,ü,Á,É,Í,Ñ,Ó,Ê,Ú,Ü,ß';

    function __construct(){
        $this->exceptions = explode(',',$exceptions);
    }

    function testlength($string,$threshold)
    {
        return strlen($string)<$threshold?
            'Your %s is too short.': // TRUE
            '';                      // FALSE
    }

    function testnumeric($string,$offset,$length,$switch=true)
    {
        if(is_numeric(substr($string,$offset,$length))===$switch)
        {
            return $switch?
                'Your %s has to begin with a character.': // Truely TRUE
                'Your %s is containing non numeric characters. Please enter only digits.'; // Falsely TRUE
        }
    }

    function testemail($string)
    {
        return filter_var($string, FILTER_VALIDATE_EMAIL)?
            '':                                   // TRUE
            'Your email is not in a valid form.'; // FALSE
    }

    function testpattern($string,$pattern='/^[0-9]{8,10}$/')
    {
        return preg_match($pattern, $string)?
            '': // TRUE
            'Your %s is entered incorrect. Please use the correct format when entering data.'; // FALSE
    }

    function testequalto($string1,$string2)
    {
        return $string1==$string2?
            '':                                       // TRUE
            'Your %s fields do not match eachother.'; // FALSE
    }

    function testchecked($bool)
    {
        return $bool===true?
            '':                                               // TRUE
            'You are required to check this %s to continue.'; // FALSE
    }

    function testspecchar($string,$excludes=array())
    {
        if(is_array($excludes)&&!empty($excludes))
        {
            foreach($excludes as $exclude)
            {
                $string=str_replace($exclude,'',$string);
            }
        }

        if(preg_match('/[^a-z0-9 ]+/i',$string))
        {
            return 'Your %s contains illegal characters.'; // TRUE
        }

        return;                                            // FALSE

    }

}
</code>```

This is an array with how the POST data is recieved in the validator and the rules I use for the different fields in the form.

```<code>    $exceptions = explode(',','Å,Ä,Þ,å,ä,þ,Ø,Ö,Ð,ø,ö,ð,Æ,Ü,æ,ü,á,é,í,ñ,ó,ú,ü,Á,É,Í,Ñ,Ó,Ê,Ú,Ü,ß');
    $postData = array
    (
        'name'             => 'Mikael',
        'familyname'       => 'Eriksson`',
        'username'         => 'Mik',
        'password'         => 'testtest',
        'password-confirm' => 'testtesty',
        'email'            => 'try.to@guess.it,se',
        'phone'            => '0000000000a',
        'policy'           => 0
    );
    $ruleSet = array
    (
        'name'=>array
        (
            'testlength'=>2,
            'testnumeric'=>array(0,1),
            'testspecchar'=>array($exceptions)
        ),
        'familyname'=>array
        (
            'testlength'=>2,
            'testnumeric'=>array(0,1),
            'testspecchar'=>array($exceptions)
        ),
        'username'=>array
        (
            'testlength'=>4,
            'testnumeric'=>array(0,1),
            'testspecchar'=>array()
        ),
        'email'=>array
        (
            'testemail'=>array()
        ),
        'phone'=>array
        (
            'testnumeric'=>array(0,strlen($postData['phone']),false),
            'testpattern'=>'/^[0-9]{8,10}$/'
        ),
        'password'=>array
        (
            'testlength'=>8
        ),
        'password-confirm'=>array
        (
            'testequalto'=>$postData['password-confirm']
        ),
        'policy'=>array
        (
            'testchecked'=>array()
        )
    );
</code>```

Here is how I validated the data up until now. It works, but I want to make this to a class to streamline the code in my project.

```<code>    foreach($postData as $key => $value)
    {
        if(!array_key_exists($key,$ruleSet))
        {
            $errors[] = "The field `$key` is not part of the form. Only send actual form data.";
            break;
        }

        $slice = array($key=>$ruleSet[$key]);
        foreach($slice as $rules => $rule)
        {
            foreach($rule as $rls => $r)
            {
                $r = array_merge((array)$value,(array)$r);
                $errors[] = sprintf(call_user_func_array($rls,$r),$key);
            }
        }
    }
    if(count($errors)>0) return implode(';;',array_filter($errors,'strlen'));
</code>```

答:
Thanks @Deadooshka for providing me with the solution.</p>

```<code>call_user_func_array("ruleValidator::$rls", $r)
</code>```

Title: Validating POST data class

Body:
This is an extension of a question I asked earlier that was deemed to be unsafe practise, due to the use of eval(). So I went for another approach but I have run into a problem. I do not know how to convert it to a class. My attempt ends with an error when I try to use call_user_func_array. it can't find the function in the class. Can you give me some hint so I get going? Thanks!

The error message I get when I try to run my code is Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'testlength' not found or invalid function name but on all validation methods. This is what I don't understand. This is what I want help to understand why it does not work.

class ruleValidator
{

    protected $postData = array();
    protected $ruleSet  = array();
    var $exceptions = 'Å,Ä,Þ,å,ä,þ,Ø,Ö,Ð,ø,ö,ð,Æ,Ü,æ,ü,á,é,í,ñ,ó,ú,ü,Á,É,Í,Ñ,Ó,Ê,Ú,Ü,ß';

    function __construct(){
        $this->exceptions = explode(',',$exceptions);
    }

    function testlength($string,$threshold)
    {
        return strlen($string)<$threshold?
            'Your %s is too short.': // TRUE
            '';                      // FALSE
    }

    function testnumeric($string,$offset,$length,$switch=true)
    {
        if(is_numeric(substr($string,$offset,$length))===$switch)
        {
            return $switch?
                'Your %s has to begin with a character.': // Truely TRUE
                'Your %s is containing non numeric characters. Please enter only digits.'; // Falsely TRUE
        }
    }

    function testemail($string)
    {
        return filter_var($string, FILTER_VALIDATE_EMAIL)?
            '':                                   // TRUE
            'Your email is not in a valid form.'; // FALSE
    }

    function testpattern($string,$pattern='/^[0-9]{8,10}$/')
    {
        return preg_match($pattern, $string)?
            '': // TRUE
            'Your %s is entered incorrect. Please use the correct format when entering data.'; // FALSE
    }

    function testequalto($string1,$string2)
    {
        return $string1==$string2?
            '':                                       // TRUE
            'Your %s fields do not match eachother.'; // FALSE
    }

    function testchecked($bool)
    {
        return $bool===true?
            '':                                               // TRUE
            'You are required to check this %s to continue.'; // FALSE
    }

    function testspecchar($string,$excludes=array())
    {
        if(is_array($excludes)&&!empty($excludes))
        {
            foreach($excludes as $exclude)
            {
                $string=str_replace($exclude,'',$string);
            }
        }

        if(preg_match('/[^a-z0-9 ]+/i',$string))
        {
            return 'Your %s contains illegal characters.'; // TRUE
        }

        return;                                            // FALSE

    }

}

This is an array with how the POST data is recieved in the validator and the rules I use for the different fields in the form.

    $exceptions = explode(',','Å,Ä,Þ,å,ä,þ,Ø,Ö,Ð,ø,ö,ð,Æ,Ü,æ,ü,á,é,í,ñ,ó,ú,ü,Á,É,Í,Ñ,Ó,Ê,Ú,Ü,ß');
    $postData = array
    (
        'name'             => 'Mikael',
        'familyname'       => 'Eriksson`',
        'username'         => 'Mik',
        'password'         => 'testtest',
        'password-confirm' => 'testtesty',
        'email'            => 'try.to@guess.it,se',
        'phone'            => '0000000000a',
        'policy'           => 0
    );
    $ruleSet = array
    (
        'name'=>array
        (
            'testlength'=>2,
            'testnumeric'=>array(0,1),
            'testspecchar'=>array($exceptions)
        ),
        'familyname'=>array
        (
            'testlength'=>2,
            'testnumeric'=>array(0,1),
            'testspecchar'=>array($exceptions)
        ),
        'username'=>array
        (
            'testlength'=>4,
            'testnumeric'=>array(0,1),
            'testspecchar'=>array()
        ),
        'email'=>array
        (
            'testemail'=>array()
        ),
        'phone'=>array
        (
            'testnumeric'=>array(0,strlen($postData['phone']),false),
            'testpattern'=>'/^[0-9]{8,10}$/'
        ),
        'password'=>array
        (
            'testlength'=>8
        ),
        'password-confirm'=>array
        (
            'testequalto'=>$postData['password-confirm']
        ),
        'policy'=>array
        (
            'testchecked'=>array()
        )
    );

Here is how I validated the data up until now. It works, but I want to make this to a class to streamline the code in my project.

    foreach($postData as $key => $value)
    {
        if(!array_key_exists($key,$ruleSet))
        {
            $errors[] = "The field `$key` is not part of the form. Only send actual form data.";
            break;
        }

        $slice = array($key=>$ruleSet[$key]);
        foreach($slice as $rules => $rule)
        {
            foreach($rule as $rls => $r)
            {
                $r = array_merge((array)$value,(array)$r);
                $errors[] = sprintf(call_user_func_array($rls,$r),$key);
            }
        }
    }
    if(count($errors)>0) return implode(';;',array_filter($errors,'strlen'));

Body:
Thanks @Deadooshka for providing me with the solution.

call_user_func_array("ruleValidator::$rls", $r)


问:
Right way to check if an object's prototype has given it a method
If an object prototype contains a specific method, I want to override it on the object/instance with a dummy. And I want to do this recursively, for all properties, objects and arrays inside this object.

What is the right way to check if an object's prototype has given it a method?

```<code>if('myInterestedMethod' in obj1){
   if(!obj1.hasOwnProperty('myInterestedMethod'){
      console.log('Method is from its prototype');
   }
}
</code>```

答:
Iterate the properties by doing for-in and check if the value of each key is a function

```<code> for ( var prop in obj1 )
 {
   if( !obj1.hasOwnProperty( prop ) && typeof obj1[ prop ] == "function" )
   {
      console.log( prop, 'Method is from its prototype');
   }
 }
</code>```

Body:
If an object prototype contains a specific method, I want to override it on the object/instance with a dummy. And I want to do this recursively, for all properties, objects and arrays inside this object.

What is the right way to check if an object's prototype has given it a method?

if('myInterestedMethod' in obj1){
   if(!obj1.hasOwnProperty('myInterestedMethod'){
      console.log('Method is from its prototype');
   }
}

Body:
Iterate the properties by doing for-in and check if the value of each key is a function

 for ( var prop in obj1 )
 {
   if( !obj1.hasOwnProperty( prop ) && typeof obj1[ prop ] == "function" )
   {
      console.log( prop, 'Method is from its prototype');
   }
 }


问:
Validate user per every request and response in spring
Since I am new to Spring and i have an issue with user service. I have admin panel and customer blog. When the Customer is logged into browser, the admin has been changed the status to Active from InActive in Table of Customer. But the user session is active. So that he can able to do process after the status is changed.

I need one common method that should be in common place. This method should be access the table and validate the user per every request. I have one controller and that should invoke the common method. Because I cannot edit code to every class. In JSP & Servlet I have handled this using doFilter. How to achieve this in Spring..

AppInitializer.java

```<code>import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { AppConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return null;
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
    registration.setMultipartConfig(getMultipartConfigElement());
}

private MultipartConfigElement getMultipartConfigElement() {
    MultipartConfigElement multipartConfigElement = new MultipartConfigElement( LOCATION, MAX_FILE_SIZE, MAX_REQUEST_SIZE, FILE_SIZE_THRESHOLD);
    return multipartConfigElement;
}

private static final String LOCATION = "C:/temp/"; // Temporary location where files will be stored

private static final long MAX_FILE_SIZE = 5242880; // 5MB : Max file size.
                                                    // Beyond that size spring will throw exception.
private static final long MAX_REQUEST_SIZE = 20971520; // 20MB : Total request size containing Multi part.

private static final int FILE_SIZE_THRESHOLD = 0;

}
</code>```

AppConfig.java

```<code>import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { AppConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return null;
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
    registration.setMultipartConfig(getMultipartConfigElement());
}

private MultipartConfigElement getMultipartConfigElement() {
    MultipartConfigElement multipartConfigElement = new MultipartConfigElement( LOCATION, MAX_FILE_SIZE, MAX_REQUEST_SIZE, FILE_SIZE_THRESHOLD);
    return multipartConfigElement;
}

private static final String LOCATION = "C:/temp/"; // Temporary location where files will be stored

private static final long MAX_FILE_SIZE = 5242880; // 5MB : Max file size.
                                                    // Beyond that size spring will throw exception.
private static final long MAX_REQUEST_SIZE = 20971520; // 20MB : Total request size containing Multi part.

private static final int FILE_SIZE_THRESHOLD = 0;

}
</code>```

HibernateConfiguration.java

```<code>import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.ppts.configuration" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {

@Autowired
private Environment environment;

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "com.ppts.model" });
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
 }

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
    dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
    dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
    return dataSource;
}

private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
    properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
    properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
    return properties;
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
   HibernateTransactionManager txManager = new HibernateTransactionManager();
   txManager.setSessionFactory(s);
   return txManager;
}
}
</code>```

AppController.java

```<code>package com.sample.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.sample.handler.FileHandler;
import com.sample.model.Address;
import com.sample.model.Employee;
import com.sample.model.EmployeeDocument;
import com.sample.model.EmployeeSalary;
import com.sample.model.FileBucket;
import com.sample.model.User;
import com.sample.model.UserProfile;
import com.sample.service.EmployeeDocumentService;
import com.sample.service.EmployeeSalaryService;
import com.sample.service.EmployeeService;
import com.sample.service.UserProfileService;
import com.sample.service.UserService;
import com.sample.validators.FileValidator;

@Controller
@RequestMapping("/")
@SessionAttributes("roles")
public class AppController {

@Autowired
UserService userService;

@Autowired
EmployeeService employeeService;

@Autowired
EmployeeSalaryService employeeSalaryService;

@Autowired
UserProfileService userProfileService;

@Autowired
EmployeeDocumentService employeeDocumentService;

@Autowired
FileValidator fileValidator;

@InitBinder("fileBucket")
protected void initBinderFileBucket(WebDataBinder binder) {
    binder.setValidator(fileValidator);
}

@Autowired
MessageSource messageSource;

@Autowired
PersistentTokenBasedRememberMeServices persistentTokenBasedRememberMeServices;

@Autowired
AuthenticationTrustResolver authenticationTrustResolver;

@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
public String adminPage(ModelMap model) {
    model.addAttribute("home",true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "home";
}

@RequestMapping(value = { "/userList" }, method = RequestMethod.GET)
public String listUsers(ModelMap model) {
    List<User> users = userService.findAllUsers();
    model.addAttribute("users", users);
    model.addAttribute("loggedinuser", getPrincipal());
    return "userslist";
}

@RequestMapping(value = { "/newuser" }, method = RequestMethod.GET)
public String newUser(ModelMap model) {
    User user = new User();
    model.addAttribute("user", user);
    model.addAttribute("edit", false);
    model.addAttribute("loggedinuser", getPrincipal());
    return "registration";
}

@RequestMapping(value = { "/newuser" }, method = RequestMethod.POST)
public String saveUser(@Valid User user, BindingResult result,
        ModelMap model) {
    if (result.hasErrors()) {
        return "registration";
    }
    if(!userService.isUserSSOUnique(user.getId(), user.getSsoId())){
        FieldError ssoError =new FieldError("user","ssoId",messageSource.getMessage("non.unique.ssoId", new String[]{user.getSsoId()}, Locale.getDefault()));
        result.addError(ssoError);
        return "registration";
    }
    userService.saveUser(user);
    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " registered successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

@RequestMapping(value = { "/edit-user-{ssoId}" }, method = RequestMethod.GET)
public String editUser(@PathVariable String ssoId, ModelMap model) {
    User user = userService.findBySSO(ssoId);
    model.addAttribute("user", user);
    model.addAttribute("edit", true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "registration";
}

@RequestMapping(value = { "/edit-user-{ssoId}" }, method = RequestMethod.POST)
public String updateUser(@Valid User user, BindingResult result,
        ModelMap model, @PathVariable String ssoId) {
    if (result.hasErrors()) {
        return "registration";
    }
    userService.updateUser(user);
    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " updated successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

//Update User and Employee By Id
@RequestMapping(value = { "/getUserById" }, method = RequestMethod.GET)
public String getUserSSOId(ModelMap model) {
    User user = new User();
    model.addAttribute("user", user);
    model.addAttribute("edit", true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "userview";
}

@RequestMapping(value = { "/updateByUserId" }, method = RequestMethod.GET)
public String getByUserId( @ModelAttribute User userDetails,ModelMap model,BindingResult result) {
    User user =userService.findBySSO(userDetails.getSsoId());
    if(user!=null){
        model.addAttribute("user", user);
        model.addAttribute("edit", true);
        model.addAttribute("loggedinuser", getPrincipal());
        return "registration";
    }else{
        FieldError referenceIdError =new FieldError("user","ssoId",messageSource.getMessage("non.empty.userid.notexist", new String[]{userDetails.getSsoId()}, Locale.getDefault()));
        result.addError(referenceIdError);
        model.addAttribute("loggedinuser", getPrincipal());
        return "userview";
    }
}

@RequestMapping(value = { "/updateByUserId" }, method = RequestMethod.POST)
public String updateUserById(@Valid User user, BindingResult result,
        ModelMap model) {
    if (result.hasErrors()) {
        return "registration";
    }
    userService.updateUser(user);
    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " updated successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

@RequestMapping(value = { "/deleteByUserId" }, method = RequestMethod.GET)
public String deleteUserById(ModelMap model) {
    User user = new User();
    model.addAttribute("user", user);
    model.addAttribute("delete", true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "userview";
}

@RequestMapping(value = { "/deleteUserById" }, method = RequestMethod.GET)
public String deleteByuserId( @ModelAttribute User userDetails,ModelMap model,BindingResult result) {
    User user=userService.findBySSO(userDetails.getSsoId());
    if(user!=null){
        userService.deleteUserBySSO(userDetails.getSsoId());
        model.addAttribute("loggedinuser", getPrincipal());
        model.addAttribute("employeeSuccess", "Employee " + user.getFirstName() + " deleted successfully");
        return "registrationsuccess";
    }else{
        FieldError referenceIdError =new FieldError("employee","employeeReferenceId",messageSource.getMessage("non.empty.userid.notexist", new String[]{userDetails.getSsoId()}, Locale.getDefault()));
        model.addAttribute("loggedinuser", getPrincipal());
        result.addError(referenceIdError);
        return "userview";
    }

}
}
</code>```

答:
You can do that also in Filter. You just have to annotate it with @Component and voila. It becomes a Spring bean. Like this:

```<code>@Component
public class UserFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        User user = (User)request.getAttribute("user");
        // Do whatever you want with your user
    }

    @Override
    public void destroy() {

    }
}
</code>```

Body:
Since I am new to Spring and i have an issue with user service. I have admin panel and customer blog. When the Customer is logged into browser, the admin has been changed the status to Active from InActive in Table of Customer. But the user session is active. So that he can able to do process after the status is changed.

I need one common method that should be in common place. This method should be access the table and validate the user per every request. I have one controller and that should invoke the common method. Because I cannot edit code to every class. In JSP & Servlet I have handled this using doFilter. How to achieve this in Spring..

AppInitializer.java

import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { AppConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return null;
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
    registration.setMultipartConfig(getMultipartConfigElement());
}

private MultipartConfigElement getMultipartConfigElement() {
    MultipartConfigElement multipartConfigElement = new MultipartConfigElement( LOCATION, MAX_FILE_SIZE, MAX_REQUEST_SIZE, FILE_SIZE_THRESHOLD);
    return multipartConfigElement;
}

private static final String LOCATION = "C:/temp/"; // Temporary location where files will be stored

private static final long MAX_FILE_SIZE = 5242880; // 5MB : Max file size.
                                                    // Beyond that size spring will throw exception.
private static final long MAX_REQUEST_SIZE = 20971520; // 20MB : Total request size containing Multi part.

private static final int FILE_SIZE_THRESHOLD = 0;

}

AppConfig.java

import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { AppConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return null;
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
    registration.setMultipartConfig(getMultipartConfigElement());
}

private MultipartConfigElement getMultipartConfigElement() {
    MultipartConfigElement multipartConfigElement = new MultipartConfigElement( LOCATION, MAX_FILE_SIZE, MAX_REQUEST_SIZE, FILE_SIZE_THRESHOLD);
    return multipartConfigElement;
}

private static final String LOCATION = "C:/temp/"; // Temporary location where files will be stored

private static final long MAX_FILE_SIZE = 5242880; // 5MB : Max file size.
                                                    // Beyond that size spring will throw exception.
private static final long MAX_REQUEST_SIZE = 20971520; // 20MB : Total request size containing Multi part.

private static final int FILE_SIZE_THRESHOLD = 0;

}

HibernateConfiguration.java

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.ppts.configuration" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {

@Autowired
private Environment environment;

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "com.ppts.model" });
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
 }

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
    dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
    dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
    return dataSource;
}

private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
    properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
    properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
    return properties;
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
   HibernateTransactionManager txManager = new HibernateTransactionManager();
   txManager.setSessionFactory(s);
   return txManager;
}
}

AppController.java

package com.sample.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.sample.handler.FileHandler;
import com.sample.model.Address;
import com.sample.model.Employee;
import com.sample.model.EmployeeDocument;
import com.sample.model.EmployeeSalary;
import com.sample.model.FileBucket;
import com.sample.model.User;
import com.sample.model.UserProfile;
import com.sample.service.EmployeeDocumentService;
import com.sample.service.EmployeeSalaryService;
import com.sample.service.EmployeeService;
import com.sample.service.UserProfileService;
import com.sample.service.UserService;
import com.sample.validators.FileValidator;

@Controller
@RequestMapping("/")
@SessionAttributes("roles")
public class AppController {

@Autowired
UserService userService;

@Autowired
EmployeeService employeeService;

@Autowired
EmployeeSalaryService employeeSalaryService;

@Autowired
UserProfileService userProfileService;

@Autowired
EmployeeDocumentService employeeDocumentService;

@Autowired
FileValidator fileValidator;

@InitBinder("fileBucket")
protected void initBinderFileBucket(WebDataBinder binder) {
    binder.setValidator(fileValidator);
}

@Autowired
MessageSource messageSource;

@Autowired
PersistentTokenBasedRememberMeServices persistentTokenBasedRememberMeServices;

@Autowired
AuthenticationTrustResolver authenticationTrustResolver;

@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
public String adminPage(ModelMap model) {
    model.addAttribute("home",true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "home";
}

@RequestMapping(value = { "/userList" }, method = RequestMethod.GET)
public String listUsers(ModelMap model) {
    List<User> users = userService.findAllUsers();
    model.addAttribute("users", users);
    model.addAttribute("loggedinuser", getPrincipal());
    return "userslist";
}

@RequestMapping(value = { "/newuser" }, method = RequestMethod.GET)
public String newUser(ModelMap model) {
    User user = new User();
    model.addAttribute("user", user);
    model.addAttribute("edit", false);
    model.addAttribute("loggedinuser", getPrincipal());
    return "registration";
}

@RequestMapping(value = { "/newuser" }, method = RequestMethod.POST)
public String saveUser(@Valid User user, BindingResult result,
        ModelMap model) {
    if (result.hasErrors()) {
        return "registration";
    }
    if(!userService.isUserSSOUnique(user.getId(), user.getSsoId())){
        FieldError ssoError =new FieldError("user","ssoId",messageSource.getMessage("non.unique.ssoId", new String[]{user.getSsoId()}, Locale.getDefault()));
        result.addError(ssoError);
        return "registration";
    }
    userService.saveUser(user);
    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " registered successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

@RequestMapping(value = { "/edit-user-{ssoId}" }, method = RequestMethod.GET)
public String editUser(@PathVariable String ssoId, ModelMap model) {
    User user = userService.findBySSO(ssoId);
    model.addAttribute("user", user);
    model.addAttribute("edit", true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "registration";
}

@RequestMapping(value = { "/edit-user-{ssoId}" }, method = RequestMethod.POST)
public String updateUser(@Valid User user, BindingResult result,
        ModelMap model, @PathVariable String ssoId) {
    if (result.hasErrors()) {
        return "registration";
    }
    userService.updateUser(user);
    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " updated successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

//Update User and Employee By Id
@RequestMapping(value = { "/getUserById" }, method = RequestMethod.GET)
public String getUserSSOId(ModelMap model) {
    User user = new User();
    model.addAttribute("user", user);
    model.addAttribute("edit", true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "userview";
}

@RequestMapping(value = { "/updateByUserId" }, method = RequestMethod.GET)
public String getByUserId( @ModelAttribute User userDetails,ModelMap model,BindingResult result) {
    User user =userService.findBySSO(userDetails.getSsoId());
    if(user!=null){
        model.addAttribute("user", user);
        model.addAttribute("edit", true);
        model.addAttribute("loggedinuser", getPrincipal());
        return "registration";
    }else{
        FieldError referenceIdError =new FieldError("user","ssoId",messageSource.getMessage("non.empty.userid.notexist", new String[]{userDetails.getSsoId()}, Locale.getDefault()));
        result.addError(referenceIdError);
        model.addAttribute("loggedinuser", getPrincipal());
        return "userview";
    }
}

@RequestMapping(value = { "/updateByUserId" }, method = RequestMethod.POST)
public String updateUserById(@Valid User user, BindingResult result,
        ModelMap model) {
    if (result.hasErrors()) {
        return "registration";
    }
    userService.updateUser(user);
    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " updated successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

@RequestMapping(value = { "/deleteByUserId" }, method = RequestMethod.GET)
public String deleteUserById(ModelMap model) {
    User user = new User();
    model.addAttribute("user", user);
    model.addAttribute("delete", true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "userview";
}

@RequestMapping(value = { "/deleteUserById" }, method = RequestMethod.GET)
public String deleteByuserId( @ModelAttribute User userDetails,ModelMap model,BindingResult result) {
    User user=userService.findBySSO(userDetails.getSsoId());
    if(user!=null){
        userService.deleteUserBySSO(userDetails.getSsoId());
        model.addAttribute("loggedinuser", getPrincipal());
        model.addAttribute("employeeSuccess", "Employee " + user.getFirstName() + " deleted successfully");
        return "registrationsuccess";
    }else{
        FieldError referenceIdError =new FieldError("employee","employeeReferenceId",messageSource.getMessage("non.empty.userid.notexist", new String[]{userDetails.getSsoId()}, Locale.getDefault()));
        model.addAttribute("loggedinuser", getPrincipal());
        result.addError(referenceIdError);
        return "userview";
    }

}
}

Body:
You can do that also in Filter. You just have to annotate it with @Component and voila. It becomes a Spring bean. Like this:

@Component
public class UserFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        User user = (User)request.getAttribute("user");
        // Do whatever you want with your user
    }

    @Override
    public void destroy() {

    }
}