配置注解
映射器、适配器、视图解析器:在springmvc中有默认配置,可以偷懒省略不写,但为了书写方便,配置视图解析器
<?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:beans="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<!-- 映射器、适配器、视图解析器:在springmvc中有默认配置,可以偷懒省略不写,但为了书写方便,配置视图解析器-->
<!--<!– 映射器–>-->
<!-- <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>-->
<!--<!– 适配器–>-->
<!-- <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>-->
<!--<!– 配置handle–>-->
<!-- <bean id="/hello.do" class="com.sky.controller.HelloController"></bean>-->
<!-- 启动springmvc的注解驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 注解的扫描包-->
<context:component-scan base-package="com.sky.controller"></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>
</beans>
java代码
package com.sky.controller;
import com.sky.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/hell")
public class HelloController{
// 根据所有的用户信息
// 处理 go.do 这个请求,RequestMapping:请求映射的注解
// 用户的请求如何到达指定的方法,类上的请求 + 方法上的地址
// 如 : http://localhost:8080/springmvc/hell/he.do
// 如果想要使用 servlet 对象,直接在方法的参数中进行声明
@RequestMapping("/he.do")
public String go(HttpServletRequest request){
User user1 = new User(1, "高兴", '男');
User user2 = new User(2, "开心", '女');
User user3 = new User(3, "快乐", '男');
List users = new ArrayList();
users.add(user1);
users.add(user2);
users.add(user3);
request.setAttribute("users",users);
System.out.println("gogo");
return "first"; // "first"就是视图名称,默认是转发
}
}