之前一直都是将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添加如下所示配置:
<context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:applicationContext.xml </param-value> </context-param> <listener> <description>启动spring上下工厂的监听器</description> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
新建一个接口UserAccount.java,代码如下所示:
package com.ldfsoft.service; public interface UserAccount { public boolean checkAccount(String account, String password); }
接着新建一个该接口的实现类checkAccount.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配置一下,如下所示:
<?xml version="1.0"encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="userAccount"class="com.ldfsoft.serviceimp.UserAccountImp"></bean> </beans>
接着新建一个登陆页面login.jsp,代码如下所示:
<%@ page language="java"contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script type="text/javascript"> function check(){ var account=document.getElementById("account").value; var password=document.getElementById("password").value; if(account=="" || password==""){ alert("用户名或者密码不能为空!"); return false; } return true; } </script> <meta http-equiv="Content-Type"content="text/html; charset=utf-8"> <title>登录</title> </head> <body> <form action="LoginServlet" method="post"> 账户:<input type="text"id="account" name="account"><br> 密码:<input type="password"id="password" name="password"><br> <input type="submit"value="登录" onclick="returncheck()"> </form> </body> </html>
新建一个登陆成功的页面success.jsp,代码如下所示:
<%@ page language="java"contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type"content="text/html; charset=UTF-8"> <title>登陆成功</title> </head> <body> <%=request.getParameter("account") %>,欢迎您回来... </body> </html>
登陆失败的页面fail.jsp,代码如下所示:
<%@ page language="java"contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type"content="text/html; charset=UTF-8"> <meta http-equiv="refresh"content="3;url=login.jsp"> <title>登录失败</title> </head> <body> 用户名或密码错误,3秒后自动返回登陆页面... </body> </html>
接着新建一个servlet文件LoginServlet.Java,注意此init()方法中强制获取bean的方法:
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) throws ServletException { // TODO Auto-generatedmethod stub super.init(config); applicationContext=WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext()); userAccount=(UserAccount) applicationContext.getBean("userAccount"); } /** * @seeHttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException { // TODO Auto-generatedmethod stub String account=request.getParameter("account"); String password=request.getParameter("password"); System.out.println(account+":"+password); if(userAccount.checkAccount(account, password)){ response.sendRedirect("success.jsp?account="+account); }else{ response.sendRedirect("fail.jsp"); } } }
效果如下图所示:
声明:这是本人学习的成果,允许转载,欢迎交流,但转载务必给出本文章的链接地址:http://blog.csdn.net/youqishini/article/details/8189141,谢谢~