Struts2+Spring4 +Hibernate4
首先看看建立项目的框架
第一步 建立web项目
第二步 导入相对应需要的jar包(放在项目WEB-INFO/lib下)
需要导入Spring需要的,Struts2需要的,Hibernate需要的,mysQL连接驱动;
第三步 配置ssh各个的xml文件;
第四步 将log4j.dtd与log4j.xml放在WEB-INFO下:
log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'> <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%c %d{yyyy-MM-dd HH:mm:ss} -- %p -- %m%n" />
</layout>
</appender> <appender name="DEBUG" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="${sshWeb.root}/sshWeb-debug.log" />
<param name="Append" value="true" />
<param name="MaxFileSize" value="10240KB" />
<param name="MaxBackupIndex" value="1000" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%c %d{yyyy-MM-dd HH:mm:ss} -- %p -- %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="DEBUG" />
<param name="LevelMax" value="DEBUG" />
</filter>
</appender> <appender name="INFO" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="${sshWeb.root}/sshWeb-info.log" />
<param name="Append" value="true" />
<param name="MaxFileSize" value="10240KB" />
<param name="MaxBackupIndex" value="1000" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%c %d{yyyy-MM-dd HH:mm:ss} -- %p -- %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="INFO" />
<param name="LevelMax" value="INFO" />
</filter>
</appender> <appender name="WARN" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="${sshWeb.root}/sshWeb-warn.log" />
<param name="Append" value="true" />
<param name="MaxFileSize" value="10240KB" />
<param name="MaxBackupIndex" value="1000" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%c %d{yyyy-MM-dd HH:mm:ss} -- %p -- %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="WARN" />
<param name="LevelMax" value="WARN" />
</filter>
</appender> <appender name="ERROR" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="${sshWeb.root}/sshWeb-error.log" />
<param name="Append" value="true" />
<param name="MaxFileSize" value="10240KB" />
<param name="MaxBackupIndex" value="1000" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%c %d{yyyy-MM-dd HH:mm:ss} -- %p -- %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="ERROR" />
<param name="LevelMax" value="ERROR" />
</filter>
</appender> <root>
<priority value="INFO" />
<appender-ref ref="STDOUT" />
<appender-ref ref="DEBUG" />
<appender-ref ref="INFO" />
<appender-ref ref="WARN" />
<appender-ref ref="ERROR" />
</root> </log4j:configuration>
log4j.dtd
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--> <!-- Authors: Chris Taylor, Ceki Gulcu. --> <!-- Version: 1.2 --> <!-- A configuration element consists of optional renderer
elements,appender elements, categories and an optional root
element. --> <!ELEMENT log4j:configuration (renderer*, throwableRenderer?,
appender*,plugin*, (category|logger)*,root?,
(categoryFactory|loggerFactory)?)> <!-- The "threshold" attribute takes a level value below which -->
<!-- all logging statements are disabled. --> <!-- Setting the "debug" enable the printing of internal log4j logging -->
<!-- statements. --> <!-- By default, debug attribute is "null", meaning that we not do touch -->
<!-- internal log4j logging settings. The "null" value for the threshold -->
<!-- attribute can be misleading. The threshold field of a repository -->
<!-- cannot be set to null. The "null" value for the threshold attribute -->
<!-- simply means don't touch the threshold field, the threshold field -->
<!-- keeps its old value. --> <!ATTLIST log4j:configuration
xmlns:log4j CDATA #FIXED "http://jakarta.apache.org/log4j/"
threshold (all|trace|debug|info|warn|error|fatal|off|null) "null"
debug (true|false|null) "null"
reset (true|false) "false"
> <!-- renderer elements allow the user to customize the conversion of -->
<!-- message objects to String. --> <!ELEMENT renderer EMPTY>
<!ATTLIST renderer
renderedClass CDATA #REQUIRED
renderingClass CDATA #REQUIRED
> <!-- throwableRenderer allows the user to customize the conversion
of exceptions to a string representation. -->
<!ELEMENT throwableRenderer (param*)>
<!ATTLIST throwableRenderer
class CDATA #REQUIRED
> <!-- Appenders must have a name and a class. -->
<!-- Appenders may contain an error handler, a layout, optional parameters -->
<!-- and filters. They may also reference (or include) other appenders. -->
<!ELEMENT appender (errorHandler?, param*,
rollingPolicy?, triggeringPolicy?, connectionSource?,
layout?, filter*, appender-ref*)>
<!ATTLIST appender
name CDATA #REQUIRED
class CDATA #REQUIRED
> <!ELEMENT layout (param*)>
<!ATTLIST layout
class CDATA #REQUIRED
> <!ELEMENT filter (param*)>
<!ATTLIST filter
class CDATA #REQUIRED
> <!-- ErrorHandlers can be of any class. They can admit any number of -->
<!-- parameters. --> <!ELEMENT errorHandler (param*, root-ref?, logger-ref*, appender-ref?)>
<!ATTLIST errorHandler
class CDATA #REQUIRED
> <!ELEMENT root-ref EMPTY> <!ELEMENT logger-ref EMPTY>
<!ATTLIST logger-ref
ref CDATA #REQUIRED
> <!ELEMENT param EMPTY>
<!ATTLIST param
name CDATA #REQUIRED
value CDATA #REQUIRED
> <!-- The priority class is org.apache.log4j.Level by default -->
<!ELEMENT priority (param*)>
<!ATTLIST priority
class CDATA #IMPLIED
value CDATA #REQUIRED
> <!-- The level class is org.apache.log4j.Level by default -->
<!ELEMENT level (param*)>
<!ATTLIST level
class CDATA #IMPLIED
value CDATA #REQUIRED
> <!-- If no level element is specified, then the configurator MUST not -->
<!-- touch the level of the named category. -->
<!ELEMENT category (param*,(priority|level)?,appender-ref*)>
<!ATTLIST category
class CDATA #IMPLIED
name CDATA #REQUIRED
additivity (true|false) "true"
> <!-- If no level element is specified, then the configurator MUST not -->
<!-- touch the level of the named logger. -->
<!ELEMENT logger (param*,level?,appender-ref*)>
<!ATTLIST logger
class CDATA #IMPLIED
name CDATA #REQUIRED
additivity (true|false) "true"
> <!ELEMENT categoryFactory (param*)>
<!ATTLIST categoryFactory
class CDATA #REQUIRED> <!ELEMENT loggerFactory (param*)>
<!ATTLIST loggerFactory
class CDATA #REQUIRED> <!ELEMENT appender-ref EMPTY>
<!ATTLIST appender-ref
ref CDATA #REQUIRED
> <!-- plugins must have a name and class and can have optional parameters -->
<!ELEMENT plugin (param*, connectionSource?)>
<!ATTLIST plugin
name CDATA #REQUIRED
class CDATA #REQUIRED
> <!ELEMENT connectionSource (dataSource?, param*)>
<!ATTLIST connectionSource
class CDATA #REQUIRED
> <!ELEMENT dataSource (param*)>
<!ATTLIST dataSource
class CDATA #REQUIRED
> <!ELEMENT triggeringPolicy ((param|filter)*)>
<!ATTLIST triggeringPolicy
name CDATA #IMPLIED
class CDATA #REQUIRED
> <!ELEMENT rollingPolicy (param*)>
<!ATTLIST rollingPolicy
name CDATA #IMPLIED
class CDATA #REQUIRED
> <!-- If no priority element is specified, then the configurator MUST not -->
<!-- touch the priority of root. -->
<!-- The root category always exists and cannot be subclassed. -->
<!ELEMENT root (param*, (priority|level)?, appender-ref*)> <!-- ==================================================================== -->
<!-- A logging event -->
<!-- ==================================================================== -->
<!ELEMENT log4j:eventSet (log4j:event*)>
<!ATTLIST log4j:eventSet
xmlns:log4j CDATA #FIXED "http://jakarta.apache.org/log4j/"
version (1.1|1.2) "1.2"
includesLocationInfo (true|false) "true"
> <!ELEMENT log4j:event (log4j:message, log4j:NDC?, log4j:throwable?,
log4j:locationInfo?, log4j:properties?) > <!-- The Date format is application dependent. -->
<!ATTLIST log4j:event
logger CDATA #REQUIRED
level CDATA #REQUIRED
thread CDATA #REQUIRED
Date CDATA #REQUIRED
time CDATA #IMPLIED
> <!ELEMENT log4j:message (#PCDATA)>
<!ELEMENT log4j:NDC (#PCDATA)> <!ELEMENT log4j:throwable (#PCDATA)> <!ELEMENT log4j:locationInfo EMPTY>
<!ATTLIST log4j:locationInfo
class CDATA #REQUIRED
method CDATA #REQUIRED
file CDATA #REQUIRED
line CDATA #REQUIRED
> <!ELEMENT log4j:properties (log4j:data*)> <!ELEMENT log4j:data EMPTY>
<!ATTLIST log4j:data
name CDATA #REQUIRED
value CDATA #REQUIRED
>
第五步 配置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" 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>SSH</display-name>
<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>
<!-- web应用一启动,便加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param> <!-- 动态设置项目的运行路径 -->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>sshWeb.root</param-value>
</context-param> <!-- 加载LOG4J -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.xml</param-value>
</context-param> <context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param> <!-- 配置Hibernate过滤器 -->
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>flushMode</param-name>
<param-value>AUTO</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 字符集过滤 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 登录过滤 -->
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>com.cy.ssh.filter.LoginFilter</filter-class>
</filter> <filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 加载spring容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 加载log4j文件 -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener> </web-app>
第六步 来配置ssh各个的xml文件,
先配置 applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 开启spring自动扫描功能,适用注解 -->
<context:component-scan base-package="com.cy.ssh" /> <!-- 配置C3P0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
<property name="user" value="root" />
<property name="password" value="root" />
<property name="minPoolSize" value="1" />
<property name="maxPoolSize" value="20" />
<property name="initialPoolSize" value="1" />
<property name="maxIdleTime" value="60" />
<property name="acquireIncrement" value="5" />
<property name="automaticTestTable" value="c3p0TestTable" />
<property name="idleConnectionTestPeriod" value="60" />
<property name="checkoutTimeout" value="3000" />
</bean> <!-- 配置SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 向SessionFactory中注入数据源 -->
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<!-- 定义Hibernate的方言 -->
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<!-- 是否根据需要每次自动更新数据库
<prop key="hibernate.hbm2ddl.auto">update</prop> -->
<!-- 控制台显示SQL -->
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<!-- 使用SQL注释 -->
<prop key="hibernate.use_sql_comments">true</prop>
</props>
</property> <!-- 浏览bean包下的所有使用Hibernate注解的JavaBean -->
<property name="packagesToScan">
<list>
<value>com.cy.ssh.beans</value>
</list>
</property>
</bean> <!-- spring通过声明式方式来进行事务管理-->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean> <!-- 定义个通知,指定事务管理器 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="delete*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="save*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="update*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="load*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice> <aop:config>
<!-- 配置一个切入点 -->
<aop:pointcut id="serviceMethods"
expression="execution(* com.cy.ssh.service.impl.*ServiceImpl.*(..))" />
<aop:advisor advice-ref="txAdvice"
pointcut-ref="serviceMethods" />
</aop:config> </beans>
配置都差不多了。
来写个登录案例
User.java 使用Hibernate注解
package com.cy.ssh.beans; import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator;
/**
* 用户
* @author acer
*
*/
@Entity
@Table(name="t_user")
public class User implements Serializable { private static final long serialVersionUID = 1L;
@Id
@Column(name="id")
@GenericGenerator(name="hbincrement", strategy="increment")
@GeneratedValue(generator="hbincrement")
private int id;
@Column(name="username",length=20)
private String username;
@Column(name="password",length=32)
private String password;
@Column(name="age")
private int age;
@Column(name="flag")
private int flag; public User(){ } public int getId() {
return id;
} public void setId(int 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 int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public int getFlag() {
return flag;
} public void setFlag(int flag) {
this.flag = flag;
} @Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password="
+ password + ", age=" + age + ", flag=" + flag + "]";
} }
工具类:
HibernateTools.java
package com.cy.ssh.tools; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
/**
*
* @author acer
*
*/
@Component
public class HibernateTools { @Autowired
@Qualifier("sessionFactory")
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
} public Session getSession(){
return sessionFactory.getCurrentSession();
} public Session getNewSession(){
return sessionFactory.openSession();
} }
StringTools.java
package com.cy.ssh.tools;
/**
* 判断是否为空
* @author acer
*
*/
public class StringTools { public static boolean isNull(String str){
if(str == null || "".equals(str)){
return true;
}
return false;
}
}
持久层
IUserDao.java
package com.cy.ssh.dao; import java.util.List; import com.cy.ssh.beans.User; public interface IUserDao {
/**
* 查询用户
* @param hql
* @return
*/
public List<?> find(String hql);
/**
* 新增user
* @param u
*/
public void saveUser(User u); /**
* 修改user
* @param u
*/
public void updateUser(User u); /**
* 删除user
* @param u
*/
public void updateDeleteUser(User u); }
UserServiceImpl.java
package com.cy.ssh.dao.impl; import java.util.List; import org.hibernate.Query;
import org.springframework.stereotype.Repository; import com.cy.ssh.beans.User;
import com.cy.ssh.dao.IUserDao;
import com.cy.ssh.tools.HibernateTools;
@Repository
public class UserDaoImpl extends HibernateTools implements IUserDao{ @Override
public List<?> find(String hql) {
Query query= getSession().createQuery(hql);
return query.list();
} @Override
public void saveUser(User u) {
getSession().save(u); } @Override
public void updateUser(User u) {
getSession().update(u); } @Override
public void updateDeleteUser(User u) {
getSession().update(u); } }
业务层
IUserService.java
package com.cy.ssh.service; import com.cy.ssh.beans.User; public interface IUserService {
/**
*
* @param user
* @return
*/
public User getUser(User user);
/**
* 新增user
* @param u
*/
public void saveUser(User u); /**
* 修改user
* @param u
*/
public void updateUser(User u); /**
* 删除user
* @param id
*/
public void updateDeleteUser(int id);
}
IUserServiceImpl.java
package com.cy.ssh.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.cy.ssh.beans.User;
import com.cy.ssh.dao.IUserDao;
import com.cy.ssh.service.IUserService;
@Service
public class UserServiceImpl implements IUserService{
@Resource
private IUserDao userDaoImpl; @Override
public User getUser(User user) { User ret = null;
String hql = "from User as u where (1=1) and u.username = '"+user.getUsername()+"' and u.flag = 1";
List<?> list = userDaoImpl.find(hql);
if(list != null && !list.isEmpty()){
ret = (User) list.get(0);
}
return ret;
} @Override
public void saveUser(User u) { userDaoImpl.saveUser(u);
} @Override
public void updateUser(User u) {
userDaoImpl.updateUser(u);
} @Override
public void updateDeleteUser(int id) { } }
LoginAction.java
package com.cy.ssh.action; import javax.annotation.Resource; import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller; import com.cy.ssh.beans.User;
import com.cy.ssh.service.IUserService;
import com.cy.ssh.tools.StringTools;
import com.opensymphony.xwork2.ActionSupport;
@Controller
@Scope("prototype")
public class LoginAction extends ActionSupport { private static final long serialVersionUID = 1L;
private User user;
@Resource
private IUserService userServiceImpl; @Override
public void validate() {
if(StringTools.isNull(user.getUsername())){
this.addFieldError("dataErr", "用户名不能为空");
}
if(StringTools.isNull(user.getPassword())){
this.addFieldError("dataErr", "密码不能为空");
} }
@Override
public String execute() throws Exception {
User u=userServiceImpl.getUser(user);
if(u!=null){
ServletActionContext.getRequest().getSession().setAttribute("user", user);
return SUCCESS;
}else{
return ERROR;
}
} public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
} }
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!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>
<s:fielderror></s:fielderror>
<form action="<%=basePath%>login.do" method="post">
<table>
<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"><input type="submit" value="登录"/></td>
</tr>
</table> </form>
</body>
</html>
配置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>
<!-- 告诉struts框架,我们的Action类的实例化来源于Spring容器 -->
<constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />
<!-- 指定需要Struts 2处理的请求后缀 -->
<constant name="struts.action.extension" value="action,do" /> <package name="default" namespace="/" extends="struts-default"> <action name="login" class="loginAction"> <result name="success">/success.jsp</result>
<result name="input">/login.jsp</result>
</action> </package> </struts>
差不多就完成了!