SpringMVC环境搭建

一、基于XML

1. 创建Maven Project,选择war,修改pom.xml

SpringMVC是依赖于Spring的,需要导入核心包。


    
    1.8
    
    4.1.6.RELEASE



    
    
        javax.servlet
        javax.servlet-api
        3.0.1
        provided
    
    
        javax.servlet.jsp
        jsp-api
        2.2
        provided
    
    
        jstl
        jstl
        1.2
    

    
    
        org.springframework
        spring-core
        ${spring.version}
    
    
    
        org.springframework
        spring-beans
        ${spring.version}
    
    
    
        org.springframework
        spring-context
        ${spring.version}
    
    
    
        org.springframework
        spring-context-support
        ${spring.version}
    
    
    
        org.springframework
        spring-expression
        ${spring.version}
    
    
    
    
        org.springframework
        spring-web
        ${spring.version}
    
    
    
        org.springframework
        spring-webmvc
        ${spring.version}
    
    

2. 在src/main/webapp下创建META-INF、WEB-INF,在WEB-INF下创建web.xml

在web.xml中配置前端控制器:



    springmvc
    org.springframework.web.servlet.DispatcherServlet
    
        contextConfigLocation
        
        classpath:springmvc.xml
    



    springmvc
    *.do

3. 在src/main/resources下创建springmvc.xml



    
    
    
    
    
    
    

    
    
        
        
        
        
    
    

4. 创建HelloController

public class HelloController implements Controller {

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView modelView = new ModelAndView();
        modelView.setViewName("index");
        return modelView;
    }
}

5. 在WEB-INF/jsp目录下创建index.jsp

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




Insert title here


hello world!

6. 浏览器访问

访问地址:http://ip:port/项目名/hello.do

二、基于注解

上面是基于 XML 的配置,每个 Handler(Controller) 类只能有一个方法,在实际开发中用的最多的基于注解配置的SpringMVC配置。

1. 修改springmvc.xml



    
    

    
    

    
    
    
    
    
    
    
    
        
        
        
        
    
    

2. 修改Controller

@Controller
public class HelloController2 {

    @RequestMapping("/hello")
    public ModelAndView showPage(){
        ModelAndView modelView = new ModelAndView();
        modelView.setViewName("index");
        return modelView;
    }
}

你可能感兴趣的:(WEB开发,SpringMVC)