SpringMVC--HelloWorld

  SpringMVC是Spring 为展现层提供的Web框架,采用了松散耦合可插拔组件结构,比其他MVC框架更具扩展性和灵活性。SpringMVC通过一套MVC注解,让POJO成为处理请求的控制器,而无须实现任何接口。

1.Web项目工程导入jar包,列表如下

  commons-logging-1.2.jar
  spring-aop-4.2.0.RELEASE.jar
  spring-beans-4.2.0.RELEASE.jar
  spring-context-4.2.0.RELEASE.jar
  spring-core-4.2.0.RELEASE.jar
  spring-expression-4.2.0.RELEASE.jar
  spring-web-4.2.0.RELEASE.jar
  spring-webmvc-4.2.0.RELEASE.jar

2.配置 web.xml

  <display-name>springMVC</display-name>
     <!-- 定义Spring MVC的前端控制器 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/springmvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
   <!-- 让Spring MVC的前端控制器拦截所有请求 -->
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

3.配置springmvc-config.xml

 <!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件,
如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean --> <context:component-scan base-package="com.demo.controller"/> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix"> <value>/WEB-INF/content/</value> </property> <!-- 后缀 --> <property name="suffix"> <value>.jsp</value> </property> </bean>

4.请求逻辑

@Controller
public class HelloController {

	private static final Log logger = LogFactory.getLog(HelloController.class); 
	
	 @RequestMapping("/helloWorld")
	 public String helloWorld(Model model) {
	     model.addAttribute("message", "Hello World!");
	     return "helloWorld";
	 }

}

5.编写helloWorld.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HelloWorld</title>
</head>
<body>
<!-- 页面可以访问Controller传递传递出来的message -->
${requestScope.message}
</body>
</html>

6.显示效果 

 

  

  

  

posted @ 2019-02-16 20:01  彩虹消失了  阅读(329)  评论(2编辑  收藏  举报