Spring MVC学习笔记(3)

来源:互联网 发布:前端如何请求后台数据 编辑:程序博客网 时间:2024/05/29 12:22

前面一篇中action的配置是在servletname-servlet.xml中添加bean:

 <bean name="/hello" class= "action.HelloWorldController"/>

如上,需要在xml中配置请求“/hello”对应的处理类。

使用注解方式,就不需要在xml重配置,直接在处理类中在对应的方法上加注解。

使用注解方法,需要在servletname-servlet.xml中添加:

<!--添加注解方法-->    <mvc:annotation-driven />

然后还要加一句扫描配置,声明哪些类是需要扫描注解的。

<context:component-scan base-package="no.*"></context:component-scan>

就是说“no.”开头的包都需要扫描。

然后新建一个“no.action”包,在里面新建一个UserAction类:

package no.action;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@Controllerpublic class UserAction {@RequestMapping("/list")public ModelAndView list(){String user="一个新用户";ModelAndView mol=new ModelAndView();mol.addObject("user", user);mol.setViewName("/list");return mol;}}


类上面标注@Controllor表示implements Controller ,spring扫描到这个注解就可以认为这是一个Controller

在方法list()上面标注一个@RequestMapping("/list") ,表示“/list”的url由这个方法进行处理。

经过list()处理后,返回到“/WEB-INF/jsp/list.jsp”:

新建list页面:

<%@ 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>list</title></head><body>这里是list页面<div>${user }</div></body></html>


请求 http://localhost:8080/springexample/list 后得到页面:


0 0
原创粉丝点击