使用springMVC搭建一个web项目
网站首页 文章专栏 使用springMVC搭建一个web项目
使用springMVC搭建一个web项目
编辑时间:2019-05-15 18:12 作者:毛毛小妖 浏览量:30 评论数:0

一、WHAT

Spring MVC属于SpringFrameWork的衍生产品,从而在使用Spring进行WEB开发时,可以选择使用Spring的SpringMVC框架或集成其他MVC开发框架,比如Struts2。

二、HOW

1、环境准备

eclipse,tomcat7,jdk1.8

2、新建maven项目,目录结构如下

3、修改pom文件,加入spring相关依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.eyesmoons</groupId>
	<artifactId>springmvcDemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springmvcDemo</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<spring.version>3.1.1.RELEASE</spring.version>
		<slf4j.version>1.7.7</slf4j.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.6.12</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.6.12</version>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<!-- common-logging 实际调用slf4j -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<!-- java.util.logging 实际调用slf4j -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jul-to-slf4j</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
	</dependencies>
</project>

4、修改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">

    <!-- spring监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<filter>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<!-- DispatcherServlet -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springview.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<!-- 字符集过滤器,防止乱码 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
		<url-pattern>/</url-pattern>
	</filter-mapping>

</web-app>

5、新建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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
 
 
        <!-- 配置自动扫描的包 -->
        <context:component-scan base-package="com.eyesmoons.springmvcDemo"></context:component-scan>
 		<!-- 为了使用jackson的json -->
        <mvc:annotation-driven />
 		
        <!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name = "prefix" value="/WEB-INF/views/"></property>
            <property name = "suffix" value = ".jsp"></property>
        </bean>
</beans>

6、log4j.properties

log4j.rootLogger=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

7、写好视图文件(webapp/WEB-INF/views目录下)

inedx.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>界面标题</title>
</head>
<body>
 
<a href="success">hello world</a>
 
</body>
</html>

success.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>成功界面</title>
</head>
<body>
 
<h4>恭喜您成功了</h4>
 
</body>
</html>

8、新建controller

HelloWorldController.java

package com.eyesmoons.springmvcDemo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/helloworld")
public class HelloWorldController {

	@RequestMapping("/index")
	public String index() {
		System.out.println("index");
        return "index";
    }
	
	@RequestMapping("/success")
	public String success() {
        System.out.println("success");
        return "success";
    }
}

9、新建tomcat,将项目运行起来,访问http://ip:端口/springmvcDemo/index,如下

三、注意的问题

1、SpringMVC配置文件的名字

SpringMVC配置文件的默认路径是WEB-INF,并且配置文件的name默认应该是你配置的DispatcherServlet的servlet-name+servlet.xml。因此,如果你配置文件放在WEB-INF目录下,但名字不想按照那个格式,可以通过namespace这个初始化参数进行指定

<init-param>
    <!-- 如果springmvc的配置文件放在WEB-INF目录下,但不想名字的形式为*-servlet.xml,则可以通过namespace属性值进行指定 -->
    <param-name>namespace</param-name>
    <param-value>springmvc</param-value>
</init-param>

如果你的配置文件不想放在WEB-INF目录下,则通过contextConfigLocation这个初始化参数进行指定,比如放在src/resources下

<init-param>
    <!-- 默认Springmvc的配置文件是在WEB-INF目录下,如果要放在其他目录,则需要指定 -->
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springmvc.xml</param-value>

    <!-- 如果springmvc的配置文件放在WEB-INF目录下,但不想名字的形式为*-servlet.xml,则可以通过namespace属性值进行指定 -->
    <!-- <param-name>namespace</param-name>
    <param-value>springmvc</param-value> -->
</init-param>

2、访问静态资源的问题,如图片,css,js

一般我们会配置成“/”来匹配所有的servlet,这时会拦截所有请求,静态资源文件会访问出错。我们可以通过以下几种方法来解决。

方法一使用tomcat默认的servlet

在web.xml中这样配置

<servlet>
    <servlet-name>default</servlet-name>
    <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
    <init-param>
        <param-name>debug</param-name>
        <param-value>0</param-value>
    </init-param>
    <init-param>
        <param-name>listings</param-name>
        <param-value>false</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.jpg</url-pattern>
  </servlet-mapping>
  
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.png</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.css</url-pattern>
</servlet-mapping>

方法二、使用mvc:default-servlet-handler解决

我们得先在springmvc.xml中引入mvc的约束

xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd

只需在springmvc.xml中添加一条语句即可

<mvc:default-servlet-handler/>

方法三、使用mvc:resources解决

只需要springmvc.xml中加入下面的语句即可

<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/images/**" location="/images/" />

3、注解的配置

<context:annotation-config>提供了基本注解的支持,比如@Required, @Autowired, @PostConstruct
<mvc:annotation-driven />实际上没有任何意义,它声明对注解驱动的MVC控制器的显式支持,比如@RequestMapping, @Controller,尽管这些是默认支持的。我的建议是如果实在不想从Jackson获得json的支持,就不要配置这个<mvc:annotation-driven />
<context:component-scan>做了<context:annotation-config>要做的事情,还额外支持@Component,@Repository,@Service,@Controller @RestController,@ControllerAdvice, and @Configuration注解。所以配置<context:component-scan>就不需要配置<context:annotation- config/>

来说两句吧
最新评论
    还没有人评论哦,快来坐沙发吧!