首页 > 代码库 > 02springmvc注解入门

02springmvc注解入门

1、建立maven web项目
2、项目pom.xml 添加
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>

3、编写servlet3 注解类 相当于web.xml配置
package com.fz.servlet;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
/**
* Created by webrx on 2017-06-24.
*/
@WebServlet(name = "springmvc", urlPatterns = {"/"}, loadOnStartup = 1,
initParams = {@WebInitParam(name = "contextConfigLocation", value = "http://www.mamicode.com/classpath:smvc.xml")})
public class SpringServlet extends DispatcherServlet {
}

4、在src/main/resources/smvc.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-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.fz.controller" />

<!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="http://www.mamicode.com/"></property>
<property name="suffix" value="http://www.mamicode.com/.jsp"></property>
</bean>
</beans>

5、编写控制器
package com.fz.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by webrx on 2017-06-24.
*/

//注解当前类为控制器类
@Controller
public class Hello {
//控制器映射方法 可以访问 http://localhost/show.action
//@ResponseBody 相当于不使用模板渲染,直接在当前输出
@RequestMapping("/show.action") @ResponseBody
public void show(){
System.out.println("show.......");
}

@RequestMapping("/user") @ResponseBody
public void user(HttpServletRequest req, HttpServletResponse res) throws IOException {
res.setCharacterEncoding("utf-8");
res.setContentType("text/html;charset=utf-8");
PrintWriter out = res.getWriter();
out.print("Hello-springmvc");
out.flush();
out.close();
System.out.println("show.......");
}

@RequestMapping("/test")
public ModelAndView test(){
ModelAndView mv = new ModelAndView("test"); // /test.jsp
mv.addObject("name","李四四");
return mv;
}
}

6、直接运行测试
http://localhost/test
http://localhost/user
http://localhost/show.action

02springmvc注解入门