springmvc入门基础之注解和参数传递
一、SpringMVC注解入门
1. 创建web项目
2. 在springmvc的配置文件中指定注解驱动,配置扫描器
- <!-- mvc的注解驱动 -->
- <mvc:annotation-driven />
- <!--只要定义了扫描器,注解驱动就不需要,扫描器已经有了注解驱动的功能 -->
- <context:component-scan base-package="org.study1.mvc.controller" />
- <!-- 前缀+ viewName +后缀 -->
- <bean
- class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <!-- WebContent(WebRoot)到某一指定的文件夹的路径 ,如下表示/WEB-INF/view/*.jsp -->
- <property name="prefix" value="/WEB-INF/view/"></property>
- <!-- 视图名称的后缀 -->
- <property name="suffix" value=".jsp"></property>
- </bean>
<context:component-scan/> 扫描指定的包中的类上的注解,常用的注解有:
@Controller 声明Action组件
@Service 声明Service组件 @Service("myMovieLister")
@Repository 声明Dao组件
@Component 泛指组件, 当不好归类时.
@RequestMapping("/menu") 请求映射
@Resource 用于注入,( j2ee提供的 ) 默认按名称装配,@Resource(name="beanName")
@Autowired 用于注入,(srping提供的) 默认按类型装配
@Transactional( rollbackFor={Exception.class}) 事务管理
@ResponseBody
@Scope("prototype") 设定bean的作用
3. @controller:标识当前类是控制层的一个具体的实现
4. @requestMapping:放在方法上面用来指定某个方法的路径,当它放在类上的时候相当于命名空间需要组合方法上的requestmapping来访问。
- @Controller // 用来标注当前类是springmvc的控制层的类
- @RequestMapping("/test") // RequestMapping表示 该控制器的唯一标识或者命名空间
- public class TestController {
- /**
- * 方法的返回值是ModelAndView中的
- */
- @RequestMapping("/hello.do") // 用来访问控制层的方法的注解
- public String hello() {
- System.out.println("springmvc annotation... ");
- return "jsp1/index";
- }
- //*****
- }
在本例中,项目部署名为mvc,tomcat url为 http://localhost,所以实际为:http://localhos/mvc
在本例中,因为有命名空间 /test,所以请求hello方法地址为:http://localhost/mvc/test/hello.do
输出:springmvc annotation...
二、注解形式的参数接收
1. HttpServletRequest可以直接定义在参数的列表,通过该请求可以传递参数
url:http://localhost/mvc/test/toPerson.do?name=zhangsan
- /**
- * HttpServletRequest可以直接定义在参数的列表,
- *
- */
- @RequestMapping("/toPerson.do")
- public String toPerson(HttpServletRequest request) {
- String result = request.getParameter("name");
- System.out.println(result);
- return "jsp1/index";
- }
可以从HttpServletRequest 取出“name”属性,然后进行操作!如上,可以取出 “name=zhangsan”
输出:zhangsan
2. 在参数列表上直接定义要接收的参数名称,只要参数名称能匹配的上就能接收所传过来的数据, 可以自动转换成参数列表里面的类型,注意的是值与类型之间是可以转换的
2.1传递多种不同类型的参数:
url:http://localhost/mvc/test/toPerson1.do?name=zhangsan&age=14&address=china&birthday=2000-2-11
- /**
- * 传递的参数的名字必须要与实体类的属性set方法后面的字符串匹配的上才能接收到参数,首字符的大小写不区分
- * 请求中传的参数只要是能和参数列表里面的变量名或者实体里面的set后面的字符串匹配的上就能接收到 a
- *
- */
- @RequestMapping("/toPerson1.do")
- public String toPerson1(String name, Integer age, String address,
- Date birthday) {
- System.out.println(name + " " + age + " " + address + " " + birthday);
- return "jsp1/index";
- }
- /**
- * 注册时间类型的属性编辑器,将String转化为Date
- */
- @InitBinder
- public void initBinder(ServletRequestDataBinder binder) {
- binder.registerCustomEditor(Date.class, new CustomDateEditor(
- new SimpleDateFormat("yyyy-MM-dd"), true));
- }
输出:zhangsan 14 china Fri Feb 11 00:00:00 CST 2000
2.2传递数组:
url:http://localhost/mvc/test/toPerson2.do?name=tom&name=jack
- /**
- * 对数组的接收,定义为同名即可
- */
- @RequestMapping("/toPerson2.do")
- public String toPerson2(String[] name) {
- for (String result : name) {
- System.out.println(result);
- }
- return "jsp1/index";
- }
输出:tom jack
2.3传递自定义对象(可多个):
url:http://localhost/mvc/test/toPerson3.do?name=zhangsan&age=14&address=china&birthday=2000-2-11
User 定义的属性有:name,age,并且有各自属性的对应的set方法以及toString方法
Person定义的属性有:name,age.address,birthday,并且有各自属性的对应的set方法以及toString方法
- /**
- *
- * 传递的参数的名字必须要与实体类的属性set方法后面的字符串匹配的上才能接收到参数,首字符的大小写不区分
- * 请求中传的参数只要是能和参数列表里面的变量名或者实体里面的set后面的字符串匹配的上就能接收到
- *
- */
- @RequestMapping("/toPerson3.do")
- public String toPerson3(Person person, User user) {
- System.out.println(person);
- System.out.println(user);
- return "jsp1/index";
- }
输出:
Person [name=zhangsan, age=14, address=china, birthday=Fri Feb 11 00:00:00 CST 2000]
User [name=zhangsan, age=14]
自动封装了对象,并且被分别注入进来!
三、注解形式的结果返回
1. 数据写到页面,方法的返回值采用ModelAndView, new ModelAndView("index", map);,相当于把结果数据放到response里面
url:http://localhost/mvc/test/toPerson41.do
url:http://localhost/mvc/test/toPerson42.do
url:http://localhost/mvc/test/toPerson43.do
url:http://localhost/mvc/test/toPerson44.do
- /**
- * HttpServletRequest可以直接定义在参数的列表,并且带回返回结果
- *
- */
- @RequestMapping("/toPerson41.do")
- public String toPerson41(HttpServletRequest request) throws Exception {
- request.setAttribute("p", newPesion());
- return "index";
- }
- /**
- *
- * 方法的返回值采用ModelAndView, new ModelAndView("index", map);
- * ,相当于把结果数据放到Request里面,不建议使用
- *
- */
- @RequestMapping("/toPerson42.do")
- public ModelAndView toPerson42() throws Exception {
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("p", newPesion());
- return new ModelAndView("index", map);
- }
- /**
- *
- * 直接在方法的参数列表中来定义Map,这个Map即使ModelAndView里面的Map,
- * 由视图解析器统一处理,统一走ModelAndView的接口,也不建议使用
- */
- @RequestMapping("/toPerson43.do")
- public String toPerson43(Map<String, Object> map) throws Exception {
- map.put("p", newPesion());
- return "index";
- }
- /**
- *
- * 在参数列表中直接定义Model,model.addAttribute("p", person);
- * 把参数值放到request类里面去,建议使用
- *
- */
- @RequestMapping("/toPerson44.do")
- public String toPerson44(Model model) throws Exception {
- // 把参数值放到request类里面去
- model.addAttribute("p", newPesion());
- return "index";
- }
- /**
- * 为了测试,创建一个Persion对象
- *
- */
- public Person newPesion(){
- Person person = new Person();
- person.setName("james");
- person.setAge(29);
- person.setAddress("maami");
- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
- Date date = format.parse("1984-12-28");
- person.setBirthday(date);
- return person;
- }
以上四种方式均能达到相同的效果,但在参数列表中直接定义Model,model.addAttribute("p", person);把参数值放到request类里面去,建议使用
2. Ajax调用springmvc的方法:直接在参数的列表上定义PrintWriter,out.write(result);把结果写到页面,建议使用的
url:http://localhost/mvc/test/toAjax.do
- /**
- *
- * ajax的请求返回值类型应该是void,参数列表里直接定义HttpServletResponse,
- * 获得PrintWriter的类,最后可把结果写到页面 不建议使用
- */
- @RequestMapping("/ajax1.do")
- public void ajax1(String name, HttpServletResponse response) {
- String result = "hello " + name;
- try {
- response.getWriter().write(result);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- *
- * 直接在参数的列表上定义PrintWriter,out.write(result);
- * 把结果写到页面,建议使用的
- *
- */
- @RequestMapping("/ajax2.do")
- public void ajax2(String name, PrintWriter out) {
- String result = "hello " + name;
- out.write(result);
- }
- /**
- * 转向ajax.jsp页面
- */
- @RequestMapping("/toAjax.do")
- public String toAjax() {
- return "ajax";
- }
ajax页面代码如下:
- <script type="text/javascript" src="js/jquery-1.6.2.js"></script>
- <script type="text/javascript">
- $(function(){
- $("#mybutton").click(function(){
- $.ajax({
- url:"test/ajax1.do",
- type:"post",
- dataType:"text",
- data:{
- name:"zhangsan"
- },
- success:function(responseText){
- alert(responseText);
- },
- error:function(){
- alert("system error");
- }
- });
- });
- });
- </script>
- </head>
- <body>
- <input id="mybutton" type="button" value="click">
- </body>
四、表单提交和重定向
1、表单提交:
请求方式的指定:@RequestMapping( method=RequestMethod.POST )可以指定请求方式,前台页面就必须要以它制定好的方式来访问,否则出现405错误
表单jsp页面:
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>SpringMVC Form</title>
- </head>
- <body>
- <form action="test/toPerson5.do" method="post">
- name:<input name="name" type="text"><br>
- age:<input name="age" type="text"><br>
- address:<input name="address" type="text"><br>
- birthday:<input name="birthday" type="text"><br>
- <input type="submit" value="submit"><br>
- </form>
- </body>
- </html>
对应方法为:
- /**
- * 转向form.jsp页面
- * @return
- */
- @RequestMapping("/toform.do")
- public String toForm() {
- return "form";
- }
- /**
- *
- * @RequestMapping( method=RequestMethod.POST)
- * 可以指定请求方式,前台页面就必须要以它制定好的方式来访问,否则出现405错误 a
- *
- */
- @RequestMapping(value = "/toPerson5.do", method = RequestMethod.POST)
- public String toPerson5(Person person) {
- System.out.println(person);
- return "jsp1/index";
- }
- /**
- *
- * controller内部重定向
- * redirect:加上同一个controller中的requestMapping的值
- *
- */
- @RequestMapping("/redirectToForm.do")
- public String redirectToForm() {
- return "redirect:toform.do";
- }
- /**
- *
- * controller之间的重定向:必须要指定好controller的命名空间再指定requestMapping的值,
- * redirect:后必须要加/,是从根目录开始
- */
- @RequestMapping("/redirectToForm1.do")
- public String redirectToForm1() {
- //test1表示另一个Controller的命名空间
- return "redirect:/test1/toForm.do";
- }
springmvc入门基础之注解和参数传递的更多相关文章
- SpringMVC入门(基于注解方式实现)
---------------------siwuxie095 SpringMVC 入门(基于注解方式实现) SpringMVC ...
- Springmvc入门基础(五) ---controller层注解及返回类型解说
0.@Controller注解 作用:通过@Controller注解,注明该类为controller类,即控制器类,需要被spring扫描,然后注入到IOC容器中,作为Spring的Bean来管理,这 ...
- SpringMVC入门和常用注解
SpringMVC的基本概念 关于 三层架构和 和 MVC 三层架构 我们的开发架构一般都是基于两种形式,一种是 C/S 架构,也就是客户端/服务器,另一种是 B/S 架构,也就 是浏览器服务器.在 ...
- Springmvc入门基础(四) ---参数绑定
1.默认支持的参数类型 处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值. 除了ModelAndView以外,还可以使用Model来向页面传递数据, Model是一个接口,在参数里直接声明 ...
- Springmvc入门基础(一) ---基于idea创建demo项目
Springmvc是什么 Springmvc和Struts2都属于表现层的框架,它是Spring框架的一部分,我们可以从Spring的整体结构中看得出来,如下图: Springmvc处理流程 ---- ...
- <SpringMvc>入门二 常用注解
1.@RequestMapping @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME ...
- Springmvc入门基础(三) ---与mybatis框架整合
1.创建数据库springmvc及表items,且插入一些数据 DROP TABLE IF EXISTS `items`; CREATE TABLE `items` ( `id` int(11) NO ...
- Springmvc入门基础(二) ---架构详解
1.框架结构图 架构流程文字说明 用户发送请求至前端控制器DispatcherServlet DispatcherServlet收到请求调用HandlerMapping处理器映射器. 处理器映射器根据 ...
- Springmvc入门基础(六) ---拦截器应用demo
1.拦截器定义 Spring Web MVC 的处理器拦截器类似于Servlet 开发中的过滤器Filter,用于对处理器进行预处理和后处理. 2.拦截器demo demo需求: 拦截用户请求,判断用 ...
随机推荐
- 解决oracle11g 空表不能exp导出的问题
在使用exp备份数据库,然后使用imp导入的时候出现了好多表或者视图不存在的错误信息. 究其原因,是11G中增加了一个新的特性:数据条数是0时不分配segment,所以就不能被导出. 解决思路:就是向 ...
- Nginx+lua环境搭建
其实有点类似WampServer一站式安装包 wget http://openresty.org/download/ngx_openresty-1.7.10.1.tar.gz tar -zxvf ng ...
- 1080P、720P、4CIF、CIF所需要的理论带宽
转自:http://blog.sina.com.cn/s/blog_64684bf30101hdl7.html 在视频监控系统中,对存储空间容量的大小需求是与画面质量的高低.及视频线路等都有很大关系. ...
- 四种方案解决ScrollView嵌套ListView问题(转)
以下文章转自@安卓泡面 在工作中,曾多次碰到ScrollView嵌套ListView的问题,网上的解决方法有很多种,但是杂而不全.我试过很多种方法,它们各有利弊. 在这里我将会从使用ScrollVie ...
- 剑指offer系列——二维数组中,每行从左到右递增,每列从上到下递增,设计算法找其中的一个数
题目:二维数组中,每行从左到右递增,每列从上到下递增,设计一个算法,找其中的一个数 分析: 二维数组这里把它看作一个矩形结构,如图所示: 1 2 8 2 4 9 12 4 7 10 13 6 8 11 ...
- Struts2文件上传下载
Struts2文件上传 Struts2提供 FileUpload拦截器,用于解析 multipart/form-data 编码格式请求,解析上传文件的内容,fileUpload拦截器 默认在defau ...
- [xsd学习]xsd实例
以下为一个表示学校的xml文件,学校内有若干学生,每个学生都有基本信息,电脑信息,选课信息 <?xml version="1.0" encoding="UTF-8& ...
- 04 DOM一窥
BOM 浏览器对象模型 * window alert(); 弹出框 confirm() 询问框 setInterval("run()",1000); 每隔1秒执行run ...
- Thymeleaf 集成spring
Thymeleaf 集成spring 如需先了解Thymeleaf的单独使用,请参考<Thymeleaf模板引擎使用>一文. 依赖的jar包 Thymeleaf 已经集成了spring的3 ...
- 使用dSYM分析App崩溃日志
前言 我们在开发App过程中,因为连接到控制台,所以遇到问题会很容易找到问题代码.但是对于线上的App出现Crash的时候,我们不可能通过这种方式,也不现实,所以我们只能通过收集Crash信息,来解决 ...