13、整合struts
13.1)引入struts开发包,将struts-1.3.8-lib下的所有jar包拷贝到WebRoot/WEB-INF/lib下
我们先测试struts是否成功,测试案例:一个登陆页面,login.jsp,提交给的Action为LoginAction,使用的form为EmployeeForm,具体流程图
上半部分淡绿色为struts单独使用流程图。
13.2)创建struts-config.xml文件,文件放在/WEB-INF 目录下,配置如下:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="employeeForm" type="com.cdtax.web.form.EmployeeForm" />
</form-beans>
<action-mappings>
<action path="/login" name="employeeForm" type="com.cdtax.web.action.LoginAction">
<forward name="ok" path="/WEB-INF/mainFrame.jsp" />
<forward name="err" path="/WEB-INF/login.jsp" />
</action>
</action-mappings>
</struts-config>
创建相关程序:login.jsp
<%@ page language="java" import="java.util.*" 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">
<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>
<h1>管理员登陆</h1>
<form action="/cdtax/Login.do?flag=login" method="post">
id:<input type="text" name="id" /><br>
pw:<input type="password" name="pwd" /><br>
<input type="submit" value="登陆" />
<input type="reset" value="重置" />
</form>
</body>
</html>
Action:
package com.cdtax.web.action;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import com.cdtax.web.forms.EmployeeForm;
public class LoginAction extends DispatchAction
{
//响应登录请求
public ActionForward login(ActionMapping arg0, ActionForm arg1,
ServletRequest arg2, ServletResponse arg3) throws Exception
{
//取出表单,我们先打通练习,我们简单验证
EmployeeForm employeeForm = (EmployeeForm)arg1;
System.out.println("id=" + employeeForm.getId() + " pwd=" + employeeForm.getPwd());
if("123".equals(employeeForm.getPwd()))
{
return arg0.findForward("ok");
}
else
{
return arg0.findForward("err");
}
}
//响应注销请求
public ActionForward logout(ActionMapping arg0, ActionForm arg1,
ServletRequest arg2, ServletResponse arg3) throws Exception
{
// TODO Auto-generated method stub
return super.execute(arg0, arg1, arg2, arg3);
}
}
form表单:
package com.cdtax.web.forms;
import org.apache.struts.action.ActionForm;
public class EmployeeForm extends ActionForm
{
private String id;
private String pwd;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getPwd()
{
return pwd;
}
public void setPwd(String pwd)
{
this.pwd = pwd;
}
}
对于DispatchAction,默认会执行excute()方法,而如果我们在struts-config.xml中进行如下配置:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="employeeForm" type="com.cdtax.web.form.EmployeeForm" />
</form-beans>
<action-mappings>
<action path="/login" parameter="flag" name="employeeForm" type="com.cdtax.web.action.LoginAction">
<forward name="ok" path="/WEB-INF/mainFrame.jsp" />
<forward name="err" path="/WEB-INF/login.jsp" />
</action>
</action-mappings>
</struts-config>
增加了一个parameter="flag"参数,那么在jsp页面的form的action提交的路径*.do后面要跟上?flag=。。。,这时提交到的Action就会执行flag所标识的方法,这里的例子是flag=login,所以会执行LoginAction的login()方法。
按照配置文件,如果成功就转到mainFrame.jsp页面,失败回到登陆页面
13.3)在web.xml(web容器)中配置我们的struts
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
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_2_5.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 配置struts -->
<servlet>
<servlet-name>struts</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>struts</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
运行出现如下错误:
严重: Servlet.service() for servlet struts threw exception
java.lang.NullPointerException
at org.apache.struts.config.FormBeanConfig.createActionForm(FormBeanConfig.java:289)
at org.apache.struts.config.FormBeanConfig.createActionForm(FormBeanConfig.java:357)
at org.apache.struts.chain.commands.CreateActionForm.execute(CreateActionForm.java:92)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:304)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:600)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1703)
at java.lang.Thread.run(Thread.java:619)
经查,是struts-config.xml中form-bean的type路径配置出现错误:type="com.cdtax.web.form.EmployeeForm",改为com.cdtax.web.forms.EmployeeForm
然后在运行,又出现:
Servlet.service() for servlet struts threw exception
java.lang.NoSuchMethodException: Action[/login] does not contain specified method (check logs)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:261)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:304)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:617)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1774)
at java.lang.Thread.run(Thread.java:619)
怎么调也没用,最后的解决办法是:
原来用的是struts1.3.8版本,重新下载了struts.3.10,将原来1.3.8的JAR包替换掉,不好用,然后将源代码关联上,然后重新生成LoginAction的execute方法,改为login方法,如下:
public ActionForward login(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
System.out.println("--------------");
//取出表单,我们先打通练习,我们简单验证
EmployeeForm employeeForm = (EmployeeForm)form;
System.out.println("id=" + employeeForm.getId() + " pwd=" + employeeForm.getPwd());
if("123".equals(employeeForm.getPwd()))
{
return mapping.findForward("ok");
}
else
{
return mapping.findForward("err");
}
}
然后程序就通过了,其他什么也没改
具体什么原因啊????真不知道
有网友给出的解答:
jar 包冲突的问题。
比如 a 包调用了 b 包的 c 方法,但是先前版本的 b 包是没 c 方法的。
然后我又看了一下,在生成execute()方法时,因为使用的myeclipse,有自动提示功能,敲一个e然后自动带出以e打头的方法,我看了一下有两个,在没有引入源文件时,两个都是execute(ActionMapping arg0, ActionForm arg1,ServletRequest arg2, ServletResponse arg3),我自动用了第一个,如果引入源文件,变成一个是execute(ActionMapping arg0, ActionForm arg1,ServletRequest arg2, ServletResponse arg3),一个是execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response),这时我在用第一个,就是参数是arg格式的,出现同样的错误。
写到这我突然明白过来了,我靠啊,是方法错了,显示的两个execute()确实是不同的方法,参数不一样的,第一个是ServletRequest,等等,第二个是HttpServletRequest,我们的web项目当然要使用HttpServletRequest类型的啦,我狂吐,这么个破问题弄了四五天
再看login.jsp中的写法,使用dispatchAction,页面提交可以使用在form的action属性中用?flag=login的方法,即<form action="/myssh/login.do?flag=login" method="POST">,也可以不在action中加,而在form体中增加一个hidden元素,如:
<form action="/myssh/login.do" method="POST">
<input type="hidden" name="flag" value="login" />
13.4)在struts组件还没有集成到spring中时,怎样获取spring中的bean呢
一个办法就是在每次用到时,使用ApplicationContext ac = new ClassPathXmlApplicationContext("");获得ApplicationContext,然后getBean(),这个方法很不好
解决:
在web容器中实例化spring容器,在tomcat启动时,在初始化web容器时,同时初始化spring容器,到时取出就行
在web.xml中进行如下配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
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_2_5.xsd">
<!-- 配置struts -->
<servlet>
<servlet-name>struts</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>struts</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 指定spring的配置文件,默认从web根目录寻找配置文件,我们可以通过spring提供的classpath:前缀指定从类路径下寻找 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 对Spring容器进行实例化 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
关于web.xml中的红字部分,注释说明(引用了 liaoxiaohua1981的博客)
context-param:
作用:该元素用来声明应用范围(整个WEB项目)内的上下文初始化参数。
param-name 设定上下文的参数名称。必须是唯一名称
param-value 设定的参数名称的值
- 初始化过程:
- 在启动Web项目时,容器(比如Tomcat)会读web.xml配置文件中的两个节点<listener>和<contex-param>。
- 接着容器会创建一个ServletContext(上下文),应用范围内即整个WEB项目都能使用这个上下文。
- 接着容器会将读取到<context-param>转化为键值对,并交给ServletContext。
- 容器创建<listener></listener>中的类实例,即创建监听(备注:listener定义的类可以是自定义的类但必须需要继承ServletContextListener)。
- 在监听的类中会有一个contextInitialized(ServletContextEvent event)初始化方法,在这个方法中可以通过event.getServletContext().getInitParameter("contextConfigLocation") 来得到context-param 设定的值。在这个类中还必须有一个contextDestroyed(ServletContextEvent event) 销毁方法.用于关闭应用前释放资源,比如说数据库连接的关闭。
- 得到这个context-param的值之后,你就可以做一些操作了.注意,这个时候你的WEB项目还没有完全启动完成.这个动作会比所有的Servlet都要早。
由上面的初始化过程可知容器对于web.xml的加载过程是context-param >> listener >> fileter >> servlet
由上面的解释,web容器加载时,先创建servletContext对象,然后根据
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
增加一个键值对,键就是contextConfigLocation,值就是classpath:applicationContext.xml,这里classpath会被具体路径取代
然后<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>这个监听器在servletContext中取到刚才的键值对,然后就可以通过
ApplicationContext ac = new ClassPathXmlApplicationContext("键值对的值");来初始化spring容器,然后将生成容器,即ac保存到servletContext中,这样在struts的Action中就可以通过:
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext());
获取spring容器,这里的ctx就应该是ac。WebApplicationContextUtils是spring提供的获取spring容器的工具。
现在使用Action与service层结合起来通过spring管理bean进行登录判断
修改Employee,增加pwd字段,修改service接口增加根据id查询的方法
package com.cdtax.domain;
import java.util.Date;
public class Employee
{
private Integer id;
private String name;
private String email;
private String pwd;
private Integer grade;
private java.util.Date hiredate;
private Float salary;
public Employee()
{
}
public Employee(String name, String email, String pwd, Integer grade,
Date hiredate, Float salary)
{
this.name = name;
this.email = email;
this.pwd = pwd;
this.grade = grade;
this.hiredate = hiredate;
this.salary = salary;
}
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 getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public java.util.Date getHiredate()
{
return hiredate;
}
public void setHiredate(java.util.Date hiredate)
{
this.hiredate = hiredate;
}
public Float getSalary()
{
return salary;
}
public void setSalary(Float salary)
{
this.salary = salary;
}
public String getPwd()
{
return pwd;
}
public void setPwd(String pwd)
{
this.pwd = pwd;
}
public Integer getGrade()
{
return grade;
}
public void setGrade(Integer grade)
{
this.grade = grade;
}
}
接口:
package com.cdtax.service.interfaces;
import java.util.List;
import com.cdtax.domain.Employee;
public interface EmployeeServiceInter
{
//声明一些方法
public void addEmployee(Employee e);
public List<Employee> showEmployee();
public void updateEmployee(Employee e);
//根据id删除雇员
public void deleteEmployee(java.io.Serializable id);
//根据id获取雇员
public Employee getEmployeeById(java.io.Serializable id);
//如果该雇员存在,则返回该雇员的完整信息,否则返回null
public Employee checkEmployee(Employee e);
}
实现:
package com.cdtax.service.impl;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.transaction.annotation.Transactional;
import com.cdtax.domain.Employee;
import com.cdtax.service.interfaces.EmployeeServiceInter;
//这里配置@Tansactional用处是让spring的事务管理器接管该service的事务
//如果只想让事务管理器管理某个方法中的事务,那么就将注解加到方法上
@Transactional
public class EmployeeService implements EmployeeServiceInter
{
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
public void addEmployee(Employee e)
{
// Session s = sessionFactory.openSession();
// Transaction tx = s.beginTransaction();
// s.save(e);
// tx.commit();
sessionFactory.getCurrentSession().save(e);
}
public List<Employee> showEmployee()
{
// TODO Auto-generated method stub
return null;
}
public void updateEmployee(Employee e)
{
// TODO Auto-generated method stub
}
public void deleteEmployee(Serializable id)
{
// TODO Auto-generated method stub
}
public Employee getEmployeeById(Serializable id)
{
// TODO Auto-generated method stub
return null;
}
public Employee checkEmployee(Employee e)
{
String hql="from Employee where id=? and pwd=?";
List<Employee> list = sessionFactory.getCurrentSession().createQuery(hql)
.setString(0, e.getId()+"").setString(1, e.getPwd()).list();
if(list.size() == 1)
{
return list.get(0);
}
else
{
return null;
}
}
}
spring配置文件:
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 配置一个testService对象,测试spring集成是否成功用 -->
<bean id="testService" class="com.cdtax.test.TestService">
<property name="name" value="小明"></property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/hibernate" />
<property name="username" value="root" />
<property name="password" value="root" />
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="3" />
<!-- 连接池的最大值 -->
<property name="maxActive" value="500" />
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="2" />
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="1" />
</bean>
<!-- 配置会话工厂() -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 设置数据源 -->
<property name="dataSource" ref="dataSource" /><!-- 应该想到类中有setDataSource()方法 -->
<!-- 接管了haibernate的对象映射文件 -->
<property name="mappingResources"><!-- 应该想到类中有setMappingResources()方法 -->
<list>
<value>com/cdtax/domain/Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true
<!-- 配置hibernate二级缓存 -->
hibernate.cache.use_second_level_cache=true
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
hibernate.generate_statistics=true
</value>
</property>
</bean>
<!-- 配置EmployeeService对象 -->
<bean id="employeeService" class="com.cdtax.service.impl.EmployeeService">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置事务管理器,统一管理sessionFactory的事务 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 启用事务注解 -->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
修改struts的Action,使用spring获取bean
package com.cdtax.web.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.cdtax.domain.Employee;
import com.cdtax.service.interfaces.EmployeeServiceInter;
import com.cdtax.web.forms.EmployeeForm;
public class LoginAction extends DispatchAction
{
// ApplicationContext ac = new ClassPathXmlApplicationContext("");
public ActionForward login(ActionMapping arg0, ActionForm arg1,
HttpServletRequest arg2, HttpServletResponse arg3) throws Exception
{
//通过下面语句,可以直接获取到spring容器实例,即我们前面讲的ApplicationContext
WebApplicationContext ctx =
WebApplicationContextUtils
.getWebApplicationContext(this.getServlet().getServletContext());
//从spring容器中获取bean
EmployeeServiceInter employeeServiceInter = (EmployeeServiceInter) ctx.getBean("employeeService");
//取出表单,我们先打通练习,我们简单验证
EmployeeForm employeeForm = (EmployeeForm)arg1;
//构建一个Employee对象
Employee e = new Employee();
e.setId(Integer.parseInt(employeeForm.getId()));
e.setPwd(employeeForm.getPwd());
e = employeeServiceInter.checkEmployee(e);
if(e != null)
{
//把雇员信息放入session,后面可以使用
arg2.getSession().setAttribute("loginer", e);
return arg0.findForward("ok");
}
else
{
return arg0.findForward("err");
}
}
//响应登录请求
public ActionForward login111(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
System.out.println("--------------");
//取出表单,我们先打通练习,我们简单验证
EmployeeForm employeeForm = (EmployeeForm)form;
System.out.println("id=" + employeeForm.getId() + " pwd=" + employeeForm.getPwd());
if("123".equals(employeeForm.getPwd()))
{
return mapping.findForward("ok");
}
else
{
return mapping.findForward("err");
}
}
//响应注销请求
public ActionForward logout(ActionMapping arg0, ActionForm arg1,
HttpServletRequest arg2, HttpServletResponse arg3) throws Exception
{
// TODO Auto-generated method stub
return super.execute(arg0, arg1, arg2, arg3);
}
}
重新部署访问,一个通过数据库管理用户登录的模块完成。
集合起来的流程图: