【SpringMVC】环境搭建

来源:互联网 发布:java游戏编程入门书籍 编辑:程序博客网 时间:2024/06/05 11:21

       学习一门新的技术,首先先实现一个小的helloworld是一个很好的选择。简单的例子能够让我们更感性的认识一门新的技术。

      接下来就一起搭建一个例子。

先来一张整体的文件图。


      

1.引入jar包

            上面的图示中已经展示了要引入的jar包。我们需要放到lib文件夹下。

      

2.配置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"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"><!-- 配置 DispatcherServlet --><servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- 配置 DispatcherServlet 的一个初始化参数: 配置 SpringMVC 配置文件的位置和名称 --><!-- 实际上也可以不通过 contextConfigLocation 来配置 SpringMVC 的配置文件, 而使用默认的.默认的配置文件为: /WEB-INF/<servlet-name>-servlet.xml--><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><!-- 拦截所有请求 --><url-pattern>/</url-pattern></servlet-mapping></web-app>

3.配置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: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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"><!-- 配置自动扫描的包 --><context:component-scan base-package="com.dmsd.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>


4.编写Controller

package com.dmsd.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class HelloWorld {        @RequestMapping("/hello")public String hello(){        System.out.println("hello");return "hello";}}

5.编写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>  <p>你好,springmvc</p></body></html>


以上就是一个简单的springmvc的示例,其实就是简单的五步,还是很简单的,但是springmvc这门技术可是不简单啊。(PS:其实写这篇文章的目的就是做个记录。这个例子的实现用了前前后后一天的时间,有问题也不知道是哪里的问题,各种百度也没有找到很好的答案。不过在这个过程中也是学到了不少。)

原创粉丝点击