SpringMVC学习-HelloWorld

web.xml

web.xml中配置SpringMVC的DispatcherServlet,将所有*.mvc的请求映射到该servlet,参数contextConfigLocation配置SpringMVC配置文件的位置,如果不配置,默认为servletName-servlet.xml,对本例来说就是springmvc-servlet.xml,即在<servlet-name>中配置的值

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0" metadata-complete="true">

	<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/config/helloworld-servlet.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.mvc</url-pattern>
	</servlet-mapping>
</web-app>

springmvc配置文件

context:component-scan元素配置要扫描的包,这里是com.endless.web,这样spring会扫描该目录下的注解注册为bean,如``` @Component, @Service, @Controller, @Repository

<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 http://www.springframework.org/schema/beans/spring-beans-4.0.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">

<context:component-scan base-package="com.endless.web">
</context:component-scan> 

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix" value="/WEB-INF/jsp/" />
	<property name="suffix" value=".jsp" />
</bean>

</beans>

### Controller

@Controller注解注册该类为一个控制器,处理的url由元素@RequestMapping指定,返回的view设置为helloworld/helloworld,即为/WEB-INF/jsp/helloworld/helloworld.jsp

@Controller public class HelloWorldController {

@RequestMapping(value="/hello")
public ModelAndView sayHello(){
	ModelAndView mv=new ModelAndView();
	mv.addObject("message","hello world");
	mv.setViewName("helloworld/helloworld");
	return mv;
}

}


### View

打开http://127.0.0.1:8080/hellomvc/hello.mvc测试

<html> <head> </head> <body> <H1>message is : ${message}</H1> </body> </html> ``` ### 总结

输入图片说明

转载于:https://my.oschina.net/Endless2010/blog/1505520

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值