用spring管理servlet,如果servlet注入了service,service为null,查找资料,网上有通过代理servlet的方式来解决,参考http://justsee.iteye.com/blog/1211814;
其实spring提供了管理servlet的方式,参考:http://hanqunfeng.iteye.com/blog/605174;
利用第二种方式,我成功调用了servlet,以下是步骤:
第一步:web.xml:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/application*.xml</param-value>
</context-param>
<!-- springMVC控制器-->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/application*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.po</url-pattern>
</servlet-mapping>
第二步:applicationContext.xml 加上
<!-- servlet适配器,这里必须明确声明,因为spring默认没有初始化该适配器 -->
<bean id="servletHandlerAdapter" class="org.springframework.web.servlet.handler.SimpleServletHandlerAdapter"/>
<bean id="beanMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/test.po=testServlet
</value>
</property>
</bean>
第三步: 实现servlet
package com.cheangis.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.cheangis.service.impl.TestService;
@SuppressWarnings("serial")
@Controller
public class TestServlet extends HttpServlet {
@Autowired
private TestService testService;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("参数:"+req.getParameter("name"));
resp.getWriter().write(testService.getFullName(req.getParameter("name")));
resp.getWriter().flush();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
第四步:service:
package com.cheangis.service.impl;
import org.springframework.stereotype.Service;
@Service
public class TestService {
public String getFullName(String name) {
return "my name is "+name;
}
}
第五步:测试
浏览器地址栏输入:
http://localhost:8080/test/test.po?name=22
打印出 my name is 22
表示ok了