比起刚刚用xml配置开发的第一个程序HelloSpringMVC简单多了,当然在实际开发中也是用注解开发的,这里还是先给出一个HelloController,但是这里不用实现Controller接口了,而是用注解搞定
package com.zhiying.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/hh")
public String Hello(Model model) {
model.addAttribute("msg", "Hello SpringMVC");
//被试图解析器处理,拼接成/WEB-INF/jsp/hello.jsp
return "hello";
}
}
接下来是要跳转的jsp页面了
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
紧接着是一些简单的Spring配置,看到之后,你会觉得超级爽,而且都是固定的
<?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/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描包,让指定包下的注解生效,由IoC容器统一管理-->
<context:component-scan base-package="com.zhiying.controller"/>
<mvc:annotation-driven/>
<!-- 视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀匹配-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 后缀匹配-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
最后就是我们的web.xml了,也是固定的
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 注册DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 关联一个springmvc的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!-- 启动级别-->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- / 匹配所有的请求,不包括.jsp-->
<!-- /* 匹配所有的请求,包括.jsp -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
好了,简简单单这几部,我们能看到,我们的HelloController类的东西越来越简单了