`
tengmaogen
  • 浏览: 1494 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

EJB3+Jboss7+Struts2整合

阅读更多

最近刚学EJB3   简单的把EJB3和Struts2整合一下吧,服务器用的是Jboss7

 

新建EJB项目 Struts2EJB3

实体User

package com.ejb3.bean;

 

import java.io.Serializable;

 

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.Column;

@Entity

public class User implements Serializable {

private static final long serialVersionUID=1L;

private Integer id;

private String username;

private String password;

public User()

{}

public User(String username,String password)

{

this.username=username;

this.password=password;

}

@Id

@GeneratedValue

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

@Column(nullable=false,length=30)

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

@Column(nullable=false,length=30)

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

@Override

public int hashCode() {

final int prime = 31;

int result = 1;

result = prime * result + ((id == null) ? 0 : id.hashCode());

result = prime * result

+ ((username == null) ? 0 : username.hashCode());

return result;

}

@Override

public boolean equals(Object obj) {

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

User other = (User) obj;

if (id == null) {

if (other.id != null)

return false;

} else if (!id.equals(other.id))

return false;

if (username == null) {

if (other.username != null)

return false;

} else if (!username.equals(other.username))

return false;

return true;

}

@Override

public String toString() {

return "User [id=" + id + ", username=" + username + "]";

}

 

}

新建接口CheckBean

package com.ejb3;

public interface CheckBean {

    boolean check(String name,String password);    //验证用户登陆信息

    public void insertUser(String username,String password);  //注册用户

}

CheckBean实现类CheckBeanImpl

package com.ejb3.impl;

 

import java.util.List;

 

import javax.ejb.Stateless;

import javax.ejb.Remote;

import javax.persistence.PersistenceContext;

import javax.persistence.EntityManager;

import javax.persistence.Query;

 

import com.ejb3.CheckBean;

import com.ejb3.bean.User;

@Stateless

@Remote(CheckBean.class)

public class CheckBeanImpl implements CheckBean {

@PersistenceContext(unitName="struts2EJB")

protected EntityManager em;

 

@Override

public boolean check(String name, String password) {

Query query=em.createQuery("select u from User u where u.username=?1 and u.password=?2");

query.setParameter(1,name);

query.setParameter(2, password);

List<User> users=query.getResultList();

if(users.size()>0)

{

return true;

}

return false;

}

public void insertUser(String username,String password)

{

System.out.println(username);

em.persist(new User(username,password));

}

}

配置persistence.xml

<?xml version="1.0"?>

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">

  <persistence-unit name="struts2EJB" transaction-type="JTA">

    

    <jta-data-source>java:jboss/datasources/MySqlDS</jta-data-source>

    

    <properties>

     <property name="hibernate.hbm2ddl.auto" value="update"/>

     <!-- 调整JDBC抓取数量的大小: Statement.setFetchSize() -->

     <property name="hibernate.jdbc.fetch_size" value="18"/>

     <!-- 调整JDBC批量更新数量 -->

     <property name="hibernate.jdbc.batch_size" value="10"/>

     <!-- 显示最终执行的SQL -->

     <property name="hibernate.show_sql" value="true"/>

     <!-- 格式化显示的SQL -->

     <property name="hibernate.format_sql" value="true"/>

     <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"></property>

    </properties>

  </persistence-unit>

</persistence>

 

将此项目导出  成jar 为Struts2EJB3.jar  发布到Jboss

 

接下来实现Web客户端

新建项目名称为Struts2EJB3Web的web项目

将必要的struts2的包导入到lib中,还有将Struts2EJB3.jar也导入到lib中

还有将jboss7/bin/client/jboss-client.jar也导入到lib中

 

写一个字符过滤类以免出现乱码  CharacterEncodingFilter

package com.ejb3.utils;

 

 

import java.io.IOException;

 

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;

 

public class CharacterEncodingFilter implements Filter {

protected String encoding = null;// 定义编码格式变量

protected FilterConfig filterConfig = null;// 定义过滤器配置对象

 

public void init(FilterConfig filterConfig) throws ServletException {

this.filterConfig = filterConfig; // 初始化过滤器配置对象

this.encoding = filterConfig.getInitParameter("encoding");// 获取配置文件中指定的编码格式

//System.out.println(encoding);

}

 

// 过滤器的接口方法,用于执行过滤业务

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException {

if (encoding != null) {

HttpServletRequest hsRequest = (HttpServletRequest) request;// 获取HttpServletRequest对象

String requestedWith = hsRequest.getHeader("x-requested-with");// 获取请求的发出者,该信息由Ajax发送POST请求时设置

String contentType = request.getContentType();// 获取请求的内容类型

if (null != contentType

&& contentType

.equalsIgnoreCase("application/x-www-form-urlencoded")

&& null != requestedWith && requestedWith.equals("ajax")) {

request.setCharacterEncoding("UTF-8");// 设置编码为UTF-8

 

} else {

request.setCharacterEncoding(encoding); // 设置请求的编码

response.setContentType("text/html; charset=" + encoding);// 设置应答对象的内容类型(包括编码格式)

}

}

//System.out.println(encoding);

chain.doFilter(request, response); // 传递给下一个过滤器

}

 

public void destroy() {

this.encoding = null;

this.filterConfig = null;

}

}

 

配置web.xml文件

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

id="WebApp_ID" version="3.0">

<display-name>Struts2EJB3Web</display-name>

 

<filter>

<filter-name>CharacterEncodingFilter</filter-name>

<filter-class>com.ejb3.utils.CharacterEncodingFilter</filter-class>

<init-param>

<param-name>encoding</param-name>

<param-value>UTF-8</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>CharacterEncodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<filter>

<filter-name>struts2</filter-name>

<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

 

</filter>

<filter-mapping>

<filter-name>struts2</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

 

</web-app>

 

struts.xml文件

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC

    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<constant name="struts.custom.i18n.resources" value="GlobalMessage" />

<constant name="struts.locale" value="zh_CN"></constant>

<constant name="struts.i18n.encoding" value="UTF-8"></constant>

<constant name="struts.devMode" value="true" />

<package name="struts2" extends="struts-default">

      <action name="*" class="com.ejb3.LoginAction" method="{1}">

        <result name="success">success.jsp</result>

         <result name="fail">fail.jsp</result>

    </action>

</package>

</struts>

 

接下来写Action类  LoginAction

package com.ejb3.action;

 

import java.io.UnsupportedEncodingException;

import java.util.Hashtable;

 

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.naming.NamingException;

import javax.servlet.http.HttpServletRequest;

 

import org.apache.struts2.ServletActionContext;

 

import com.ejb3.CheckBean;

 

import com.opensymphony.xwork2.ActionSupport;

 

public class LoginAction extends ActionSupport {

private String username;

private String password;

 

public String getUsername() {

return username;

}

 

public void setUsername(String username) {

this.username = username;

}

 

public String getPassword() {

return password;

}

 

public void setPassword(String password) {

this.password = password;

}

 

public String login() {

CheckBean dao = null;

Hashtable<String, String> jndiProperties = new Hashtable<String, String>();

jndiProperties.put(Context.URL_PKG_PREFIXES,

"org.jboss.ejb.client.naming");

try {

Context context = new InitialContext(jndiProperties);

 

final String appName = "";

final String moduleName = "Struts2EJB3";

final String distinctName = "";

 

Object obj = context.lookup("ejb:" + appName + "/" + moduleName

+ "/" + distinctName + "/CheckBeanImpl!com.ejb3.CheckBean");

 

dao = (CheckBean) obj;

} catch (NamingException e) {

e.printStackTrace();

}

if (dao.check(username, password)) {

return "success";

}

return "fail";

}

 

public String register() {

CheckBean dao = null;

Hashtable<String, String> jndiProperties = new Hashtable<String, String>();

jndiProperties.put(Context.URL_PKG_PREFIXES,

"org.jboss.ejb.client.naming");

try {

Context context = new InitialContext(jndiProperties);

 

final String appName = "";

final String moduleName = "Struts2EJB3";

final String distinctName = "";

 

Object obj = context.lookup("ejb:" + appName + "/" + moduleName

+ "/" + distinctName + "/CheckBeanImpl!com.ejb3.CheckBean");

 

dao = (CheckBean) obj;

} catch (NamingException e) {

e.printStackTrace();

}

dao.insertUser(username, password);

return "success";

}

}

 

接下来写web页面

register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<form action="register" method="post">

name:<input type="text" name="username" /><br> password:<input

type="password" name="password" /><br> <input type="submit"

value="submit">

</form>

</body>

</html>

 

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >

<%@ taglib prefix="s" uri="/struts-tags"%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title></title>

</head>

<body>

<form action="login" >

name:<input type="text" name="username" /><br> password:<input

type="password" name="password" /><br> <input type="submit"

value="submit">

</form>

</body>

</html>

 

还有就是要先建jboss-ejb-client.properties文件  并把它放到src目录下

jboss-ejb-client.properties  内容如下

remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false

remote.connections=default

remote.connection.default.host=localhost

remote.connection.default.port = 4447

remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false

 

最后一步要配置Jboss7服务器编码  否则中文会出现乱码

 

<system-properties>

     <property name="org.apache.catalina.connector.URI_ENCODING" value="UTF-8"/>

     <property name="org.apache.catalina.connector.USE_BODY_ENCODING_FOR_QUERY_STRING" value="true"/>

</system-properties>

将以上内容插入到standalone.xml文件中 <extensions> </extensions> 节点之后

 

 

最后将Web项目 导报为war  部署到Jboss中

 

在浏览器中输入   localhost:8080/Struts2EJB3Web/register.jsp

即可 

分享到:
评论

相关推荐

    spring+struts+ejb整合

    spring+struts+ejb整合 版本 jboss-5.1.0.GA struts-2.2.3 spring-3.2.4.RELEASE

    EJB+struts2整合示例

    完全自己做的,直接放到JBOSS....../deploy目录可以直接运行,给开发者一个可以运行的例子,希望可以给你们带来帮助。。。

    经典JAVA.EE企业应用实战.基于WEBLOGIC_JBOSS的JSF_EJB3_JPA整合开发.pdf

    中文名: 经典Java EE企业应用实战--基于WebLogic/JBoss的JSF+EJB 3+JPA整合开发 原名: 经典Java EE企业应用实战--基于WebLogic/JBoss的JSF+EJB 3+JPA整合开发 作者: 李刚 资源格式: PDF 版本: 第一版 出版社: 电子...

    EJB3与Struts与Spring整合开发(SSE)

    EJB3与Struts与Spring整合开发(SSE),很不错的,可以借鉴下,提意见(EJB Bean放在JBoss服务器上,Web放在Tomcat服务器上)这入门程序,主要看配置

    struts2.1.6+spring2.0+hibernate3.2常用配置包

    最近温习ssh2整合编程,顺便浏览下struts2有什么更新的消息,下载了新版本的struts2的2.1.8.1版,使用的是MyEclipse8.0开发,但是问题就随之而来了。MyEclipse8.0中自带的struts2版本是2.1.6,spring版本有2.0,2.5...

    电子宠物管理

    struts1.2 + ejb3.0 +spring2.0 整合,使用 jboss4.2.0 与 tomcat 服务器, 连接 mysql 数据库。jar 包什么都在里面,解压后直接将 petejb 工程部署到 jboss 上并启动,然后将 petweb 工程部署到 tomcat6.0 即可。...

    hibernate中文文档

    1. Read 第 1 章 教程 for a tutorial with step-by-step instructions. The source code for ...7. Hibernate 网站的社区是讨论关于设计模式以及很多整合方案(Tomcat、JBoss AS、Struts、EJB 等)的好地方。

    Hibernate v3.2中文参考手册

    &lt;br&gt;Hibernate网站的“社区(Community Area)”是讨论关于设计模式以及很多整合方案(Tomcat, JBoss AS, Struts, EJB,等等)的好地方。 &lt;br&gt;如果你有问题,请使用Hibernate网站上链接的用户论坛。我们也提供一...

    Hibernate3.2官方中文参考手册

    &lt;br&gt;Hibernate网站的“社区(Community Area)”是讨论关于设计模式以及很多整合方案(Tomcat, JBoss AS, Struts, EJB,等等)的好地方。 &lt;br&gt;如果你有问题,请使用Hibernate网站上链接的用户论坛。我们也提供一...

    计算机求职意向简历.pdf

    2.能熟练的整合Spring+Struts+Hibernate(SSH)三大开源框架; 3.能熟练的应用各种常见的设计模式:工厂模式、单例模式、缺省适配器模式、不变模式、装饰模式、代理模式、MVC、SpringIoC等; 4.熟练应用Oracle、MySQL...

Global site tag (gtag.js) - Google Analytics