I.Requirements
1. Mysql Database and Mysql JDBC Driver library
2. Struts Framework/Libraries
3. Hibernate Framework/Libraries
4. JSTL library
5. Apache Tomcat
6.Java EE
7. Netbeans 6.5 up IDE
II.Database and table
1. Create Database
CREATE DATABASE `test_db` /*!40100 DEFAULT CHARACTER SET latin1 */;
2. Create table
DROP TABLE IF EXISTS `test_db`.`user`; CREATE TABLE `test_db`.`user` ( `usrName` varchar(256) NOT NULL, `passwrd` varchar(256) default NULL, `userId` int(10) unsigned NOT NULL auto_increment, `timeStamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, PRIMARY KEY (`userId`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
III. Web Application
1. Create New Project
a. File -> New Project
b. Choose Project -> Java Web -> Web Application-> Next
c. Name and Location: set Name (mine is WebStruts) and browse designated location ->Next
d. Server and Settings: Select apache tomcat and Java EE version ->Next
f. Choose Framework: Check Hibernate 3.2.5 and Struts 1.3.8 (check TLD also under struts to be use for templation in the future)
g. Click finished
2. Open Index.jsp and modify for Login Page.
a. Add the following tags except the line with jstl/core_rt if JSTL library was not added and if you are not planning to use JSTL
b. Add form inputs; Form Action path (login.do) will be created after a few more steps and should refer from struts.config.xml.
a. Right click on the Project Node -> Select New -> Other
b. New File -> Struts -> Struts Action Bean -> Next
c. New Struts ActionForm Bean: input Class Name (LoginForm) and package(app.struts.form)
d. Click Finish
e. Below is my LoginForm content
public class LoginForm extends org.apache.struts.action.ActionForm {
private String username; private String userpass; public LoginForm() { super(); // TODO Auto-generated constructor stub
}
public String getUsername() { return username;
} public void setUsername(String username) {
this.username = username;
} public String getUserpass() {
return userpass;
}
public void setUserpass(String userpass) { this.userpass = userpass; } }
f. In struts.config.xml, you may see the line below as netbean's automatically produced:
4. Create Struts Action Class
a. Right click on the Project Node -> Select New -> Other
b. New File -> Struts -> Struts Action -> Next
c. New Struts Action: Input class name (LoginAction), package(app.struts.action) and the action path (/login-called in index.jsp form action)
d. Click finish
e. In struts.config.xml, you may see the line below as netbean's automatically produced:
- We will get back on this/modify this action class content after creating another java class for DB access and after preparing Hibernate requirements
4.Create a POJO/bean class for getter and setter that will be use for hibernate. I created a User.java inside the package app.struts.bean
public class User {
public User(){ //Instantiate
}
private String usrName;
private String passwrd;
private Integer userId;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUsrName() {
return usrName;
}
public void setUsrName(String usrName) {
this.usrName = usrName;
}
public String getPasswrd() {
return passwrd;
}
public void setPasswrd(String passwrd) {
this.passwrd = passwrd;
}
}
5. Hibernate Configuration
a. Create the hibernate.config.xml file always inside the
b. Create an hbm file for the POJO class(User.java) you created.
i. Right click on the Project Node-> New -> Other -> Next
ii. Select Hibernate -> Hibernate Mapping Wizard ->Next
iii. Input File Name (User.hbm) and folder inside the package app.struts.bean.hbm
iv. Map to the pojo Class User.java and click Finishv. Add the following line inside the hibernate.cfg.xml
c. You may create the hibernateSessionFactory class in any packages. below is the sample content of the class SessionFactoryUtil.java; I created this inside app.struts.dao
public class SessionFactoryUtil {
public SessionFactoryUtil(){
}
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable e) {
System.err.println("Error in creating SessionFactory object."
+ e.getMessage());
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
5. Create a JSP for Error Result. /jsp/loginError.jsp
6. Create a JSP for success result. WelcomeStruts.jsp
7 Modify Struts.config.xml for LoginAction Result mapping.
8.Class to Access the Database
a. Create a new Java Class
b. Name it as UserDAO.java inside the package app.struts.dao
c. Below is the sample content
public class UserDao {
public UserDao(){ }
/* QJ: Method to validate if user exist from db */
public boolean authenticateUser(String usr, String pwd){
Session session=null;
Transaction tx =null;
int rsCtr;
boolean boolresult=false;
try{
session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
//QJ: Use Hibernate Criteria for more secured functionalities
List rs=(List) session.createCriteria(User.class)
.add(Restrictions.eq("usrName", usr))
.add(Restrictions.eq("passwrd", pwd))
//and .list(); rsCtr=rs.size(); if(rsCtr>0){ boolresult=true; } }catch(HibernateException e){
e.printStackTrace();
}
return boolresult;
}
}
9. Modify Action Class LoginAction.java and add the following
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(true); //QJ: access form bean request LoginForm lf = (LoginForm) form;
UserDao ud = new UserDao();
Boolean canAccept = ud.authenticateUser(lf.getUsername(), lf.getUserpass());
if (canAccept == true) {
session.setAttribute("username", lf.getUsername());
return mapping.findForward(SUCCESS);
}
return mapping.findForward(ERROR); }
10. Right click on the Project Node, select Build and then Run
Could post link for complete project download...in Netbeans?
ReplyDeletethis code not authnticate username and password
ReplyDeleteThis Is Good For Me
ReplyDeletemake this website little wider. we cant get what is written.
ReplyDelete