Simple Login and Session maintaining with Mysql

Hi everybody,
I'm not expert in Java servlets and I'm writing and application that recognize users and maintain their session trough application's pages.
This application, after authentication, will displays a table coming from a query where I will have to modify only a "square" ( i Don't know the right english name for it,sorry...) of a row, more exactly the notes
I need a hand about Session and Login, and if you can post the code of a "row-selectionable" (to modify notes) query resulted table it will be very appreciated ;) (for the table, does'nt matter if it will be a Servlet or a JSP)
This is my actual Login code, but it doesn't works! (I tried to manage session reading some tutorials around the net)
package Login;
import java.sql.*;
import javax.servlet.http.*;
import javax.swing.JOptionPane;
* @author Alessio
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
public class Login extends HttpServlet{
     private Connection con;
     private Statement st;
     private ResultSet rs,rs2;
     boolean autenticato= false;
     public void doGet(HttpServletRequest req,HttpServletResponse res) {
          try{
          Class.forName("com.mysql.jdbc.Driver");
          con=DriverManager.getConnection("jdbc:mysql://localhost:3306/gecoprova","root","argoilcane");
          HttpSession session=req.getSession(true);
          String sessione = session.getId();
          //APRE uno statement e con una query pesca dal DB tutte le tuple che hanno i dati passati allaservlet (nome, cognome,...)
          st=con.createStatement();     
          rs=st.executeQuery("SELECT * FROM anagrafe_procuratori WHERE ragsoc='"+req.getParameter("ID")+"'");
          //se il RESULTSET non � vuoto fa un check per vedere cosa restituisce RULES mentre nel frattempo pone 1 su LOGGED
          PreparedStatement updateProcuratore = con.prepareStatement("UPDATE privilegi_procuratore SET Logged=? WHERE (userid=? AND pass=?)");
          if(rs!=null){
               if(rs.next())try {
                    st=con.createStatement();
                    rs2=st.executeQuery("SELECT * FROM privilegi_procuratore WHERE (userid='"+req.getParameter("ID")+"' AND pass='"+req.getParameter("pass")+"' AND Logged=0)");
                    if(rs2!=null){
                         if(rs2.next())try {
                                      autenticato = true;
                                      String utente=req.getParameter("ID");
                                      String password=req.getParameter("pass");
                                      HttpSession s= req.getSession(true);
                                      Utente u =(Utente)s.getValue("Login.utente");
                                      if (u==null){
                                           u =new Utente (utente,password);
                                      else{
                                           u.ID=utente;
                                           u.pass=password;
                                      s.putValue("Login.utente",s);
                                        rs2.close();     
                                        con.close();
                                        updateProcuratore.close();
                                        }catch (Exception e){e.printStackTrace();}
                                             if (autenticato=true){               
                                             res.sendRedirect("RulezAmministration");
          else{
               res.sendRedirect("errorlogin.html");
               }catch (Exception e){e.printStackTrace();}
                              res.sendRedirect("errorlogin.html");
          else{
               res.sendRedirect("errorlogin.html");
          res.sendRedirect("errorlogin.html");
          catch(Exception e){
               try {
                    e.printStackTrace();
                    res.sendRedirect("errorlogin.html");
               catch(Exception e1){}
     public void doPost(HttpServletRequest req,HttpServletResponse res){
          try{
          HttpSession s=req.getSession(false);
          Utente u=(Utente)s.getValue("Login.utente");
          u.Logout();
          s.putValue("Login.utente",s);
          res.sendRedirect("index.htm");
               catch(Exception e1){}
public class RulezAmministration extends HttpServlet{
     private Connection con;
     private Statement st;
     private ResultSet rs;
     public void doGet(HttpServletRequest req,HttpServletResponse res){
          try{
               HttpSession s=req.getSession(false);
               if (s!=null){
                    Utente u= (Utente)s.getValue("Login.utente");
                    if (u!=null){
                         if (u.ID!=null){
                              res.sendRedirect("Inserimento.jsp");
                         else res.sendRedirect("errorlogin.html");
          catch(Exception e){}
     }

After you can use:
String utente=req.getParameter("ID");          
String password=req.getParameter("pass");
to get the ID and password, use a Database Access Object to communicate with the database. A sample block of code would something like:
Connection conn = null;
Context ctx = null;
DataSource ds = null;
try {
     DriverManager.registerDriver(new OracleDriver());
     String connectString = "jdbc:oracle:thin:@...";
               conn = DriverManager.getConnection(connectString, userName, password);
} catch (Exception e) {
e.printStackTrace();
Then,
statement = conn.createStatement();
resultSet = statement.executeQuery("select * from TABLE where Id = id and pass=password");
if it returns you a result, then, it means the login info is valid, you can set this info in a session object, like:
request.setSesion().setAttribute("login", "true");
Later on, in your application, you can chk whether the user has logon by
request.getSesion().setAttribute("login");
You should organize your code so that it separate different functions in your program.
Hope that helps.

Similar Messages

  • Basic Questions about JSF, Login and Session

    Hi,
    I try to implement a login/logout function on my jsf-website. I create one <form> with Login and Pass to enter. My AuthenticBean(sessionbean) checks login and pass. If Login is "ok" the login and pass will set in the authenticBean (min. value of login and pass = 2).
    Now I check protected .jsf files (files who need a login) if in the AuthenticBean the login.equals("") or pass.equals(""). If so, the user is not logged in.
    Is this a safe method or should I choose a better way to have secure login/logout functions. Perhaps its better to create a userSessionBean after a succeful login and check it with HttpServletRequest rq.getSession().getAttribute(userSessionBean)?
    I am confused a little bit and I hope you'll help me:)
    Thnx Alex

    Implement a javax.servlet.Filter and indeed use the attributes of the HttpSession.

  • What's the best way for a web app to handle logins and sessions?

    I'm deploying in JBoss, using JSF. As is often the case, I keep User information in an entity bean. My question is, what's the best way to handle this bean?
    My inclination is to create a login page with a LoginBackingBean atached to it. When the user attempts to log in, it will see if there is a User entity bean that corresponds to the given name and password. If there is no User bean that matches, obviously we show an informative error screen.
    But what happens if there is a valid user?
    In the plain old Servlet world (without EJB / J2EE) I would just put the User object (it's an object, not an EJB) into the HttpSession, and I would create a Filter that would check for the presence of that User object, and I would map the filter to something like /members/*, and that would be it. I would use Hibernate to persist the User object, and there would also be a filter that creates a Hibernate session and stores it in the Request so that the User object would work and persist.
    How do I do this within the J2EE / EJB world?
    My first thought would be to just do the same thing. Install the User bean into the HttpSession, and create a filter and do all the same stuff. Is that the right way to do it? It would work pretty well with JSF because I could just access things in the normal JSF way: #{user.firstName} would find the "user" object in the HttpSession scope. So that's good.
    One question that comes up from that is if the user makes some change to the User object that is in the Session scope, will the EJB automatically do the right thing and make those changes persistent? Is there anything else I need to do?
    I'm new to the EJB world, but from what I can see so far, it seems like it's the best way to think about a web application.
    Thanks

    hi ,
    i think the best way is to create java beans ,in that bean call your EJB ,
    and check the validation over there.
    and make that bean scope to session.
    in each and everypage try to check the session ,if it is not valid then forward to your login page...
    otherwise continue to give access to him like guest
    Regards,
    AfTaB

  • Auto login and password problems with Safari after OS 7.0.4 update?

    Hi all,
       I updated my IPad 4 to OS 7.0.4 , now Safari won't auto login to my favorite forums and won't remember my user names or pass words. I checked in Safari settings and Names/passwords and auto fill are on. Have restarted a number of times but no change. Any fixes?
       Thanks.

    Make sure Private Browsing is off.
    Tap "Private" on Safari Screen to disable Private Browsing. When top of screen is white, Private Browsing is off.
    http://i1224.photobucket.com/albums/ee374/Diavonex/547958b4a8c01ac084dd6649e8386 a0f_zps12fa0cca.jpg

  • Help - JSC to Tomcat with MySql

    I built a simple test app in JSC with MySql.
    Product: MySql Ver. 5.0.27-community-nt
    Database name: Test
    Table name: testtable
    Datasource name: MySql1
    Dataprovider's SQL: SELECT ALL testtable.code, testtable.name FROM testtable WHERE testtable.name LIKE ?
    The page had a textfield, button, statictext and a table mapped to the dataprovider
    The following code was included:
    public void prerender() {
    try {
    String s = "";
    String t = (String) textField1.getText();
    if (t == null || t.equals(""))
    s = "";
    else
    s = t;
    s += "%";
    staticText3.setText(s);
    getSessionBean1().getTesttableRowSet().setObject(1,s);
    getSessionBean1().getTesttableDataProvider().refresh();
    } catch (Exception e) {error(e.toString());}
    public String button1_action() {
    return null;
    When tested in JSC, it worked fine.
    But when I exported it as a war file and deployed it in Tomcat 5.5.17 with the following settings, the statictext
    displayed the selected value, but the table showed "No items found". Please help.
    User: root
    password: adminadmin
    Connector downloaded: mysql-connector-java-5.0.4.zip
    The appropriate jstl.jar and standard.jar where used by copying them from jakarta
    The tomcat's server.xml used is shown below:
    <?xml version="1.0" encoding="UTF-8"?>
    <Server>
    <Listener className="org.apache.catalina.core.AprLifecycleListener"/>
    <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
    <Listener className="org.apache.catalina.storeconfig.StoreConfigLifecycleListener"/>
    <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"/>
    <GlobalNamingResources>
    <Environment
    name="simpleValue"
    type="java.lang.Integer"
    value="30"/>
    <Resource
    auth="Container"
    description="User database that can be updated and saved"
    name="UserDatabase"
    type="org.apache.catalina.UserDatabase"
    pathname="conf/tomcat-users.xml"
    factory="org.apache.catalina.users.MemoryUserDatabaseFactory"/>
    <Resource
    name="jdbc/Travel"
    type="javax.sql.DataSource"
    driverClassName="org.apache.derby.jdbc.ClientDriver"
    password="travel"
    maxIdle="2"
    maxWait="5000"
    validationQuery="select * from TRAVEL.PRODUCT"
    username="travel"
    url="jdbc:derby://localhost:21527/samp"
    maxActive="4"/>
    </GlobalNamingResources>
    <Service
    name="Catalina">
    <Connector
    port="8080"
    redirectPort="8443"
    minSpareThreads="25"
    connectionTimeout="20000"
    maxThreads="150"
    maxSpareThreads="75">
    </Connector>
    <Connector
    port="8009"
    redirectPort="8443"
    protocol="AJP/1.3">
    </Connector>
    <Engine
    defaultHost="localhost"
    name="Catalina">
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"/>
    <Host
    appBase="webapps"
    name="localhost">
    <Context
    path="/TomTest">
    </Context>
    <Context
    path="/TradeMeTender">
    <Resource
    auth="Container"
    description="Creator generated DataSource Reference"
    name="jdbc/Travel"
    type="javax.sql.DataSource"
    driverClassName="org.apache.derby.jdbc.ClientDriver"
    password="travel"
    maxIdle="2"
    maxWait="5000"
    validationQuery="SELECT * from TRAVEL.PRODUCT"
    username="travel"
    url="jdbc:derby://localhost:21527/sample"
    maxActive="4"/>
    </Context>
    <Context
    path="/FileUploadExample">
    <EJB
    home="greeting.GreeterHome"
    name="GreeterEJB"
    remote="greeting.Greeter"
    type="Session"/>
    </Context>
         <Context path="/MySqlTest" docBase="MySqlTest"
         debug="5" reloadable="true" crossContext="true">
              <Resource name="jdbc/MySql1" auth="Container" type="javax.sql.DataSource"
    maxActive="100" maxIdle="30" maxWait="10000"
    username="root" password="adminadmin" driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/Test?autoReconnect=true"/>
         </Context>
    </Host>
    </Engine>
    </Service>
    </Server>

    You could track JDBC calls and the SQL's executed by the driver at the database,
    Update you datasource, DBURL with some parameters/properties to generate some info for debugging like this:
    jdbc:mysql://$hostname:$port/$databasename?autoGenerateTestcaseScript=true&dumpQueriesOnException=true
    Check out your deployment containers log to find out which particular SQL statement is being executed. This could help in identifying performance issues with application. That could possibly give a clue, if something is not working in your application.
    For designtime JDBC calls made, this info is sent to IDE log.
    Reference: http://dev.mysql.com/doc/refman/5.0/en/cj-configuration-properties.html
    HTH,
    Sakthi

  • Start-up / shut-down (and other) problems with ZFS over iSCSI

    Hi,
    I've had a limited time in which to try some concepts on an evaluation x4500 server. This is unfortunately my last day, so by the time anyone can reply I will probably not be able to to further tests, but maybe someone will be able to reproduce the issues.
    I'm using the evaluation server to export some iSCSI targets, and I'm connecting to them from my laptop, which has a fresh installation of SXDE 01/08. I was able to attach to the targets with
    iscsiadm add static-config \
    iqn.1986-03.com.sun:02:f4281081-c3fc-e448-c8f0-943d8861c9e8,192.168.15.62
    iscsiadm add static-config \
    iqn.1986-03.com.sun:02:371c6fe7-f0c8-e02c-c865-baef90fb71ce,192.168.15.62
    iscsiadm add static-config \
    iqn.1986-03.com.sun:02:ee74d5de-3046-6295-f35e-afe60e13db23,192.168.15.62
    iscsiadm modify discovery -s enableThis made the appropriate entries appear in /dev/dsk so I could then set up a simple zpool and zfs filesystem with:
    zpool create -m none dPool c3t010000144FA70C1400002A0047C2BF73d0 \
    c3t010000144FA70C1400002A0047C2BF81d0 c3t010000144FA70C1400002A0047C2BF8Bd0
    zfs create -o mountpoint=/data -o sharenfs=on dPool/dataThe general concept I'm testing is having a ZFS-based server using an IP SAN as a growable source of storage, and making the data available to clients over NFS/CIFS or other services. In principle this solution should also allow failover to another server, since all the ZFS data and metadata is in the IP SAN, not on the server. Although not done in this example it should also be possible to run raidz across multiple iSCSI disk arrays. However, it's not been a bed of roses. I've had a lot of errors in dmesg like the following, which I think are causing zfs/zpool commands to stall at times:
    Feb 28 14:30:39 F4060 iscsi: [ID 866572 kern.warning] WARNING: iscsi connection(ffffff014f6b6b78) protocol error - received an unsupported opcode:0x41
    Feb 28 14:30:41 F4060 iscsi: [ID 158826 kern.warning] WARNING: iscsi connection(10) login failed - failed to receive login response
    Feb 28 14:30:41 F4060 scsi_vhci: [ID 734749 kern.warning] WARNING: vhci_scsi_reset 0x1
    Feb 28 14:30:41 F4060 iscsi: [ID 339442 kern.notice] NOTICE: iscsi connection failed to set socket optionTCP_NODELAY, SO_RCVBUF or SO_SNDBUF
    Feb 28 14:30:41 F4060 iscsi: [ID 933263 kern.notice] NOTICE: iscsi connection(13) unable to connect to target iqn.1986-03.com.sun:02:ee74d5de-3046-6295-f35e-afe60e13db23
    Feb 28 14:30:41 F4060 iscsi: [ID 339442 kern.notice] NOTICE: iscsi connection failed to set socket optionTCP_NODELAY, SO_RCVBUF or SO_SNDBUF
    Feb 28 14:30:41 F4060 iscsi: [ID 933263 kern.notice] NOTICE: iscsi connection(7) unable to connect to target iqn.1986-03.com.sun:02:f4281081-c3fc-e448-c8f0-943d8861c9e8Does anyone know why a Solaris iSCSI target would send an unsupported opcode (0x41) to a Solaris iSCSI initiator? Surely they should be talking the same language!
    The main problems however are with shutdown and start-up. On occasions, I suspect that the ordering of ZFS, iSCSI and network services gets a bit out of sync. On one occasion the laptop even refused to complete the shutdown because it was reporting a continuous stream of console messages like
    Feb 27 18:26:37 F4060 iscsi: [ID 933263 kern.notice] NOTICE: iscsi connection(13) unable to connect to target iqn.1986-03.com.sun:02:ee74d5de-3046-6295-f35e
    -afe60e13db23
    Feb 27 18:26:37 F4060 iscsi: [ID 933263 kern.notice] NOTICE: iscsi connection(10) unable to connect to target iqn.1986-03.com.sun:02:371c6fe7-f0c8-e02c-c865
    -baef90fb71ce
    Feb 27 18:26:37 F4060 iscsi: [ID 933263 kern.notice] NOTICE: iscsi connection(7) unable to connect to target iqn.1986-03.com.sun:02:f4281081-c3fc-e448-c8f0-
    943d8861c9e8I also get these on start-up, where it looks like ZFS tries to load the zpool configuration before iSCSI has found the disks, and even worse, iSCSI is starting up before nwamd has time to do its network auto-magic, and complains that the devices are unavailable.
    If these problems sorted themselves out after everything came up, I wouldn't really mind some temporary complaints in the log file, but what I get after a reboot is a working zpool but an unmounted ZFS filesystem! Here is what I have today:
    bash-3.2# zpool status
      pool: dPool
    state: ONLINE
    scrub: scrub completed with 0 errors on Thu Feb 28 14:33:43 2008
    config:
            NAME                                     STATE     READ WRITE CKSUM
            dPool                                    ONLINE       0     0     0
              c3t010000144FA70C1400002A0047C2BF73d0  ONLINE       0     0     0
              c3t010000144FA70C1400002A0047C2BF81d0  ONLINE       0     0     0
              c3t010000144FA70C1400002A0047C2BF8Bd0  ONLINE       0     0     0
    errors: No known data errors
    bash-3.2# zfs list
    NAME         USED  AVAIL  REFER  MOUNTPOINT
    dPool        480M  28.9G     1K  none
    dPool/data   480M  28.9G   480M  /dataThis all looks fine, and you can see that I was even able to scrub the pool data with no problems. But where are the 480MB of data I have put in the /data mountpoint:
    bash-3.2# ls /data
    bash-3.2# df -h /data
    Filesystem             size   used  avail capacity  Mounted on
    /dev/dsk/c1d0s0         15G   4.4G    11G    30%    /As you can see, /data is unmounted, causing df to revert to the / filesystem containing the empty /data mountpoint, instead of showing the zpool mount.
    Since zfs is supposed to take care of its own mounts rather than using vfstab, I can't use "mount /data" to force this to mount. The only workaround I've found is to export and import the zpool. Then I get the filesystem to reappear:
    bash-3.2# df -h /data
    Filesystem             size   used  avail capacity  Mounted on
    dPool/data              29G   480M    29G     2%    /dataDoes anyone know if these are known issues with snv_79b, and is there a fix available or in the works?
    TIA,
    Graham

    EasyE, Welcome to the discussion area!
    (a) Call Apple and get your iMac G5 fixed since it is in the repair extension group. Don't waste your time doing anything else.
    (b) This area is for discussing the iMac G4. Since you have an iMac G5 in the future you should post in the iMac G5 discussion area.

  • A drag and drop game with dynamic text response

    Hi,
    I am a teacher and my school has recently upgraded to Adobe Design Premium.  Our previous version was about 5 versions out of date.
    I teach A Level which requires students to create an Interactice Multimedia product.
    In the previous 6 years, I have taught students how to create simple drag and drop game with dynamic text responses.
    Since the upgrade to Actionscript 3.0 the dynamic text response has ceased working.
    When creating the game from scratch, I need to move to Actionscript 2.0 as 3.0 does not allow me to add actionscript to objects - I know and am sure that this is a better way of doing things, but I would prefer to keep working the way I am used to.
    I use a switch case statement which I have copied below to make the drag and drop work.  The objects I apply the code to work in that they can be dragged, however, my dynamic text box with a variable name of "answer" is no longer displaying the response when an answer is left on a dropzone (rectangle converted to a symbol and given an instance name).
    on(press) {
    startdrag(this);
    on(release) {
    stopdrag();
    switch(this._droptarget) {
      case "/dropzoneB":
       _root.answer="Well done";
       break;
      case "/dropzoneA":
      case "/dropzoneC":
       _root.answer="Hopeless";
       break;
      default:
       _root.answer="";
       break;
    Any help would be much apeciated.
    Thanks
    Adrian

    To drag in as3
    blie_btn is the instance of the object drawin on the stage. In AS3 you have to assign a even listener, in this case MOUSE_DOWN, and MOUSE_UP, as we want the drag to stop if the mouse is not clicked. Then we fire the functions, and tell the object to start drag.
    // Register mouse event functions
    blue_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
    blue_btn.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
    red_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
    red_btn.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
    // Define a mouse down handler (user is dragging)
    function mouseDownHandler(evt:MouseEvent):void {
         var object = evt.target;
         // we should limit dragging to the area inside the canvas
         object.startDrag();
    function mouseUpHandler(evt:MouseEvent):void {
         var obj = evt.target;
              obj.stopDrag();
    if you want to make the text do what you want then something like this might work.
    In the function, you could add a text box onto the stage, give it a instance of something like outputText
    and then:
    outputText = ("Bla Bla Bla");
    (^Not sure if this will work exactly^)
    PS. I am currently a A-level student

  • Create and sign PDF with IAC?

    Hello, does anybody know, how to create simple PDF and sign it with X509Certificate from .NET managed application? It seems to me, that it is not possible with Acrobat Interapplication Communication API. Do I really need LiveCycle for this operation?
    Thank you for help.

    When you say "create", do you really mean "convert some other format to PDF" or did you want to start with a blank page and then do things like "draw string", "draw line", etc?
    Will this be a desktop or server-based application?

  • How to work with EJBs and database for a simple login application

    Hi all :)
    I am new in JSP,EJB and Servlets. I just wanted to develop a simple login application, using JSP+EJBand servlets. In some tutorial I found that the beans are already populatesd with database records. But will it be good logic to retrive all records into a bean and then search for a perticuler users data for authentication.
    Can any one tell me me what is the best logic for doing so. :(
    Thanx in advance.

    Himanshu.Shekhar wrote:
    Hi all :)
    I am new in JSP,EJB and Servlets. I just wanted to develop a simple login application, using JSP+EJBand servlets. In some tutorial I found that the beans are already populatesd with database records. But will it be good logic to retrive all records into a bean and then search for a perticuler users data for authentication.No. Let the database do the search. It's far more efficient.
    %

  • What's wrong with a simple login.jspx?

    Hello,
    I wrote a simple login.jspx page by following the indications at http://download.oracle.com/docs/cd/E15523_01/web.1111/b31974/adding_security.htm#BABDEICH
    Now, the page works with Firefox 5, but does not with IE 7. When under IE 7, the page keeps reloading giving errors about *"AdfBootStrap undefined*" or *"AdfLogger undefined".*
    What is wrong? Please note that I have already read all the threads on the forum about this issue, without actually solving my problem (I have not really seen any useful solutions there to be honest).
    Jdeveloper is 11.1.1.5.0, only adf authentication is enabled.
    The error messages are like the following ones:
    http://forums.oracle.com/forums/thread.jspa?threadID=952977&tstart=29
    thanks.
    Edited by: user10047839 on 27-giu-2011 8.07
    Changing from jspx to jsp does not solve the problem.

    Hello codeplay,
    in the source code of the page I have the following similar to your line:
    <script type="text/javascript" src="/Myapp/afr/partition/ie/default/opt/boot-11.1.1.5.0-1095.js"></script>
    No lines with SHERMAN inside.
    I could not open "/Myapp/afr/partition/ie/default/opt/boot-11.1.1.5.0-1095.js" or
    "afr/partition/ie/default/opt/boot-11.1.1.5.0-1095.js". Page not found
    Why does it happen with login page only?
    In firefox, as opposite to ie, where the page is rendered a little better (not as good as it should be though, due to these problems), I can login and be redirected to the secured main page, which is another .jsp, more complex than the simple login page, and there I have no problems at all.
    I noticed that the badly rendered page has a link pointing to the generated html below. NOTE that JavaScript IS ENABLED in my IE despite what this html says at the end. I checked this twice:
    WHAT IS WRONG??????????
    <html lang="en-EN"><head><script>
    ** Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
    * This is the loopback script to process the url before the real page loads. It introduces
    * a separate round trip. During this first roundtrip, we currently do two things:
    * - check the url hash portion, this is for the PPR Navigation.
    * - do the new window detection
    * the above two are both controled by parameters in web.xml
    * Since it's very lightweight, so the network latency is the only impact.
    * here are the list of will-pass-in parameters (these will replace the param in this whole
    * pattern:
    * viewIdLength view Id length (characters),
    * loopbackIdParam loopback Id param name,
    * loopbackId loopback Id,
    * loopbackIdParamMatchExpr loopback Id match expression,
    * windowModeIdParam window mode param name,
    * windowModeParamMatchExpr window mode match expression,
    * clientWindowIdParam client window Id param name,
    * clientWindowIdParamMatchExpr client window Id match expression,
    * windowId window Id,
    * initPageLaunch initPageLaunch,
    * enableNewWindowDetect whether we want to enable new window detection
    * jsessionId session Id that needs to be appended to the redirect URL
    * enablePPRNav whether we want to enable PPR Navigation
    var id = null;
    var query = null;
    var href = document.location.href;
    var hashIndex = href.indexOf("#");
    var hash = null;
    /* process the hash part of the url, split the url */
    if (hashIndex > 0)
    hash = href.substring(hashIndex + 1);
    /* only analyze hash when pprNav is on (bug 8832771) */
    if (false && hash && hash.length > 0)
    hash = decodeURIComponent(hash);
    if (hash.charAt(0) == "@")
    query = hash.substring(1);
    else
    var state = hash.split("@");
    id = state[0];
    query = state[1];
    href = href.substring(0, hashIndex);
    /* process the query part */
    var queryIndex = href.indexOf("?");
    if (queryIndex > 0)
    /* only when pprNav is on, we take in the query from the hash portion */
    query = (query || (id && id.length>0))? query: href.substring(queryIndex);
    href = href.substring(0, queryIndex);
    var jsessionIndex = href.indexOf(';');
    if (jsessionIndex > 0)
    href = href.substring(0, jsessionIndex);
    /* we will replace the viewId only when pprNav is turned on (bug 8832771) */
    if (false)
    if (id != null && id.length > 0)
    href = href.substring(0, href.length - 10) + id;
    var isSet = false;
    if (query == null || query.length == 0)
    query = "?";
    else if (query.indexOf("_afrLoop=") >= 0)
    isSet = true;
    query = query.replace(/_afrLoop=[^&]*/, "_afrLoop=12570889997779");
    else
    query += "&";
    if (!isSet)
    query = query += "_afrLoop=12570889997779";
    /* below is the new window detection logic */
    var initWindowName = "_afr_init_"; // temporary window name set to a new window
    var windowName = window.name;
    // if the window name is "_afr_init_", treat it as redirect case of a new window
    if ((true) && (!windowName || windowName==initWindowName ||
    windowName!="1bvr27bkx4_1"))
    /* append the _afrWindowMode param */
    var windowMode;
    if (false)
    /* this is the initial page launch case,
    also this could be that we couldn't detect the real windowId from the server side */
    windowMode=0;
    else if ((href.indexOf("/__ADFvDlg__") > 0) || (query.indexOf("__ADFvDlg__") >= 0))
    /* this is the dialog case */
    windowMode=1;
    else
    /* this is the ctrl-N case */
    windowMode=2;
    if (query.indexOf("_afrWindowMode=") >= 0)
    query = query.replace(/_afrWindowMode=[^&]*/, "_afrWindowMode="+windowMode);
    else
    query = query += "&_afrWindowMode="+windowMode;
    /* append the _afrWindowId param */
    var clientWindowId;
    /* in case we couldn't detect the windowId from the server side */
    if (!windowName || windowName == initWindowName)
    clientWindowId = "null";
    // set window name to an initial name so we can figure out whether a page is loaded from
    // cache when doing Ctrl+N with IE
    window.name = initWindowName;
    else
    clientWindowId = windowName;
    if (query.indexOf("_afrWindowId=") >= 0)
    query = query.replace(/_afrWindowId=\w*/, "_afrWindowId="+clientWindowId);
    else
    query = query += "&_afrWindowId="+clientWindowId;
    var sess = "";
    if (sess.length > 0)
    href += sess;
    /* if pprNav is on, then the hash portion should have already been processed */
    if ((false) || (hash == null))
    document.location.replace(href + query);
    else
    document.location.replace(href + query + "#" + hash);
    </script><noscript>JavaScript is not enabled in your browser.</noscript></head></html>

  • Simple authentication and authorization with a servlet and a filter

    Could somebody point me to code example that do simple authentication/authorization using one servlet and one filter? (without Spring, Struts, JSF or any framework)
    I&rsquo;m having a lot of problems with that, apparently, easy task.
    These are the rules:
    - A simple login page
    - Two roles (admin, registered).
    - If the user loged is an admin, redirect to his entry page (private/admin/index.jsp).
    - If the user loged is of role registered, redirect him to his entry page (private/registered/index.jsp).
    - If it&rsquo;s not a valid user, redirect again to login page.
    - Admin&rsquo;s users cannot go to private/registered/ area.
    - Registered users cannot go to private/admin/ area.
    - Non authenticated user cannot go to private/ area
    Thanks a lot in advance!
    Edited by: JLuis on 25-ago-2010 15:27

    AccessControl.java:
    package com.tlsformacion.security;
    import java.io.IOException;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.tlsformacion.utils.Log;
    public final class AccessControl extends HttpServlet {
         private static final long serialVersionUID = 5741058615983779764L;
         private static final String USERNAME_ATTR = "username";
         private static final String PWD_ATTR = "password";
         private static final String LOGIN_PAGE_ATTR = "login_page";
         private static final String ROL_ATTR = "role";     
         private boolean isAuthentic = false;
         private String role = null;
         private String loginPage = null;
         public AccessControl() {
            super();
         public void init(ServletConfig config) throws ServletException {
              loginPage = config.getInitParameter(LOGIN_PAGE_ATTR);
         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside doGet");
              doAccessControl(request, response);
         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside doPost");
              doAccessControl(request, response);
         private void doAccessControl (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside doAccessControl");
              doAuthentication(request, response);     
              if (isAuthentic) { //Authentic user
                   doAuthorization(request, response);                         
              } else { //User NOT authentic
                   doRejection(request, response);
         private void doAuthentication(HttpServletRequest request, HttpServletResponse response) {     
              debug("Inside doAuthentication");                         
            String requestedURI = request.getRequestURI();
            if (requestedURI.contains("/AccessControl")) { //Comes from login page           
                 debug("Comes from login page");
                  String username = request.getParameter(USERNAME_ATTR);
                String pwd = request.getParameter(PWD_ATTR);   
                 role = getRole(username, pwd);
                 if (role != null) {
                      isAuthentic = true;
                      request.getSession().setAttribute(ROL_ATTR, role);
            } else { //Doesn't comes from login page
                 debug("Doesn't comes from login page");
                 if (isInSession(request)) {
                      debug("Rol is in session");               
                      isAuthentic = true;
                 } else {
                      debug("Rol is NOT in session");
         private void doAuthorization(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {          
              debug("Inside doAuthorization");
              String requestedURI = request.getRequestURI();
              debug("requestedURI: " + requestedURI);
              if (requestedURI.contains("/AccessControl")) { //Comes from login page                                                                 
                   goHomePage(request, response);
              } else if (requestedURI.contains("/private/" + role)) { //Trying to access his private area
                   goRequestedPage(request, response);
              } else { //Trying to access other roles private area
                   goLoginPage(request, response);
        private void doRejection(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {          
             debug("Inside goRejection");
             role = null;
              goLoginPage(request, response);         
         private void goHomePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside goHomePage");     
              String homePage = "private/" + role + "/index.jsp";
              goPage(request, response, homePage);
         private void goLoginPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside goLoginPage");
              goPage(request, response, loginPage);
         private void goRequestedPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside goRequestedPage");
              String contextPath = request.getContextPath();          
              debug("contextPath: " + contextPath);
              String requestedPage = request.getRequestURI().replace(contextPath + "/", "");
              goPage(request, response, requestedPage);
         private void goPage(HttpServletRequest request, HttpServletResponse response, String page) throws IOException, ServletException {
              debug("Inside goPage ...trying to go to: " + page);
              //Option A
              response.sendRedirect(page);
              //Option B
              //RequestDispatcher requestDispatcher = request.getRequestDispatcher(page);
              //requestDispatcher.forward(request, response);                  
         private boolean isInSession(HttpServletRequest httpRequest) {
             boolean inSession = false;
              role = (String)httpRequest.getSession().getAttribute(ROL_ATTR);
              if (role != null && !role.equals("")) {
                   inSession = true;
             return inSession;
        //PENDIENTE: mock method!
        private String getRole(String username, String pwd) {         
             String role = null;
             if (username.equals("admin") && pwd.equals("admin")) {
                  role = "administrator";
             } else if (username.equals("regis") && pwd.equals("regis")) {
                  role = "registered";
             return role;
        private void debug(String msg) {
             Log.debug(msg);
    }Proyect Folder Structure:
    WebContent
         login.html
         private
              administrator
                   index.jsp
              registered
                   index.jspBasically, the problem is that if you try to log as admin/admin (for example) the servlet AccessControl executes infinitely
    Edited by: JLuis on 26-ago-2010 8:04

  • Php with mysqli, mbstring and xsl extensions

    I don't understand why php isn't build with mysqli and mbstring extensions since mysql4 is installed and there are a lot of languages that need multibytes strings. Here is a PKGBUILD that enable them. I also added xsl extension to use xsl files with php.
    # $Id: PKGBUILD,v 1.51 2004/12/16 22:03:19 judd Exp $
    # Maintainer: dorphell <[email protected]>
    # Contributor: Benoit Chesneau <[email protected]>
    pkgname=php
    pkgver=5.0.3
    pkgrel=2
    pkgdesc="A high-level scripting language"
    url="http://www.php.net"
    backup=(etc/php.ini)
    depends=('openssl' 'libjpeg' 'freetype2' 'libpng' 'pam'
    'gdbm' 'libxml2' 'openldap' 'ncurses' 'curl' 'libxslt')
    makedepends=('apache' 'mysql' 'imap' 'postgresql' 'bzip2' 'smtp-server'
    'gd' 'fam' 'sqlite3' 'unixodbc')
    source=(http://www.php.net/distributions/$pkgname-$pkgver.tar.gz php.ini)
    md5sums=('bf89557056ce34d502e20e24071616c7' 'd5b9b37fbb746f0967d795763106735a')
    build() {
    cd $startdir/src/$pkgname-$pkgver
    ./configure --with-apxs2 --prefix=/usr --sysconfdir=/etc
    --with-layout=PHP
    --with-ttf --enable-mailparse --with-config-file-scan-dir=/etc
    --enable-bcmath=shared --enable-calendar=shared --enable-ftp=shared
    --enable-gd-native-ttf --enable-magic-quotes --enable-posix=shared
    --enable-session --enable-shared --enable-shmop=shared --with-imap
    --with-imap-ssl --with-ncurses --with-readline --with-sqlite=shared
    --enable-sysvsem=shared --enable-sysvshm=shared --enable-track-vars
    --enable-trans-sid --enable-safe-mode --enable-sockets=shared
    --enable-xml --with-bz2=shared --with-curl --with-mime-magic
    --with-unixODBC=shared
    --enable-dba --without-db2 --without-db3 --with-inifile --with-flatfile
    --with-gdbm --with-freetype-dir=/usr --with-gd=shared --enable-exif
    --with-jpeg-dir=/usr --with-mysql=/usr --with-mysqli=/usr/bin/mysql_config
    --with-ldap=shared
    --with-mysql-sock=/tmp/mysql.sock --with-openssl --with-gettext
    --with-pear=/usr/share/pear --with-dom --with-dom-xslt
    --with-pgsql=shared --with-pgsql-sock=/tmp/pgsql.sock
    --with-png-dir=/usr --with-regex=php --with-zlib --with-fam=shared
    --with-xsl
    --enable-mbstring=all --enable-mbregex
    # fixes a build error in sqlite support
    ln -s main/php_config.h ./config.h
    make || return 1
    mkdir -p $startdir/pkg/usr/lib/apache
    # cp config_vars.mk config_vars.old
    # sed "s|^INSTALL_IT.*$|INSTALL_IT = apxs -i -a -S LIBEXECDIR=$startdir/pkg/usr/lib/apache -n php4 libs/libphp4.so|" config_vars.old >config_vars.mk
    sed -i "s|-i -a -n php5|-i -n php5|g" Makefile
    make INSTALL_ROOT=$startdir/pkg EXTENSION_DIR=/usr/lib/php install
    cp ../php.ini $startdir/pkg/etc

    i suggest filing a feature request through the bug tracker.
    As for why such features may not be compiled in is that whoever maintains the package may have never had the need to have such features in php or experienced any issue because of it. You will experience this with many distros so I suggest not getting accusatory and simply request the feature through the proper channels.
    Each persons needs and experience are different and that is why developers write their code to encompass as many features as their users request.  How robust a package needs to be in arch is up to people like you giving the crucial feedback.
    (btw i don't see why your request would not be granted. I suggest the feature request though because i know the maintainer of the PHP package is not a frequent visitor to this forum but he will get your request if you make to the bug tracker)

  • Maintaining login page session id

    I have a login page 101 that has some webservice calls in it and saves returned data into collections. I am using the standard login pkg :
    wwv_flow_custom_auth_std.login(
    P_UNAME => :P1_USERNAME,
    P_PASSWORD => :P1_PASSWORD,
    P_SESSION_ID => v('APP_SESSION'),
    P_FLOW_PAGE => :APP_ID||':100'
    I noticed that afer login and going to home page ( page 100 here ) it changes the session id , which results in wiping out my collections! Is there a way to maintain the same sessionID for the login page and use it through the application ? I thought that P_SESSION_ID => v('APP_SESSION') is supposed to do that but it actually does not !
    Any hints ?
    Thanks,
    Sam

    Scott,
    I would love to upload my app to apex.oracle.com, but I can not actually do that for many reasons including the amount of work/time it may take.
    But I can provide you with an overview of what I am doing there:
    1- page 101 is my login page
    - I have a process before submit that is basically a secure web service call (( and I think this is causing the issue but am not sure yet))
    - On submit, I have a login process that basically calls a custom auth. scheme that looks like the built in auth scheme except in that it checks for users in some users table I defined and checks the role for the user to redirect to the appropriate page ... 1,2,3.....
    my_sec_pkg.login(
    P_UNAME => :P101_USERNAME,
    P_PASSWORD => :P101_PASSWORD,
    P_SESSION_ID => v('APP_SESSION'),
    P_FLOW_PAGE => :APP_ID
    );and my sec_pkg.login calls the standard login function:
    --check for user in my users table and check the role, and finally sets the go_to_page, then
    wwv_flow_custom_auth_std.login(
    P_UNAME => :P1_USERNAME,
    P_PASSWORD => :P1_PASSWORD,
    P_SESSION_ID => v('APP_SESSION'),
    P_FLOW_PAGE => :APP_ID||':'||go_to_page
    );and I also have a valid_user function in this package that simply returns true if user is valid and is set to be my current auth. scheme
    Now when I login to Apex >> my app >> run for the first time (user in session state is my apex_user)>> login works fine
    If I log out , user in session state becomes no body and if I try to login with correct user/pwd is gives the error I reported in my first post
    Another way to reproduce this error is to run the app directly in a browser , i.e type in "....../pls/apex/f?p=100:101 " , here I also will see the "nobody" user and same problem.
    I am suspecious that this has to do with my web service call, since I never had such an issue before ( where I never used web services).
    Another note about changing the session id in the home page ( right after I login) , I checked the session value passed to the auth. pkg, and it is the correct session id for the login page, but I don't know why it changes it in the home page ! which causes me to loose the collection that saves the web service call return!
    P.S: here is my logout URL :
    wwv_flow_custom_auth_std.logout?p_this_flow=&APP_ID.&p_next_flow_page_sess=&APP_ID.:101Sorry for the time this may consume , but I tried to provide as much useful details as possible.
    Thanks,
    Sam

  • JDeveloper 10.1.2 with MySQL and PostgreSQL

    I'm testing JDeveloper 10.1.2 business components with mysql or postgresql because my company needs to connect also to these non-oracle DBs. ADF suits our developement needs, in speed and functionalities; anyway to make it our main developement system we need it to be compatible.
    I made three tests and they were all disappointing.
    At first, I installed MySQL 4.0 on my windows machine. I used the stable Connector/J 3.1
    and then MySQL Connector/J 3.0, but in both cases JDeveloper had a strange behaviour: I can make the connection, I can navigate correctly through all tables in the connection-navigator, I see all the column names etc... Anyway, as I try to build a "new Entity Object" from a table, there are no available table properties, like if the table had no columns.
    In this forum I only found documentation about rowid problems with mysql, but nothing about Entity Object wizard issues.
    Then I switched to PostgreSQL. I installed it locally, so I had to choose the 8.01 since I'm on a windows machine. JDBC driver: postgresql-8.0-310 jdbc3
    The developement test phase went ok, it is possible to use this DB just as if it was a Oracle, all the business components wizards works perfectly.
    The problem is at runtime, unfortunately. I built a simple datapage on the struts-config diagram and I dragged on it a "read-only table" from the data control palette.
    As I run the application, the embedded OC4J immediately returns this error:
    oracle.jbo.JboException: JBO-29000: JBO-29000: JBO-29000: JBO-26061: Errore durante lapertura della connessione JDBC.
    at oracle.jbo.JboException.<init>(JboException.java:343)
    (in english: Error during JDBC connection)
    There are no other available JDBC drivers for JVM 1.4x so I see no solution...
    I also tried to connect to an older PostgresSQL with its (older) JDBC but I get same the result.
    Anyone can help? Is it a JDev 10.1.2 issue?

    Hi Paolo.
    I'm also doing such tests.
    I did not ran into these problems because I created the busisness componentes using an Oracle connection first.
    After that, I switched the datatype of the table columns in the entity object to meet the SQL92 criteria ( like changing NUMBER(n) to INTEGER ).
    And then, I switched the connection to the postgreSQL or MySQL. This worked fine for me.
    But, the other big problem you will face is related to updating records using postgreSQL connection.
    Please see my post "Problem updating records using BC4J with foreign data sources" Problem updating records using BC4J with foreign data sources
    It would by fine if we help each other to solve this problems.
    Thanks
    Denis

  • "Accounting-Start" and "Accounting-Stop" with same "user name" and "session Id" recorded in different RADIUS servers.

    Hi,
    I have questions about "Accounting-Start" and "Accounting-Stop".
    1.If a NAS configured to have a primary and a backup RADIUS server. To start with all the “Accounting-Start” records will be in the primary RADIUS server. Later on the primary server goes down (Primary server won’t tell the NAS?). When sessions stop, the NAS sends the “Accounting-Stop” to the secondary. I understand the “Start-Stop” record with the same “user name” and “session-id” ideally should be recorded in the same server. If this situation happens what should both the NAS and RADIUS server do?
    2.A NAS configured to have a primary and backup RADIUS server. To start with all the “Accounting-Start” records will be in the primary RADIUS server. Later on the administrator decided to change the primary server (as there are problems with the previous primary). sessions stop, the NAS sends the “Accounting-Stop” to the new primary. This ends up the “Accounting-Start” and “Accounting-Stop” with the same “user name” and “session Id” in two RADIUS servers.
    To summarize, how to avoid the ”start-stop” pair ends up in different servers ? If it does, is it  an issue for RADIUS application ?
    Cheers,
    1.If a NAS configured to have a primary and a backup RADIUS server. To start with all the “Accounting-Start” records will be in the primary RADIUS server. Later on the primary server goes down (Primary server won’t tell the NAS?). When sessions stop, the NAS sends the “Accounting-Stop” to the secondary. I understand the “Start-Stop” record with the same “user name” and “session-id” ideally should be recorded in the same server. If this situation happens what should both the NAS and RADIUS server do?
    2.A NAS configured to have a primary and backup RADIUS server. To start with all the “Accounting-Start” records will be in the primary RADIUS server. Later on the administrator decided to change the primary server (as there are problems with the previous primary). sessions stop, the NAS sends the “Accounting-Stop” to the new primary. This ends up the “Accounting-Start” and “Accounting-Stop” with the same “user name” and “session Id” in two RADIUS servers.
    To summarize, how to avoid the ”start-stop” pair ends up in different servers ? If it does, is it  an issue for RADIUS application ?
    Cheers,

    vignesh and BalusC,
    following is the code in front controller's doFilter method. is this not thread safe?
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            HttpSession session = req.getSession();
            somepackage.User user;
            if(session.getAttribute("user") == null){
                user = new somepackage.User();
                session.setAttribute("user", user);
            }else{           
                user = (somepackage.User) session.getAttribute("user");
            }user object maintains all information about a user. if it is in session scope, everything should work fine.
    another observation is after some time of usage, both people in different systems are getting same session.getId()
    in my logout page i am using
    session.invalidate();
    thanks,
    moses

Maybe you are looking for

  • Conversion of dimensionless units is not possible

    Dear All, i have maintain WM configuration. but while creating and saving a MIGO document w.r.t PO errors shows "Conversion of dimensionless units is not possible". Waiting for favourable response regards Mahesh Dasari

  • Changing Datasource and New Aliases in CRystal Reports 11

    <p>I am in the process of converting from Crystal 7 to Crystal 11. In existing reports that have been saved in 11, I need to point to new tables. After pointing to a new table I get error messages saying that it does not know the fields used in the r

  • Microsoft Exchange 2010 and Outlook 2013

    My colleagues computer suddenly crashed yesterday and it wouldn't restart without a system restore. Now when we try to open up Outlook it says that you must connect to Microsoft Exchange at least once before you can usse your Outlook Data file (.ost)

  • Secure connections

    I want to be able to create secure http connections (https) I am a complete novice when it comes to security. Can anybody help me figure out how to do this? Is it online somewhere?

  • IPhoto 5 Slideshow - Cannot create slideshow to include titles.

    Whilst I can watch a slideshow which includes titles from a photo album, if I wish to create a slideshow from that album, there is no opportunity to then include titles, transition or music. Selecting the display icon selection when selecting a slide