欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springmvc(2)---入门示例

程序员文章站 2022-07-11 10:37:57
...

本示例采用非注解模式开发

步骤 1:新建项目springmvcDemo,并导入springmvc所需要的jar包

项目结构如下:

springmvc(2)---入门示例


所需要的jar包如下:


springmvc(2)---入门示例

步骤2:在src下新建springmvc的核心配置文件springMvc.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
    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" >
	<!-- 1、配置处理器 -->
	<bean id="hello" class="com.cn.controller.HelloController" />
	<!-- 2、配置处理器映射器 -->
	<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings">
			<props>
				<prop key="hello.do">hello</prop>
			</props>
		</property>
	</bean>
	<!-- 3、配置视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

步骤3:新建控制器类HelloController

package com.cn.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * springmvc控制层
 * 此处采用非注解模式开发,实现Controller接口即可
 * 
 * */
public class HelloController implements Controller{

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse reponse) throws Exception {
		//实例化一个模型视图控制类
		ModelAndView mv=new ModelAndView();
		//将hello world springmvc赋值到message,然后传递到前端
		mv.addObject("message", "hello world springmvc!");
		//设置视图名称
		mv.setViewName("hello");  //此处的hello必须和jsp中的hello.jsp同名,会根据配置去/WEB-INF/jsp下查找hello.jsp文件
		return mv;
	}
	
}

步骤4:新建视图层Hello.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">   
    <title>My JSP 'hello.jsp' starting page</title>
  </head>
  
  <body>
    	${message}
  </body>
</html>

步骤5:测试

springmvc(2)---入门示例