Struts2.3.16Spring4.0.6Hibernate4.3.5项目

时间:2022-01-28 06:18:38

项目结构

Struts2.3.16Spring4.0.6Hibernate4.3.5项目

Struts2.3.16Spring4.0.6Hibernate4.3.5项目

数据库使用的是sql server2008

创建表

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[sys_czy](
[czyID_i] [int] IDENTITY(1,1) NOT NULL,
[Czyxm_c] [varchar](32) NOT NULL,
[dlID_c] [varchar](16) NOT NULL,
[Dlmm_c] [varchar](32) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'操作员标识' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'sys_czy', @level2type=N'COLUMN',@level2name=N'czyID_i'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'操作员姓名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'sys_czy', @level2type=N'COLUMN',@level2name=N'Czyxm_c'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'登陆标识' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'sys_czy', @level2type=N'COLUMN',@level2name=N'dlID_c'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'登陆密码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'sys_czy', @level2type=N'COLUMN',@level2name=N'Dlmm_c'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'操作员' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'sys_czy'
GO


配置文件说明

web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
	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_3_0.xsd">
	<display-name></display-name>
	
	<!-- 添加对spring的支持 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!-- 添加对struts2支持 -->
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
		<!-- 当hibernate+spring配合使用的时候,如果设置了lazy=true,那么在读取数据的时候,当读取了父数据后,  
     		hibernate会自动关闭session,这样,当要使用子数据的时候,系统会抛出lazyinit的错误,  
      		这时就需要使用spring提供的 OpenSessionInViewFilter,OpenSessionInViewFilter主要是保持Session状态  
      		知道request将全部页面发送到客户端,这样就可以解决延迟加载带来的问题 -->
	<filter>
		<filter-name>openSessionInViewFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
		<init-param>
			<param-name>singleSession</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<filter-mapping>
		<filter-name>openSessionInViewFilter</filter-name>
		<url-pattern>*.do,*.action</url-pattern>
	</filter-mapping>
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
	
<struts>
	<include file="struts-default.xml"/>
	<constant name="struts.i18n.encoding" value="UTF-8"/>
	<constant name="struts.action.extension" value="action"/>
	<constant name="struts.serve.static.browserCache" value="false"/>
	<package name="s2sh" namespace="/user" extends="struts-default">
		<action name="login" method="login" class="loginAction"> <!--name 对应的是from表单action对应的值 method对应的是action类中的login方法也可以这样 <span style="color: rgb(94, 94, 94); font-family: Verdana, Helvetica, Arial; font-size: 13px; line-height: 18px; text-align: justify; ">method属性值为一个表达式{1},表示它的值是name属性值中第一个*的值。例如:用户请求URL为user_login.action时,将调用到UserAction类的login方法;用户请求URL为user_regist.action时,将调用到UserAction类的regist方法。class对应spring的配置文件applicationContext.xml用户注册的ACTION的id--></span>
			<result name="success">/success.jsp</result>
			<result name="error">/login.jsp</result>
		</action>
	</package>
	<package name="s2s4h4" namespace="/user" extends="struts-default">
		<action name="register" method="register" class="registerAction">
			<result name="success">/login.jsp</result>
			<result name="error">/register.jsp</result>
		</action>
	</package>
</struts>

db.properties
连接数据配置属性
db.driverClassName=com.microsoft.sqljdbc.jdbc.SQLServerDriver
db.url=jdbc:sqlserver://127.0.0.1:1433;databaseName=KJDZSW
db.username=sa
db.password=sqlserver

hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC  
         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
		<property name="jdbc.batch_size">20</property>
		<property name="connection.autocommit"></property>
		<!-- 显示sql语句 -->
		<property name="show_sql">true</property>
		<property name="connection.useUnicode">true</property>
		<property name="connection.characterEncoding">UTF-8</property>
		<!-- 缓存设置 -->
		<property name="cache.provider_configuration_file_resource_path">/ehcache.xml</property>
		<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
		<property name="cache.use_query_cache">true</property>
<span style="white-space:pre">		</span><!-- 指定hibernate映射文件路径-->
		<mapping resource="com/bsd/s2s4h4/entity/Sys_czy.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

类代码

loginAction类

package com.bsd.s2s4h4.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.User;
import org.apache.struts2.ServletActionContext;

import com.bsd.s2s4h4.entity.Sys_czy;
import com.bsd.s2s4h4.service.UserService;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -64678345374645373L;
	private UserService userService;
	public Sys_czy user1;
	
	public String login(){
		HttpServletRequest request=ServletActionContext.getRequest();
		Sys_czy user=userService.findUserByUsernameAndPassword(user1.getUsername(), user1.getPassword());
		if(user!=null){
			request.setAttribute("username", user.getUsername());
			return SUCCESS;
		}else{
			return ERROR;
		}
	}
	
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public Sys_czy getUser1() {
		return user1;
	}

	public void setUser1(Sys_czy user1) {
		this.user1 = user1;
	}

}


registerAction类

package com.bsd.s2s4h4.action;

import com.bsd.s2s4h4.entity.Sys_czy;
import com.bsd.s2s4h4.service.UserService;
import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport {
	private Sys_czy user;

	private UserService userService;
	
	public String register(){
		try {
			userService.add(user);
			return SUCCESS;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return ERROR;
		}
	}
	public Sys_czy getUser() {
		return user;
	}
	
	public void setUser(Sys_czy user) {
		this.user = user;
	}
	public UserService getUserService() {
		return userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
}

registerAction-validation.xml注册时的验证

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN"
	"http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
<validators>
	<!-- 添加对注册账号的验证 -->
	<field name="user.czyxm_c">
		<field-validator type="requiredstring">
			<param name="trim">true</param>
			<message>姓名不能为空</message>
		</field-validator>
		<field-validator type="regex">
			<param name="expression"><![CDATA[([\s]{0,})]]></param>
			<message>姓名输入不合法,不能字符串为空或者都是空白字符</message>
		</field-validator>
	</field>
	<field name="user.dlID_c">
		<field-validator type="requiredstring">
			<param name="trim">true</param>
			<message>用户名不能为空</message>
		</field-validator>
		<field-validator type="regex">
			<param name="expression"><![CDATA[(\w{6,16})]]></param>
			<message>用户名输入不合法,必须为长度在6~16之间的字符</message>
		</field-validator>
	</field>
	<field name="user.dlmm_c">
		<field-validator type="requiredstring">
			<param name="trim">true</param>
			<message>密码不能为空</message>
		</field-validator>
		<field-validator type="regex">
			<param name="expression"><![CDATA[(\w{6,16})]]></param>
			<message>密码输入不合法,必须在6到16直接长度的字符</message>
		</field-validator>
	</field>
</validators>

BaseDAO类

package com.bsd.s2s4h4.dao;

import java.io.Serializable;
import java.util.List;

/** 
 * 通用Dao父类实现的接?口,只提供常见的一些功能,其它特殊的功能,可以在子接口中定义。 
 * 事务也在需要的时候加到实现类中 
 * 
 * @param <T> 实体类型 
 */ 
public interface BaseDAO<T> {
	public T get(String hql,Object[] param);
	
	public List<T> find(String hql,Object[] param);
	
	public Serializable add(Object suser);
}

BaseDaoImpl类

package com.bsd.s2s4h4.daoImpl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.bsd.s2s4h4.dao.BaseDAO;

public class BaseDAOImol<T> implements BaseDAO<T> {

	public SessionFactory sessionFactory;
	
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}


	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}


	@Override
	public T get(String hql, Object[] param) {
		// TODO Auto-generated method stub
		List<T> list=this.find(hql,param);
		if(list!=null && list.size()>0){
			return list.get(0);
		}else
			return null;
	}

	private Session getCurrentSession(){
		return sessionFactory.getCurrentSession();
	}
	@Override
	public List<T> find(String hql, Object[] param) {
		// TODO Auto-generated method stub
		Query q=this.getCurrentSession().createQuery(hql);
		if(param!=null && param.length>0){
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return q.list();
	}


	@Override
	public Serializable add(Object suser) {
		// TODO Auto-generated method stub
		return this.getCurrentSession().save(suser);
	}

}


Sys_czy类


package com.bsd.s2s4h4.entity;

public class Sys_czy {
	private Integer id;
	private String name;
	private String username;
	private String password;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	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;
	}
	
}

Sys_czy.hbm.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC  
                            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
                            "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >  
<hibernate-mapping package="com.bsd.s2s4h4.entity">
	<class name="Sys_czy" table="Sys_czy" >  
</pre><pre name="code" class="html"><!--name对应Sys_czy实体类定义的属性 column对应表的字段名-->
		<id name="id" column="czyID_i" type="java.lang.Integer">
			<generator class="native"/>
		</id>
		<property name="name" column="czyxm_c" type="java.lang.String" not-null="true" length="32"/>
		<property name="username" column="dlID_c" type="java.lang.String" not-null="true" length="32"/>
		<property name="password" column="dlmm_c" type="java.lang.String" not-null="true" length="124"/>
	</class>
</hibernate-mapping>

UserService 类


package com.bsd.s2s4h4.service;

import com.bsd.s2s4h4.entity.Sys_czy;

public interface UserService {
	public Sys_czy findUserByUsernameAndPassword(String username,String password);

	public void add(Object user);
}

UserServiceImpl类


package com.bsd.s2s4h4.serviceImpl;

import org.springframework.beans.BeanUtils;

import com.bsd.s2s4h4.dao.BaseDAO;
import com.bsd.s2s4h4.entity.Sys_czy;
import com.bsd.s2s4h4.service.UserService;

public class UserServiceImpl implements UserService {

	private BaseDAO<Sys_czy> baseDao;
	@Override
	public Sys_czy findUserByUsernameAndPassword(String username, String password) {
		// TODO Auto-generated method stub
		return baseDao.get(" from Sys_czy where dlID_c=? and Dlmm_c=?", new Object[] { username, password });
	}
	public BaseDAO<Sys_czy> getBaseDao() {
		return baseDao;
	}
	public void setBaseDao(BaseDAO<Sys_czy> baseDao) {
		this.baseDao = baseDao;
	}
	@Override
	public void add(Object obj) {
		// TODO Auto-generated method stub
		baseDao.add(obj);
	}

}


JSP页面


login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
System.out.print(basePath);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<form action="${pageContext.request.contextPath}/user/login.action" method="get"><!--action使用绝对路径-->
		username:<input type="text" name="user1.username"><!--user1.username 封装对象loginAction可直接使用public Sys_czy user1;user1就可获得username值-->
		password:<input type="password" name="user1.password">
		<input type="submit" value="提交">
	</form>
</html>

register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<form action="user/register.action"><!--action使用相对路径-->
		<table align="center">
			<tr>
				<td>姓名:</td>
				<td><input type="text" name="user.name"></td>
			</tr>
			<tr>
				<td>用户名:</td>
				<td><input type="text" name="user.username"></td>
			</tr>
			<tr>
				<td>密码:</td>
				<td><input type="password" name="user.password"></td>
			</tr>
			<tr >
				<td colspan="2" align="center"><input type="submit" value="提交"></td>
				
			</tr>
		</table>
	</form>
</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
	Object obj=request.getAttribute("username");
	System.out.print(obj.toString());
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	欢迎<%=obj.toString() %>
</body>
</html>


下载地址http://download.csdn.net/detail/strutce/7677641