EJB实现登录功能

环境

MyEclipse 8.6 + JBoss 6.0 + JDK 1.6.13 + EJB 3.0

 

问题

EJB实现登录

 

解决

 

1.       配置JBoss数据源

a)         数据源参考配置文件

jboss-6.0.0.Final/docs/examples/jca/**-ds.xml

b)         将配置文件放到站点根目录下

jboss-6.0.0.Final/server/default/deploy

c)         将connector加入站点

server/default/lib

d)         配置相关的参数

<jndi-name>MySqlDS</jndi-name>

<connection-url>jdbc:mysql://xxx:3306/xxx</connection-url>

<driver-class>com.mysql.jdbc.Driver</driver-class>

<user-name>xxx</user-name>

<password>xxx</password>

e)         启动JBoss

 

2.       创建数据库表

 

CREATE TABLE user
(
  id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  name varchar(255) DEFAULT NULL,
  password varchar(255) DEFAULT NULL,
);


 

3.       编写实体Bean

 

User.java

 

package com.wgb.bean.entity;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.Id;

import com.wgb.bean.UserListener;

/** 
 * @className: User.java
 * @classDescription: 
 * @function: 
 * @author: Wentasy
 * @createTime: 2012-12-4 下午08:00:32
 * @modifyTime: 
 * @modifyReason: 
 * @since: JDK 1.6
 */
@Entity
@EntityListeners(UserListener.class)
public class User implements Serializable{
	private int id;
	private String name;
	private String password;
	
	@Id
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}


 

 

4.       创建对数据库进行操作的Session Bean

 

UserDao.java

 

package com.wgb.dao;

import java.util.List;

import com.wgb.bean.entity.User;

/** 
 * @className: UserDao.java
 * @classDescription: 
 * @function: 
 * @author: Wentasy
 * @createTime: 2012-12-4 下午08:02:46
 * @modifyTime: 
 * @modifyReason: 
 * @since: JDK 1.6
 */
public interface UserDao {
	public boolean login(String name, String password);
}


 

UserDaoImpl.java

 

package com.wgb.dao.impl;

import java.util.Iterator;
import java.util.List;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.wgb.bean.entity.User;
import com.wgb.dao.UserDao;

/** 
 * @className: UserDaoImpl.java
 * @classDescription: 
 * @function: 
 * @author: Wentasy
 * @createTime: 2012-12-4 下午08:03:25
 * @modifyTime: 
 * @modifyReason: 
 * @since: JDK 1.6
 */
@Stateless
@Remote ({UserDao.class})
public class UserDaoImpl{
	@PersistenceContext
	private EntityManager em;
	@SuppressWarnings("unchecked")
	public boolean login(String name, String password) {
		boolean isValid = false;
		Query query = em.createQuery("from User u where u.name=?1 and u.password=?2");
//		Query query = em.createNativeQuery("select * from user u where u.id = ?");
		
		query.setParameter(1, name);
		query.setParameter(2, password);
		List<User> list = query.getResultList();
		if(list.isEmpty()){
			isValid = false;
		}else{
			isValid = true;
		}
		
//		Iterator<User> it = list.iterator();
//		while(it.hasNext()){
//			User u = it.next();
//			if(u.getName().equals(name) && u.getPassword().equals(password)){
//				isValid = true; 
//			}
//		}
		
		return isValid;
	}
}


 

 

5.       编写登录界面

 

login.jsp

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>登录页面</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
  <h1>登录</h1>
  <form action=<%=path %>/servlet/LoginAction method="post">
  用户名:<input type="text" name="username"><br>
  密    码:<input type="password" name="passwd"><br>
  <input type="submit" value="登录">
  <input type="reset" value="重置">
  </form>
  </body>
</html>


 

 

login_suc.jsp

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>登录成功页面</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
  <P><font color="red" align="center" size="+1">恭喜您!登录成功!</font></P>
 <%
  
	String username = request.getParameter("username");
	String password = request.getParameter("passwd");
%>
<%
	out.println("姓名:" + username);
%>
<br>
<%
	out.println("输入密码:" + password);
%>

  </body>
</html>


 

 

6.       编写对登录进行处理的Servlet

 

LoginAction

 

package com.wgb.bean;

import java.io.IOException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wgb.dao.UserDao;
import com.wgb.dao.impl.UserDaoImpl;


public class LoginAction extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public LoginAction() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("username");
		System.out.println(name);
		String pwd =  request.getParameter("passwd");
		System.out.println(pwd);
		UserDao userDao = null;
		try {
			InitialContext ctx = new InitialContext();
			userDao = (UserDao)ctx.lookup("UserDaoImpl/remote");
		} catch (NamingException e) {
			e.printStackTrace();
		}
		if(userDao.login(name, pwd)){
			request.getRequestDispatcher("/wgb/login_suc.jsp").forward(request, response);
		}else{
			request.getRequestDispatcher("/wgb/login.jsp").forward(request, response);
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
	
}


 

 

web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  	<servlet>
		<description>This is the description of my J2EE component</description>
		<display-name>This is the display name of my J2EE component</display-name>
		<servlet-name>LoginAction</servlet-name>
		<servlet-class>com.wgb.bean.LoginAction</servlet-class>
	</servlet>
  	<servlet-mapping>
		<servlet-name>LoginAction</servlet-name>
		<url-pattern>/servlet/LoginAction</url-pattern>
	</servlet-mapping>
</web-app>


 

 

 

你可能感兴趣的:(EJB实现登录功能)