SpringMVC学习第一章:HelloWorld

来源:互联网 发布:java 日志级别设置 编辑:程序博客网 时间:2024/05/16 11:43

今天开始学习SpringMVC,以前偶尔也看过,现在想系统的学习下,准备从SpringMVC—Spring boot—Spring cloud


整体思路

1、新建web项目(需要勾选自动创建web.xml的选项,否则不生成web.xml文件);

2、导入Spring相应的包(spring-aop-version.jar、spring-beans-3.2.0.M1.jar、context、core、expression、web、webmvc、logging等包,不过在启动环境的时候Tomcat报错了,后来发现还需要导入asm的jar包);

3、导入jar包后,需要配置web.xml文件,今天只是看到在web.xml中需要配置请求的拦截器,以及配置springmvc.xml文件的名称以及路径,示例如下:

<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<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>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

4、创建对应的springmvc.xml文件,该文件在本次学习中的作用是:配置Spring的扫描包以便注解可以正常使用,还可以配置视图解析器,方便返回组装后返回前台;

<!-- 配置自定义字段扫描包以及配置视图解析器-->
<context:component-scan base-package="icss.lqh.com"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

5、创建控制类,也就是创建HelloWorld.jar,示例如下:

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


@Controller
public class HelloWorld {

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


}

@Controller:表示该类为控制类

@RequestMapping(""):表示请求映射到该方法

6、编写前台页面并测试,如果你想在浏览器里面看的话,路径上需要把项目名称也带上.

最后:注意事项,在本项目中,遇到了一些麻烦,比如:xml中不提示包名,需要找到对应的Eclipse的版本安装插件,插件地址: http://dist.springsource.com/release/TOOLS/update/e4.3/,安装速度并不快。


在使用@RequestMapping用在注解类的时候需要注意:如果注解了类,在Spring配置文件中,配置试图解析器时如:<property name="prefix" value="/WEB-INF/views/"></property>,一定要在WEB-INF前面加上斜线,否则在组装返回路径时,父路径也会组装到返回的地址上面。

原创粉丝点击