关闭

SpringMVC配置HelloWorld

532人阅读 评论(0) 收藏 举报
分类:

1.配置web.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	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">
	<display-name>AweekServer1.1</display-name>
	<servlet>
		<servlet-name>user</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>user</servlet-name>
<!-- 使用"/* "就不行,这是为什么呢?-->
		<url-pattern>/</url-pattern>

	</servlet-mapping>
</web-app>

2.在web-inf下配置servlet.xml文件:

<?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/mvc 
	http://www.springframework.org/schema/mvc/spring-mvc.xsd
		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.xsd">
	<mvc:annotation-driven/>
	<context:component-scan base-package="com.aweek.controller"></context:component-scan>
	<!-- 配置从逻辑视图到物理试图的映射对象 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>

3.写一个controller:

@Controller
public class UserController {
	
	/**
	 * 注意:方法必须是public属性,第一次写的时候变成了私有属性,结果老是加载不了。
	 *'/'表示的是在url-pattern中设置的路径。
	 */
	@RequestMapping("/hello")
	public void helloWorld(){
		System.out.println("helloWorld");
	}
	

}

4.运行

5.如何获取Response与request对象:

	@RequestMapping("/get")
	
		public String getRequest(HttpServletRequest request,HttpServletResponse response){
		request.setAttribute("hello", "你好");
		
		//自动映射到hello.jsp中的表达式
		return "hello";
	}

}
hello.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>hello:${hello }${string }</h1>
</body>
</html>

关于Servlet中Url正确匹配的问题:

http://www.oschina.net/question/554525_135696

 * Controller是单例的.不是线程安全的。所以不要有类的参数。

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场