SpringMVC学习-HelloWorld

原创
2017/08/09 21:38
阅读数 13

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> ``` ### 总结

输入图片说明

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部