SpringMVC入门

205 阅读1分钟

所需jar包自己导入

修改web.xml,表示拦截所有请求

dispatcher-servlet.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.xsd">

    <bean class="cn.niit.Controller.HelloController" name="/hello"/>
    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
</beans>

hello.jsp

你好:${requestScope.hello}

HelloController

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloController implements Controller {

    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView hello = new ModelAndView("hello");
        hello.addObject("hello", "无情");
        return hello;
    }
}

运行自动打开首页index.jsp,如果404找不到或者空白,运行没报错,那么试试下面的方法

使用注解

记得添加命名空间

    <!--    注解扫描-->
    <context:component-scan base-package="cn.niit.Controller"/>

HelloController

@Controller
public class HelloController {
    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String hello(Model model){
        model.addAttribute("hello","世界");
        // 寻找web-inf目录下的jsp/hello.jsp文件
        return "hello";
    }
}