赞
踩
在操作前需要了解的知识:
Controller的具体配置过程:
(1)准备操作。
在webapp/WEB-INF目录下创建config(存放配置文件)和view(存放jsp文件)文件夹。在 src/main/java目录下创建controller包(存放控制器类)。
(2)在web.xml中配置DispatcherServlet。
打开web.xml文件,在< web-app >标签内输入以下内容。
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/config/spring-mvc-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

以上配置应该注意的几点:
(3)Spring MVC配置文件
/WEB-INF/config目录下创建spring-mvc-servlet.xml文件。(具体的创建位置由web.xml中servlet的contextConfigLocation决定)。向该xml文件中添加下面信息。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 启用spring mvc注解 -->
<context:annotation-config />
<!-- 设置使用注解的类所在的包,即Dispatcherservlet寻找controller时扫描的包 -->
<context:component-scan base-package="controller" />
<!-- 对处理结果所转向的页面进行解析 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

以上配置文件应注意的几点:
(3)编写controller类文件
在src/mian/controller文件夹下创建FisetController类。
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class FirstController {
@RequestMapping("index")
public String Index() {
return "index";
}
}
(4)编写index.jsp
在/WEB-INF/VIEW文件夹下创建index.jsp,在index.jsp中添加页面内容。
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
My First Controller.
</body>
</html>
(6)在Package Explorer中右击工程名,依次选择 run as -> run on server,然后选择tomcat服务器。打开浏览器,输入http://localhost:8080/test/index即可访问index页面。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。