SpringMVC(2)之HelloWorld

  1. 导入相关jar包
    在这里插入图片描述
  2. 在web.xml中配置DispatcherServlet
	<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
	<servlet>
		<servlet-name>springDispatcherServlet</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>
			<!-- 可以不通过contextConfigLocation 来配置springmvc.xml文件
			使用默认的:/WEB-INF/<servlet-name>-servlet.xml
		 -->
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
  1. 添加springmvc.xml 文件

在这里插入图片描述
添加一个自动扫描包内容如下:

<!--配置自动扫描包  -->
	<context:component-scan base-package="com.bubbletg.handlers"></context:component-scan>

4.在com.bubbletg.handlers 包下创建一个HelloWorld类,编写下内容如下(部分):

@Controller
public class HelloWorld {
	@RequestMapping("/helloworld")
	public String hello() {
		System.out.println("hello world");
		return "success";
	}
}

其中@Controller 把HelloWorld标识为控制器,也就是请求处理器了。让hello方法应答一个请求;则是@RequestMapping(“/hellowrld”)来映射请求;
请求页面是一个简单的a标签请求:
在这里插入图片描述
这个请求先被web.xml 中的<servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
处理,应答所有请求,交给@RequestMapping来映射请求。

5.配置视图解析器
在springmvc.xml 中配置

	<!-- 配饰视图解析器  : 如何把handler 方法值解析为实际物理视图-->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	

hello方法中的返回值会通过视图解析器解析为实际的物理视图,对于InternalResourceViewResolver 会做如下解析
通过 prefix + returnVal + 后缀 这样的方式得到实际的物理视图,然后做转发操作
/WEB-INF/views/success.jsp
所以需要建立一个success.jsp 页面。
在这里插入图片描述
6.运行结果
在这里插入图片描述
当点击请求是页面成功跳转并且打印成功,说明项目完成。


好了到这里就是springmvc第一个程序就完成了,也是学springmvc的第一次笔记,后面讲持续跟进,对了,我这所学来源尚硅谷,自己看视频然后根据自己理解做的笔记。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值