之前一直都是将Spring与Struts2整合在一起,近日需要将Spring与Servlet整合在一起。如果把Spring与Struts2整合在一起的方法用到Servlet显然是不行的。因为Struts2已经与Servlet分离了,可以把Struts2的action类看成是一个普通类,可以用IOC的方式注入。但是Servlet是一个服务器类,servlet容器实例化一个对象是需要经过init()-àService()-àdoPost()||doGet()àdestroy()的过程,所以我们需要在init()时期就创建一个ApplicationContext对象并且得到注册在Spring配置文件中的bean对象。
做了个登录小例子,贴出完整的代码。
新建一个web工程,在web.xml添加如下所示配置:
[html] www.2cto.com
classpath*:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
新建一个接口UserAccount.java,代码如下所示:
[java
package com.ldfsoft.service;
public interface UserAccount {
public boolean checkAccount(String account, String password);
}
接着新建一个该接口的实现类checkAccount.java ,代码如下所示:
[java]
package com.ldfsoft.serviceimp;
import com.ldfsoft.service.UserAccount;
public class UserAccountImp implements UserAccount {
@Override
public boolean checkAccount(Stringaccount, String password) {
// TODO Auto-generatedmethod stub
if("admin".equals(account)&&"123".equals(password)){
return true;
}
return false;
}
}
将此类在Spring的配置文件applicationContext.xml配置一下,如下所示:
[html]
< xml version="1.0"encoding="UTF-8" >
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
接着新建一个登陆页面login.jsp,代码如下所示:
[html]
<%@ page language="java"contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<script type="text/java script">
function check(){
var account=document.getElementById("account").value;
var password=document.getElementById("password").value;
if(account=="" || password==""){
alert("用户名或者密码不能为空!");
return false;
}
return true;
}
新建一个登陆成功的页面success.jsp,代码如下所示:
[html]
<%@ page language="java"contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%=request.getParameter("account") %>,欢迎您回来...
登陆失败的页面fail.jsp,代码如下所示:
[html]
<%@ page language="java"contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
用户名或密码错误,3秒后自动返回登陆页面...
接着新建一个servlet文件LoginServlet.Java,注意此init()方法中强制获取bean的方法:
[java]
package com.ldfsoft.servlet;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
importorg.springframework.web.context.support.WebApplicationContextUtils;
import com.ldfsoft.service.UserAccount;
/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ApplicationContext applicationContext;
private UserAccount userAccount;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @seeServlet#init(ServletConfig)
*/
public void init(ServletConfig config) thro