SpringMVC01-回忆servlet-搭建servlet环境



1.新建一个Maven工程当父工程,方便导入依赖。


先删除src文件夹,因为父工程里src没什么用


导入依赖 pom.xml:


        
            junit
            junit
            4.13
        
        
            org.springframework
            spring-webmvc
            5.1.9.RELEASE
        
        
            javax.servlet
            servlet-api
            2.5
        
        
            javax.servlet.jsp
            jsp-api
            2.2
        
        
            javax.servlet
            jstl
            1.2
        

    


2.建立一个Module,添加Web app的支持。


先创建一个普通的maven项目(module),再加入Web app的支持(相比直接建议一个maven的web项目,这样建立可以得到一个比较简洁的web.xml)


3.搭建servlet环境



HelloServlet:

package com.kakafa.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1.获取前端参数
        String method=req.getParameter("method");
        if(method.equals("add")){
            req.getSession().setAttribute("msg","执行了add方法");
        }
        else if (method.equals("delete")){
            req.getSession().setAttribute("msg","执行了delete方法");
        }

        //2.调用业务层


        //3.视图转发或者重定向
        req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}


from.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title



web.xml:

<?xml version="1.0" encoding="UTF-8"?>


    
        hello
        com.kakafa.servlet.HelloServlet
    
    
        hello
        /hello
    



test.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


${msg}