SpringMVC学习(一):搭建SpringMVC-注解-非注解
文章参考:http://www.cnblogs.com/Sinte-Beuve/p/5730553.html
一、环境搭建:
目录结构:
引用的JAR包:
如果是Maven搭建的话pom.xml配置依赖如下:
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.yoki.edu</groupId> <artifactId>SpringMvcTest</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>SpringMvcTest Maven Webapp</name> <url>http://maven.apache.org</url> <!--项目依赖 --> <dependencies> <!--日志包--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> </dependency> <!--j2ee相关包 servlet、jsp、jstl--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--mysql驱动包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <!--spring相关包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.1.RELEASE</version> </dependency> <!--其他需要的包--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> </dependencies> <build> <finalName>SpringMvcTest</finalName> </build> </project>
二、代码的编写:
web.xml文件的配置:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <!--配置首页--> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!--配置springmvc DispatcherServlet--> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!--指定SpringMVC的配置文件,如果不配置这一项默认为"[servlet-name]-servlet.xml"--> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.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> </web-app>
spring-mvc.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-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--启用spring的一些annotation --> <context:annotation-config/> <!-- 配置注解驱动 可以将request参数与绑定到controller参数上 --> <mvc:annotation-driven/> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="org.yoki.edu"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--HandlerMapping 无需配置,springmvc可以默认启动--> <!--静态资源映射--> <!--本项目把静态资源放在了WEB-INF的statics目录下,资源映射如下--> <!--<mvc:resources mapping="/css/**" location="/WEB-INF/statics/css/"/>--> <!--<mvc:resources mapping="/js/**" location="/WEB-INF/statics/js/"/>--> <!--<mvc:resources mapping="/image/**" location="/WEB-INF/statics/image/"/>--> <!--但是项目部署到linux下发现WEB-INF的静态资源会出现无法解析的情况,但是本地tomcat访问正常,因此建议还是直接把静态资源放在webapp的statics下,映射配置如下--> <mvc:resources mapping="/css/**" location="/statics/css/"/> <mvc:resources mapping="/js/**" location="/statics/js/"/> <mvc:resources mapping="/image/**" location="/statics/image/"/> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀(如果最后一个还是表示文件夹,则最后的斜杠不要漏了) 使用JSP--> <!-- 默认的视图解析器 在上边的解析错误时使用 (默认使用html)- --> <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/view/"/><!--设置JSP文件的目录位置--> <property name="suffix" value=".jsp"/> </bean> <!-- springmvc文件上传需要配置的节点--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="20971500"/> <property name="defaultEncoding" value="UTF-8"/> <property name="resolveLazily" value="true"/> </bean> <!--非注解方式配置Controller--> <!-- MVC 配置 --> <bean id="noAnnocationController" class="org.yoki.edu.controller.NoAnnocationController"> <!-- <property name="commandClass"> <value>com.vo.User</value> </property> --> </bean> <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="noAnnocation">noAnnocationController</prop> </props> </property> </bean> </beans>
配置log4j.properties:
日志文件是debug中一个必不可少的工具,因此添加了log4j日志包。配置文件如下。
#配置根Logger 后面是若干个Appender log4j.rootLogger=DEBUG,A1,R #log4j.rootLogger=INFO,A1,R # ConsoleAppender 输出 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%c]-[%p] %m%n # File 输出 一天一个文件,输出路径可以定制,一般在根路径下 log4j.appender.R=org.apache.log4j.DailyRollingFileAppender log4j.appender.R.File=log.txt log4j.appender.R.MaxFileSize=500KB log4j.appender.R.MaxBackupIndex=10 log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n
Controller层AnnocationController.java文件的编写:
package org.yoki.edu.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * Created by SunnyWen on 2017/6/3. */ @Controller @RequestMapping("/annocation") public class AnnocationController { //添加一个日志器 private static final Logger logger = LoggerFactory.getLogger(AnnocationController.class); //映射一个action @RequestMapping("/index") public String index(){ //输出日志文件 logger.info("the first jsp pages"); //返回一个index.jsp这个视图 return "index_annocation"; } }
Controller层NoAnnocationController.java文件的编写:
package org.yoki.edu.controller; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by SunnyWen on 2017/6/3. */ public class NoAnnocationController implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { //返回ModelAndView ModelAndView modelAndView = new ModelAndView(); //相当 于request的setAttribut,在jsp页面中通过itemsList取数据 modelAndView.addObject("nameString", "yoki"); //指定视图 modelAndView.setViewName("index_noAnnocation"); return modelAndView; } }
/WEB-INF/index.jsp
<html> <body> <h2>Hello World!</h2> </body> </html>
/WEB-INF/view/index_annocation.jsp
<html> <body> <h2>Hello! This AnnocationController !!</h2> </body> </html>
/WEB-INF/view/index_noAnnocation.jsp
<html> <body> <h2>Hello! This noAnnocationController !!</h2> </body> </html>
3、打包放入web容器中运行