SpringMVC框架应该说应用比较多,也比较流行的。它到目前为止依然保持着强大的活力和广泛的用户群.下面就
来一起学习一下吧。
加入jar包:
<?xmlversion="1.0"encoding="UTF-8"?> <web-appxmlns: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_2_5.xsd" id="WebApp_ID"version="2.5">
<!-- 配置DispatcherServlet --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置 DispatcherServlet的一个初始化参数: 配置 SpringMVC 配置文件的位置和名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> |
在src下面新建xml文件,取名为springmvc.xml
<?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
</beans> |
package com.wangju.springmvc.handlers; import org.springframework.stereotype.Controller; @Controller public class HelloWorld { /** * 1.使用@RequestMapping注解来映射请求的URL * 2.返回值会通过视图解析器解析为实际的物理视图,对于InternalResourceView视图解析器,会做如下分析: * 通过组合成prefix+returnVal+suffix方式,得到实际的物理视图,然后做转发操作 * /WEB-INF/views/success.jsp * * @return */ @RequestMapping("/helloworld") public String hello(){ System.out.println("hello world"); return"success"; } } |
在springmvc.xml配置扫描器
<!-- 配置指定扫描的包 --> <context:component-scanbase-package="com.wangju.springmvc"></context:component-scan> |
<%@ page language="java"contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPEhtml PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <metahttp-equiv="Content-Type"content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <!-- 超链接发送一个请求url --> <ahref="helloworld">Hello World</a> </body> </html> |
<!-- 实际上也可以不通过 contextConfigLocation来配置 SpringMVC的配置文件, 而使用默认的. 默认的配置文件为: /WEB-INF/<servlet-name>-servlet.xml -->
DispatcherServlet在初始化话时需要一些参数,默认从/WEB-INF/<servlet-name>-servlet.xml中加载配置,所以啊可以将springmvc.xml中的内容放到web-inf下。
|