springmvc(2)---入门示例

来源:互联网 发布:新网域名转出申请 编辑:程序博客网 时间:2024/05/22 16:45

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

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

项目结构如下:



所需要的jar包如下:



步骤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{@Overridepublic 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:测试



原创粉丝点击