HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

Embed Size (px)

Citation preview

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    1/30

    HandOnLabs_Portlet_Simple Login Portlet App with MySQL_v1.1 RAI Dept, FPT Software HCM

    Hands-On Lab

    Build a simple Login Portlet App with MySQL.

    Page i

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    2/30

    HandOnLabs_Portlet_Simple Login Portlet App with MySQL_v1.1 RAI Dept, FPT Software HCM

    *A - Added M - Modified D Deleted

    13-Feb-10 DoanNX. A Create. 1.0

    14-Mar-10 DoanNX. M Modify. 1.1

    Pageii

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    3/30

    HandOnLabs_Portlet_Simple Login Portlet App with MySQL_v1.1 RAI Dept, FPT Software HCM

    Build a simple Login Portlet App with MySQL...............................................................................................i

    LAB: BUILDING A SIMPLE LOGIN PORTLET APP WITH MYSQL...................................................................5

    Lab Objectives...............................................................................................................................................5Exercise 1 Create a simple portlet application SimpleLoginPortlet...............................................................61. Create a new Dynamic Web Project............................................................................................................ 61. In the next dialog, click Next button............................................................................................................. 62. In this dialog, let modify the value of Context root: change from SimpleLoginPortlet to portletdriver/dt........................................................................................................................................................................ 74. Create new portlet object: SimpleLoginPortlet............................................................................................. 83. Input information for SimpleLoginPortlet portlet as following:....................................................................... 86. Modify the JSPs.......................................................................................................................................... 9Open the SimpleLoginPortlet\WebContent\WEB-INF\jsp\SimpleLoginPortlet_view.jsp file. You can use thehot key Ctrl + Shift + R to open one file/resource quickly................................................................................. 9

    ....................................................................................................................................................................... 9

    4. Refresh and then, run the project.............................................................................................................. 10

    ..........................................................................................................................................................................11

    Exercise 2 Implement coding for SimpleLoginPortlet project......................................................................121. Create database query.............................................................................................................................. 12In MySQL, create new database with name is simplelogin and run the script as following:...........................122. Import the necessary libraries into SimpleLoginPortlet project................................................................... 12There are two libraries needed to import, they are:....................................................................................... 12log4j-1.2.15.jar: this is used for log4j............................................................................................................ 12mysql-connector-java-5.1.8-bin.jar: this is MySQL driver.............................................................................. 12standard.jar: this is used for JSTL................................................................................................................ 12jstl.jar: this is used for JSTL.......................................................................................................................... 12

    Download these *.jar file and copy them to \WEB-INF\lib folder of SimpleLoginPortlet project, then refreshproject again................................................................................................................................................. 12.................................................................................................................................................................... 12Add these libraries into the classpath of project............................................................................................ 13Right click on project name, choose Build Path/Configure Build Path........................................................... 13.................................................................................................................................................................... 133. Create *.properties files............................................................................................................................ 14Create db.properties file:............................................................................................................................. 14Right click on project name, choose New/File and input as following figure:................................................. 14.................................................................................................................................................................... 14The content of db.properties file:................................................................................................................. 14.................................................................................................................................................................... 14Create log4j.properties file:........................................................................................................................... 14

    Get the log4j.properties standard file from rai-server and copy it to the same location with db.properties file...................................................................................................................................................................... 14Search this line ........................................................................................................................................... 14.................................................................................................................................................................... 14and changed to ............................................................................................................................................14.................................................................................................................................................................... 144. Create utility class(s)................................................................................................................................. 15Create Connection class as following:.......................................................................................................... 15Create a new class with name Constants to contain all project constants and the content of this class asfollowing (until now):...................................................................................................................................... 16.................................................................................................................................................................... 16And now the getConnection() method is changed as following:.................................................................... 17.................................................................................................................................................................... 17

    5. Create DTO class(s).................................................................................................................................. 17Create new class as following:..................................................................................................................... 176. Create DAO class(s)................................................................................................................................. 19Create new class as following:..................................................................................................................... 19

    Pageiii

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    4/30

    HandOnLabs_Portlet_Simple Login Portlet App with MySQL_v1.1 RAI Dept, FPT Software HCM

    7. Create BLO class(s).................................................................................................................................. 21Create new class as following:..................................................................................................................... 21................................................................................................................................................................... 22

    8. Create form/bean class(s)......................................................................................................................... 23Create new class as following:..................................................................................................................... 23.................................................................................................................................................................... 249. Modify the JSP page................................................................................................................................. 2510. Modify SimpleLoginPortlet class............................................................................................................. 26

    Add new properties as following:.................................................................................................................. 26.................................................................................................................................................................... 26Modify processAction() method as following:................................................................................................ 26.................................................................................................................................................................... 26Now, add these new constants to Constants class:...................................................................................... 26.................................................................................................................................................................... 26Modify doView() method as following:.......................................................................................................... 27.................................................................................................................................................................... 2711. Deploy and run SimpleLoginPortlet project.............................................................................................. 27Build entire project: right click on project name, choose Refresh, then choose Project menu/Clean submenu.

    ..................................................................................................................................................................... 27.................................................................................................................................................................... 28Export to *.war file and deploy again into uPortal (you dont need to publish a new channel, the changes innew *.war file will be updated automatically into the created channel)........................................................... 28Start server and browse to SimpleLoginPortlet in uPortal............................................................................. 28.................................................................................................................................................................... 28.................................................................................................................................................................... 2812. View log file............................................................................................................................................. 28Log file SimpleLoginPortlet.log is located at ${UPORTAL_TOMCAT_HOME}\ SimpleLoginPortlet.log..........28Exercise 3 Implement a simple validation for SimpleLoginPortlet...............................................................291. With a web application, there is two way to validate the input data. ........................................................... 29Validate at client-side: using Javascript, now a good choice is jQuery.......................................................... 29Validate at server-side: execute validation at server-side............................................................................. 29This lab will execute follow the second way, validate at server-side.............................................................. 292. Modify SimpleLoginForm class to validate the input data........................................................................... 29For validation at server-side, we can put the validation code at any place, but, for clearly and exactly (aboutmeaning), we will implement validation in bean/form class............................................................................ 29Add the validate() method with the content as following:............................................................................... 29.................................................................................................................................................................... 293. Modify a little in doView() method of SimpleLoginPortlet class................................................................... 29.................................................................................................................................................................... 294. Deploy again into uPortal and rerun.......................................................................................................... 30.................................................................................................................................................................... 30

    Pageiv

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    5/30

    Estimated time to complete this lab: 45 minutes.

    This lab will guide you to building a simple login application using: .

    model.

    library to tracking your projects flow.

    DBMS.

    Using file in Java with object and object.

    :

    Log4j: http://www.vipan.com/htdocs/log4jhelp.html

    http://www.vipan.com/htdocs/log4jhelp.htmlhttp://www.vipan.com/htdocs/log4jhelp.html
  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    6/30

    1. Create a new Dynamic Web Project.

    Goining to menu > > . Input the values as followingfigure.

    1. In the next dialog, click button.

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    7/30

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    8/30

    4. Create new portlet object: .

    Going menu > , select node .

    Click on button.

    3. Input information for SimpleLoginPortlet portlet as following:

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    9/30

    Click on Finish button. The structure of the project is:

    6. Modify the JSPs.

    Open the SimpleLoginPortlet\WebContent\WEB-INF\jsp\SimpleLoginPortlet_view.jsp file.You can use the hot key Ctrl + Shift + R to open one file/resource quickly.

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    10/30

    Modify the content of this file as following:

    VIEW MODE

    4. Refresh and then, run the project.

    Righ-click on the project, select .

    If no available server exists, you will add a new server to run project.

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    11/30

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    12/30

    1. Create database query.

    In MySQL, create new database with name is simplelogin and run the script asfollowing:

    -- ------------------------------ Table structure for simpleuser-- ----------------------------DROP TABLE IF EXISTS `simpleuser`;CREATE TABLE simpleuser` (`id` int(11) NOT NULL AUTO_INCREMENT,`sname` varchar(10) NOT NULL,`spass` varchar(10) NOT NULL,PRIMARY KEY (`id`)

    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;-- ------------------------------ Records-- ----------------------------INSERT INTO `simpleuser` VALUES ('1', 'joanie', 'joanie');

    2. Import the necessary libraries into SimpleLoginPortlet project.

    There are two libraries needed to import, they are:

    o : this is used for log4j.

    o : this is MySQL driver.

    o : this is used for JSTL.

    o : this is used for JSTL.

    Download these file and copy them to folder of SimpleLoginPortletproject, then refresh project again.

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    13/30

    Add these libraries into the classpath of project.

    o Right click on project name, choose .

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    14/30

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    15/30

    4. Create utility class(s).

    Create class as following:

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    16/30

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    17/30

    And now the method is changed as following:

    publicstatic java.sql.Connection getConnection() {// load the driver and establish a connection.try {

    String jdbcDriver =props.getProperty(Constants.JDBD_DRIVER);String jdbcUrl =props.getProperty(Constants.JDBD_URL);String jdbcUser =props.getProperty(Constants.JDBD_USER);String jdbcPassword =props.getProperty(Constants.JDBD_PASS);

    Class.forName(jdbcDriver);return (java.sql.Connection) DriverManager.getConnection(jdbcUrl,

    jdbcUser, jdbcPassword);} catch (Exception ex) {

    // in case occur exception, log it.log.error("getConnection", ex);

    }returnnull;

    }

    5. Create DTO class(s).

    Create new class as following:

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    18/30

    Content of this class:

    package rai.dto;/*** This object uses to contain the data of 'simpleuser' table.* @author joanie**/

    publicclass SimpleUserDTO {privateintid;private String sname;private String spass;/*** @return the id*/

    publicint getId() {returnid;

    }/*** @paramid the id to set*/

    publicvoidsetId(int id) {this.id = id;

    }/*** @return the sname*/

    public String getSname() {returnsname;

    }/*** @paramsname the sname to set*/

    publicvoidsetSname(String sname) {this.sname = sname;

    }/*** @return the spass*/

    public String getSpass() {returnspass;

    }/*** @paramspass the spass to set*/

    publicvoidsetSpass(String spass) {this.spass = spass;

    }}

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    19/30

    6. Create DAO class(s).

    Create new class as following:

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    20/30

    Content of this class:

    package rai.dao;

    import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;

    import java.sql.SQLException;import java.util.ArrayList;import java.util.List;

    import org.apache.log4j.Logger;

    import rai.dto.SimpleUserDTO;import rai.util.Constants;

    /*** DAO class for SimpleLoginPortlet.* @author joanie**/

    publicclass SimpleLoginDAO {/*** log property.*/

    privatestatic Logger log= Logger.getLogger("SimpleLoginDAO");

    /*** Get the information of one specify user.* @paramname* @parampass* @return*/

    public List getUser(String name, String pass) {SimpleUserDTO dto;List result = new ArrayList();Connection conn = null;String query = Constants.BLANK_VALUE;ResultSet rs = null;PreparedStatement pStat = null;

    try {// query commandquery = "select * from simpleuser where sname=? and spass=?";// get connectionconn = rai.util.Connection.getConnection();// prepare statementpStat = conn.prepareStatement(query);pStat.setString(1, name);pStat.setString(2, pass);// execute queryrs = pStat.executeQuery();// get resultwhile (rs.next()) {

    dto = new SimpleUserDTO();dto.setId(rs.getInt("id"));

    dto.setSname(rs.getString("sname"));dto.setSpass(rs.getString("spass"));result.add(dto);

    }} catch (Exception sqlEx) {

    log.error("SimpleLoginDAO.getUser " + sqlEx);} finally {

    try {rs.close();pStat.close();conn.close();

    } catch (SQLException sqlEx) {log.error("SimpleLoginDAO.getUser " + sqlEx);

    }}

    return result;

    }}

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    21/30

    7. Create BLO class(s).

    Create new class as following:

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    22/30

    Content of this class:

    package rai.blo;

    import org.apache.log4j.Logger;

    import rai.dao.SimpleLoginDAO;

    import rai.dto.SimpleUserDTO;

    /*** Process business logic for SimpleLoginPortlet.* @author joanie**/

    publicclass SimpleLoginBLO {/*** log property.*/

    privatestatic Logger log= Logger.getLogger("SimpleLoginBLO");

    /*** DAO property.*/

    private SimpleLoginDAO dao = new SimpleLoginDAO();

    /*** Check whether user is valid.* @paramname* @parampass* @return*/

    publicboolean isValidUser(String name, String pass) {log.debug("isValidUser.start");

    boolean res = true;SimpleUserDTO dto = dao.getUser(name, pass);if (dto == null) {

    res = false;}

    log.debug("isValidUser.end");return res;

    }}

    Now, the structure of src folder like as following:

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    23/30

    8. Create form/bean class(s).

    Create new class as following:

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    24/30

    Content of this class:

    package rai.form;

    /*** This object uses to contain the value of JSP form.* @author joanie

    **/

    publicclass SimpleLoginForm {/*** txtName property.*/

    private String txtName;/*** txtPass property.*/

    private String txtPass;/*** @return the txtName*/

    public String getSname() {returntxtName;

    }/*** @paramtxtName the txtName to set*/

    publicvoidsetSname(String txtName) {this.txtName = txtName;

    }/*** @return the txtPass*/

    public String getSpass() {returntxtPass;

    }/*** @paramtxtPass the txtPass to set*/

    publicvoidsetSpass(String txtPass) {

    this.txtPass = txtPass;}

    }

    Now, the structure of src folder like as following:

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    25/30

    9. Modify the JSP page.

    Modify the content of file as following:

    function getForm(namespace, name) { return document.forms[namespace + name];

    }

    function submitForm(namespace, name) { var frm = getForm(namespace, name);

    frm.txtAction.value = "login";frm.submit();

    }${sessionScope.errorMess}

    Username

    Pass

    Create new JSP page named in folder and the content as following:

    function getForm(namespace, name) {

    return document.forms[namespace + name];}

    function submitForm(namespace, name) {var frm = getForm(namespace, name);frm.txtAction.value = "back";frm.submit();

    }

    SimpleLoginPortlet
    Hello ${sessionScope.name}!

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    26/30

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    27/30

    Modify doView() method as following:

    publicvoiddoView(RenderRequest request, RenderResponse response)throws PortletException, IOException {

    PortletRequestDispatcher dispatcher;

    response.setContentType("text/html");

    log.info("doView.start");

    // if user enters this page the first timeif (firstFlag) {

    log.debug("doView.firstFlag = true");dispatcher = getPortletContext().getRequestDispatcher(

    Constants.LOGIN_VIEW_PATH);dispatcher.include(request, response);

    } else {log.debug("doView.firstFlag = false");if (action.equals(Constants.LOGIN_ACTION)) {

    log.debug("doView.action = login");blo = new SimpleLoginBLO();// check whether isValidUserif (blo.isValidUser(form.getSname(), form.getSpass())) {

    // set user namerequest.getPortletSession().setAttribute(

    Constants.NAME_PORT_SESS_ATT, form.getSname(),PortletSession.APPLICATION_SCOPE);

    dispatcher = getPortletContext().getRequestDispatcher(Constants.WELCOME_VIEW_PATH);

    dispatcher.include(request, response);} else {

    // show error message in case user info is invalidrequest.getPortletSession().setAttribute(

    Constants.ERR_MESS_PORT_SESS_ATT,"User info is invalid!",PortletSession.APPLICATION_SCOPE);

    // remove user name if anyrequest.getPortletSession().removeAttribute(

    Constants.NAME_PORT_SESS_ATT);dispatcher = getPortletContext().getRequestDispatcher(

    Constants.LOGIN_VIEW_PATH);

    dispatcher.include(request, response);}

    } elseif (action.equals(Constants.BACK_ACTION)) {// remove error message if anyrequest.getPortletSession().removeAttribute(

    Constants.ERR_MESS_PORT_SESS_ATT);log.debug("doView.action = back");dispatcher = getPortletContext().getRequestDispatcher(

    Constants.LOGIN_VIEW_PATH);dispatcher.include(request, response);

    }}log.info("doView.end");

    }

    11. Deploy and run SimpleLoginPortlet project.

    Build entire project: right click on project name, choose , then.

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    28/30

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    29/30

    1. With a web application, there is two way to validate the input data.

    Validate at client-side: using Javascript, now a good choice is .

    Validate at server-side: execute validation at server-side.

    This lab will execute follow the second way, validate at server-side.

    2. Modify class to validate the input data.

    For validation at server-side, we can put the validation code at any place, but, for clearlyand exactly (about meaning), we will implement validation in class.

    Add the method with the content as following:

    /*** Log property.*/

    privatestatic Logger log=Logger.getLogger("SimpleLoginForm");

    /*** Validate the input data.* @return*/

    public List validate(RenderRequest request, RenderResponse response) {log.debug("validate.start");List errorMess = new ArrayList();// check whether the txtName is blankif (this.txtName.equals(Constants.BLANK_VALUE)) {

    errorMess.add("Please input the Username!");log.debug("validate.errorMess: Please input the Username!");

    }else {request.getPortletSession().setAttribute(

    Constants.NAME_PORT_SESS_ATT, this.txtName,PortletSession.APPLICATION_SCOPE);

    }// check whether the txtPass is blank

    if (this.txtPass.equals(Constants.BLANK_VALUE)) {errorMess.add("Please input the Password!");log.debug("validate.errorMess: Please input the Password!");

    }log.debug("validate.end");// return error message listreturn errorMess;

    }

    3. Modify a little in method of class.

    if (action.equals(Constants.LOGIN_ACTION)) {

    log.debug("doView.action = login");// validate the input dataList errorLst = form.validate(request, response);// in case there is no errorif (errorLst.isEmpty()) {

    blo = new SimpleLoginBLO();

    dispatcher = getPortletContext().getRequestDispatcher(Constants.LOGIN_VIEW_PATH);

    dispatcher.include(request, response);}

    } else {// show error message in case username is blankrequest.getPortletSession().setAttribute(

    Constants.ERR_MESS_PORT_SESS_ATT, errorLst.get(0),PortletSession.APPLICATION_SCOPE);

    dispatcher = getPortletContext().getRequestDispatcher(Constants.LOGIN_VIEW_PATH);

    dispatcher.include(request, response);}

    } elseif (action.equals(Constants.BACK_ACTION)) {

  • 7/31/2019 HandOnLabs_Portlet_Simple Login Portlet App With MySQL_v1.1

    30/30

    4. Deploy again into uPortal and rerun.