Spring 学习笔记4—— SpringMVC的控制器与View简单demo

    xiaoxiao2021-03-26  9

    配置MVC

    web.xml

    <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Web</display-name> <!-- 添加下面部分 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>

    dispatcherServlet-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" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 自动扫描的包名 --> <context:component-scan base-package="com.xundh.controller"></context:component-scan> <!-- 默认的注解映射的支持 --> <mvc:annotation-driven /> <!-- 视图解释类 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/Views/" /> <!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 --> <property name="suffix" value=".jsp" /> </bean> <!-- HandlerMapping --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> <!-- HandlerAdapter --> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> </beans>

    WEB-INF/Views/hello.jsp

    <html> <body> hello </body> </html>

    HelloWorldController

    package com.xundh.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @Controller public class HelloWorldController { @RequestMapping("/hello") public ModelAndView helloWorld(@RequestParam int id,Model model) { String message = "Hello World, Spring 3.0!"; System.out.println(message); ModelAndView mv=new ModelAndView("hello", "message", message); return mv; } }

    访问网页 http://localhost:8080/Web/hello?id=1

    效果

    转载请注明原文地址: https://ju.6miu.com/read-650129.html

    最新回复(0)