web.xml:(里面添加)
<!-- 确定spring配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml</param-value>
</context-param>
<!-- 配置spring 监听器,加载spring-config.xml配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
pom.xml:(添加依赖)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
Servlet中添加:
@Override
public void init(ServletConfig config) throws ServletException
{
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
AnimalServlet.java:
@WebServlet("/AniamlServlet")
public class AniamlServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException
{
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1 中文处理
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//2 读取method参数
String method=request.getParameter("method");
//3 读取method参数,调用具体方法
if ("findall".equals(method)){
findAll(request,response);
}
}
@Autowired
private AnimalService animalService;
private void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1读取请求参数
List<Animal> list=animalService.findAll();
//2 保存数据到request中
request.setAttribute("list",list);
//转发视图
request.getRequestDispatcher("showall.jsp").forward(request,response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}