一、配置Struts
首先在web.xml中配置Struts核心过滤器和过滤器映射
web.xml代码如下:
<!-- 定义Struts 2 的核心控制器 -->
<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>/*.action</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.apache.struts2.dispatcher.ng.listener.StrutsListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
新建包com.ssh.action,建立BaseAction,继承ActionSupport,实现接口ServletRequestAware,ServletResponseAware,ServletContextAware,SessionAware
package com.ssh.action;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
public class BaseAction extends ActionSupport
implements ServletRequestAware,ServletResponseAware,ServletContextAware,SessionAware{
private static final long serialVersionUID = 4565394360208096613L;
protected HttpServletRequest request;
protected HttpServletResponse response;
protected ServletContext context;
protected Map<String,Object>session;
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
@Override
public void setServletContext(ServletContext context) {
this.context = context;
}
@Override
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
}
编写测试Struts的Action,在com.ssh.action包内建立LoginAction类,继承BaseAction类,作为Struts的测试
LoginAction类的代码如下:
package com.ssh.action;
public class LoginAction extends BaseAction{
private static final long serialVersionUID = -6144396976094110475L;
public String execute() throws Exception{
return "success";
}
}
在struts.xml文件中添加对LoginAction的配置
struts.xml文件配置如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.objectFactory" value="spring" />
<constant name="struts.i18n.encoding" value="UTF-8" />
<constant name="struts.i18n.reload" value="false" />
<constant name="struts.configuration.xml.reload" value="false" />
<constant name="struts.custom.i18n.resources" value="globalMessages" />
<constant name="struts.action.extension" value="action,," />
<constant name="struts.convention.package.locators.basePackage"
value="com.ssh.action" />
<constant name="struts.convention.result.path" value="/" />
<constant name="struts.serve.static" value="true" />
<constant name="struts.serve.static.browserCache" value="false" />
<package name="login" extends="struts-default">
<action name="login" class="com.ssh.action.LoginAction">
<result name="success">/WEB-INF/jsp/welcome.jsp</result>
</action>
</package>
</struts>
二、配置spring
在applicationContext.xml文件中配置spring,添加ActionBean的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd ">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
</bean>
</beans>
打开web.xml文件,在web.xml文件中配置spring监听器
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- ssh 中文过滤 -->
<filter>
<filter-name>characterEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 对Spring 容器进行实例化 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.apache.struts2.dispatcher.ng.listener.StrutsListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
三、配置hibernate
在src文件下建立hibernate.cfg.xml文件
hibernate.cfg.xml代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306;databaseName=test</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.config.*"/>
</session-factory>
</hibernate-configuration>
四、建立数据库和数据表
此处采用MySQL,不同的数据库连接驱动和URL不同,jar也不同。在MySQL中建立test数据库,创建user表,包括id,username,password等属性,插入一条数据。
五、创建实体类
创建包com.ssh.model,创建User类,实现接口Serializable
package com.ssh.model;
import java.io.Serializable;
public class User implements Serializable{
private static final long serialVersionUID = 6120793500259112385L;
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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 static long getSerialversionuid() {
return serialVersionUID;
}
}
添加映射文件,创建包com.ssh.config,创建User.hbm.xml文件,作为User 与数据表之间的映射文件
<?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.ssh.model">
<class name="User" table="user">
<id name="id" type="integer">
<column name="id"></column>
<generator class="native"></generator>
</id>
<property name="username" type="string">
<column name="username"></column>
</property>
<property name="password" type="string">
<column name="password"></column>
</property>
</class>
</hibernate-mapping>
添加包名是为了下面class的name属性可以直接使用类名,不用带着包名。generator属性为主键生成机制,常用的有3种(native,identity和sequence),mysql使用identity,也可以直接使用native(根据数据库的默认设定而定)。
重新写LoginAction类,加入数据库信息验证,采用分层结构,model持久层,dao模型层,service业务控制层。从action开始写,需要什么业务就定义出来,生成service 接口,然后实现接口,同样用相同的方法定义dao 层。
LoginAction:
package com.ssh.action;
import com.ssh.service.UserService;
public class LoginAction extends BaseAction{
private static final long serialVersionUID = -6144396976094110475L;
private UserService userService;
private String username;
private String password;
public String execute() throws Exception{
try{
if(userService.login(username, password))
return "success";
else
return "error";
}catch(Exception e){
e.printStackTrace();
}
return "error";
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
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 static long getSerialversionuid() {
return serialVersionUID;
}
}
生成service接口
UserService:
package com.ssh.service;
public interface UserService {
public boolean login(String username,String password);
}
实现service接口
UserServiceImpl:
package com.ssh.service.impl;
import com.ssh.dao.UserDao;
import com.ssh.model.User;
import com.ssh.service.UserService;
public class UserServiceImpl implements UserService{
private UserDao userDao;
@Override
public boolean login(String username, String password) {
// TODO Auto-generated method stub
User user = userDao.findUserByName(username);
if(user != null){
if(password != null){
if(password.equals(user.getPassword()))
return true;
}
}
return false;
}
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
}
同样,生成dao 接口
UserDao:
package com.ssh.dao;
import com.ssh.model.User;
public interface UserDao {
public User findUserByName(String username);
}
实现dao接口,继承HibernateDaoSupport
UserDaoImpl:
package com.ssh.dao.impl;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.ssh.dao.UserDao;
import com.ssh.model.User;
public class UserDaoImpl extends HibernateDaoSupport implements UserDao{
@SuppressWarnings("unchecked")
@Override
public User findUserByName(String username) {
// TODO Auto-generated method stub
List<User> list;
String hql = "from User u where u.username=?";
list = this.getHibernateTemplate().find(hql,username);
if(list != null){
return list.get(0);
}
return null;
}
}
六、建立JSP测试页面,在/WEB-INF下建立jsp文件夹,在其中建立login.jsp、welcome.jsp
login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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>My JSP 'login.jsp' starting page</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>
<form action="login" method="post">
Username:<input type="text" name="username"/><br/>
Password:<input type="password" name="password"/><br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
登录成功跳转
welcom.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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>welcome</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>
welcome!<s:property value="username"/>
</body>
</html>
重新写Struts配置文件
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.objectFactory" value="spring" />
<constant name="struts.i18n.encoding" value="UTF-8" />
<constant name="struts.i18n.reload" value="false" />
<constant name="struts.configuration.xml.reload" value="false" />
<constant name="struts.custom.i18n.resources" value="globalMessages" />
<constant name="struts.action.extension" value="action,," />
<constant name="struts.convention.package.locators.basePackage"
value="com.ssh.action" />
<constant name="struts.convention.result.path" value="/" />
<constant name="struts.serve.static" value="true" />
<constant name="struts.serve.static.browserCache" value="false" />
<package name="login" extends="struts-default">
<action name="loginform">
<result name="success">/WEB-INF/jsp/login.jsp</result>
</action>
<action name="login" class="LoginAction">
<result name="success">/WEB-INF/jsp/welcome.jsp</result>
</action>
</package>
</struts>
基本的ssh框架配置就完成了。
ssh框架的构建配置比较麻烦,需要细心和耐心,一旦有一个地方配置出错,就会运行不起来。