EJB实现登录功能

101 篇文章 1 订阅
90 篇文章 1 订阅

环境

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>


 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
对于一个完整的计件工资系统,需要设计和实现很多不同的功能,因此这里只能提供一些代码实现的思路和示例,不能提供完整的代码实现。以下是一个简单的示例: 1. 员工信息管理模块: 在EasyUI中,可以使用datagrid组件来实现员工信息的管理。具体地,可以使用以下代码实现一个最基本的员工信息管理界面: ```html <table id="employee-grid"></table> ``` ```javascript $('#employee-grid').datagrid({ url: 'employee/list', fit: true, fitColumns: true, rownumbers: true, singleSelect: true, columns: [[ {field: 'id', title: 'ID', width: 100}, {field: 'name', title: '姓名', width: 100}, {field: 'department', title: '部门', width: 100}, {field: 'position', title: '职务', width: 100} ]] }); ``` 在后台,可以使用EJB框架来实现员工信息的管理。具体地,可以定义一个Employee实体类和一个EmployeeService服务类,如下: ```java @Entity public class Employee { @Id private Long id; private String name; private String department; private String position; // 省略getter和setter方法 } @Stateless public class EmployeeService { @PersistenceContext private EntityManager entityManager; public List<Employee> findAll() { TypedQuery<Employee> query = entityManager.createQuery("SELECT e FROM Employee e", Employee.class); return query.getResultList(); } } ``` 在EmployeeService中,可以定义一个findAll方法,用于查询所有的员工信息。在该方法中,使用EntityManager对象执行JPQL查询语句,返回一个包含所有员工信息的List对象。 2. 工资计算模块: 在EJB框架中,可以定义一个计算工资的Bean组件。具体地,可以定义一个WageCalculatorBean组件,如下: ```java @Stateless public class WageCalculatorBean { public double calculateWage(double pieceCount, double unitPrice) { return pieceCount * unitPrice; } } ``` 在WageCalculatorBean中,可以定义一个calculateWage方法,用于计算员工的工资。在该方法中,根据员工的计件数和单价计算出员工的工资,并将计算结果返回。 3. 工资发放模块: 在EasyUI中,可以使用datagrid组件来实现工资的发放和管理。具体地,可以使用以下代码实现一个最基本的工资管理界面: ```html <table id="wage-grid"></table> ``` ```javascript $('#wage-grid').datagrid({ url: 'wage/list', fit: true, fitColumns: true, rownumbers: true, singleSelect: true, columns: [[ {field: 'id', title: 'ID', width: 100}, {field: 'employee', title: '员工姓名', width: 100}, {field: 'wage', title: '工资', width: 100}, {field: 'date', title: '发放日期', width: 100} ]] }); ``` 在后台,可以使用EJB框架来实现工资的发放和管理。具体地,可以定义一个Wage实体类和一个WageService服务类,如下: ```java @Entity public class Wage { @Id private Long id; @ManyToOne private Employee employee; private double wage; private Date date; // 省略getter和setter方法 } @Stateless public class WageService { @PersistenceContext private EntityManager entityManager; public List<Wage> findAll() { TypedQuery<Wage> query = entityManager.createQuery("SELECT w FROM Wage w", Wage.class); return query.getResultList(); } public void saveWage(Wage wage) { entityManager.persist(wage); } } ``` 在WageService中,可以定义一个findAll方法,用于查询所有的工资信息。在该方法中,使用EntityManager对象执行JPQL查询语句,返回一个包含所有工资信息的List对象。另外,还可以定义一个saveWage方法,用于保存工资信息。在该方法中,使用EntityManager对象将工资信息保存到数据库中。 以上是一个简单的计件工资系统的实现示例,实际上还需要考虑很多更复杂的问题,如数据的校验、权限的管理、异常的处理等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值