最近刚学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
即可