Take a look at GW

【Spring】SpringMVC非注解配置的两种方式

目录结构:

contents structure [+]

SpringMVC是什么

MVC的全称是Model View Controller,通过实现MVC框架可以很好的数据、视图、业务逻辑进行分离。Spring MVC也是一种MVC框架,它是SpringFrameWork的后续产品,同样需要Spring的Jar包才能运行起来。

SpringMVC的设计原理

Spring MVC的设计是围绕着DispatcherServlet展开的,由DispatcherServlet将请求派发到特定的Controller。

下面是SpringMVC的一个简单流程图:

 

SpringMVC配置第一种方式

我的项目结构:

1,复制Jar包

将Spring的Jar包复制到lib目录下。

2,Web.xml文件

配置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_3_0.xsd" id="WebApp_ID" version="3.0">
  
  <!-- 
    this name matched project name
   -->
  <display-name>SpringMVC</display-name>
  
  <!-- 
    transmit to dispacherServlet to deal with information that passed from table servlet-mapping
   -->
   <servlet>
     <servlet-name>mySpring</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   </servlet>
   <servlet-mapping>
     <servlet-name>mySpring</servlet-name>
     <url-pattern>*.ms</url-pattern>
   </servlet-mapping>
   
   <!-- 
     solve messy code
    -->
    <filter>  
        <filter-name>encodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <init-param>  
            <param-name>encoding</param-name>  
            <param-value>UTF-8</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>encodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping> 
</web-app>

3,mySpring-servlet.xml文件

在工程的WEB-INF下面创建dispatcherServlet配置文件[servlet-name]-servlet.xml。

文件名的格式必需为“[servlet-name]-servlet.xml”,比如笔者的web文件里servlet-name为mySpring,则文件名必须为mySpring-servlet.xml,如果放错的位置或是文件名称格式不对,那么通过web.xml文件是找不到dispatcherServlet文件的。也可以说,只要在Web.xml里配置好了DispatcherServlet,那么该DispatcherServlet的名称也就唯一确定了,一个web.xml文件可以映射出多个DispatcherServlet文件。

<?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:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.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-4.3.xsd">

  <!-- 
    configure HandlerMapping
   -->
   <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
  <!-- 
    configure HandlerAdapter
   -->
   <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
   
   <!-- 
     configure controller
    -->
    <bean name="/testSpring.ms" class="com.my.spring.TestSpring"></bean>
    
    <!-- 
      configure viewResolver
     -->
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <property name="viewClass">  
           <value>org.springframework.web.servlet.view.InternalResourceView</value>  
       </property> 
       <property name="prefix" value="/view/"></property>
       <property name="suffix" value=".jsp"></property>
     </bean>
</beans>

4,welcome.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>
<form action="testSpring.ms">
input your words:
<input type="text" name="words"/>
<input type="submit" value="提交">
</form>
</body>
</html>

5,result.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>
${myValue}
</body>
</html>

6,TestSpring.java文件

package com.my.spring;

import java.util.HashMap;
import java.util.Map;

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

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

public class TestSpring extends AbstractController {

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        String value=request.getParameter("words");
        
        //create model
        Map<String,String>model=new HashMap<String,String>();
        //set value
        model.put("myValue", value);
        
        //create modelAndView
        ModelAndView mav=new ModelAndView("result",model);
        
        return mav;
    }

}

这个文件必需要实现AbstrcactController抽象类,或是实现Controller接口。然后重写handlerRequestInternal方法。这里一定要选择servlet下的AbstractController或Controller,如果读者选择了portlet,恰好项目下又没有相应的包,那么就会报错。

错误

一,错误一:

错误代码:

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

错误解决:

这是因为项目下没有该类,添加servlet-api.jar即可,详见Eclipse如何发布Web项目

二,错误二:

  错误代码:

Server Tomcat v8.5 Server at localhost failed to start.

错误解决:

造成这个错误的原因有许多,这里建议读者检查一下自己的Web.xml文件中的语法是否正确。

三,错误三:

错误代码:

Multiple markers at this line
    - The type javax.portlet.ActionResponse cannot be resolved. It is indirectly
     referenced from required .class files
    - The type javax.portlet.RenderRequest cannot be resolved. It is indirectly
     referenced from required .class files
    - The type javax.portlet.RenderResponse cannot be resolved. It is indirectly
     referenced from required .class files
    - The type javax.portlet.ActionRequest cannot be resolved. It is indirectly
     referenced from required .class files
    - The type javax.portlet.PortletContext cannot be resolved. It is indirectly referenced
     from required .class files

问题解决:

这是因为读者的项目下面没有,portlet包导致的,portlet包的下载

除了引入相应的Portlet包外,这里读者也可以将

import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.mvc.AbstractController;

改为:

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

四,错误四:

错误代码:

Handler processing failed; nested exception is java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config

错误解决:

导入一个jstl标签库即可,下载一个标签标准文档库下载页面

SpringMVC配置的第二种方式

这种方式和上面的方式都是非注解的方式,两者的区别就是使用的类不同。

下面的配置方式和上面的配置方式是想通的:

来一张目录结构:

applicationContext.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:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
        
        <bean id="helloController" class="cn.xdl.controller.HelloController"></bean>
        
        <bean  id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
            <property name="mappings">
                <props>
                <!-- 
                    key: 请求的url地址
                    value: 自己编写的控制器(Controller实现类)在容器中对象的id
                    
                    起到的作用, 将一个url地址, 绑定一个控制器 ,当匹配这个url的请求发生时, 入口Servlet自动调用这个控制器对象, 并将请求对象与响应对象转递过来
                 -->
                    <prop key="/hello.do">helloController</prop>
                </props>
            </property>
        
        </bean>
        
        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 
            解析modelAndView的工具
            
            例如我们返回了一个ModelAndView  ., 封装了一个视图name为: hello
                
                    解析完毕后: perfix+hello+suffix
                            转发至:/hello.jsp
                    
         -->
            <property name="prefix" value="/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
        
        
        
        
</beans>
applicationContext.xml

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_3_0.xsd" version="3.0">
  <display-name>day04_WebMvc</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!--
  如果不需要使用 ini-param 对web配置文件指明SpringMVC的配置文件的地址,那么SpringMVC的配置文件必须放到WEB-INFO目录下,并且命名为[Servlet-name]-servlet.xml。
  -->
  <servlet>
      <servlet-name>dispatcherServlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </init-param>      
  </servlet>
  <servlet-mapping>
      <servlet-name>dispatcherServlet</servlet-name>
      <url-pattern>*.do</url-pattern>
      
  </servlet-mapping>
  
</web-app>
web.xml

HelloController.java文件

package cn.xdl.controller;

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

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

public class HelloController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("控制器正在执行");
        System.out.println("调用响应的Dao进行操作");
        System.out.println("根据结果, 返回不同的视图封装");
        //modelandView 最少要传递一个View
        ModelAndView mav = new ModelAndView();
        mav.setViewName("hello");
        //mav.getModel().put(key, value)
        return mav;
    }

}
HelloController

除了实现Controller接口,也可以继承AbstractController 类。

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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    哈哈哈哈哈哈哈哈哈
</body>
</html>
hello.jsp

当然关于上面这两种方式,不一定经常用,关于使用注解比较多。使用注解的配置可以参加“SpringMVC之基于注解的实现SpringMVC+MySQL”

参考文章

posted @ 2016-12-28 14:47  HDWK  阅读(1215)  评论(0编辑  收藏  举报