spring mvc基础篇(十一):注解配置深入

本文介绍SpringMVC中使用注解配置请求路径的方法,包括类级别的请求映射及自动表单绑定。通过具体案例展示了如何利用@RequestParam和@PathVariable进行参数绑定,以及@ModelAttribute在模型驱动中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

11.1引言

在上一章的案例中,我们通过为方法配置请求路径来进行访问,而这一章我们将为类配置一个请求实例,这种类似于struts2中package-namespace。另外,我们还会学习到自动表单的注解,作用类似于struts2的模型驱动action。

 

11.2 开发环境

开发工具:myeclipse8.6.1

数据库:mysql5.5.23

服务器: tomcat6.0.37

框架版本: spring3.2.2

 

11.3 案例开发步骤

步骤一:在myeclipse8.6中新建web工程springmvc11,拷贝如下包到lib目下:

 

步骤二:编写web.xml 配置文件,代码如下:

=================================web.xml========================

<?xmlversion="1.0" encoding="UTF-8"?>

<web-appversion="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee

http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 

<!-- 配置spring的字符集过滤 -->

  <filter>

    <filter-name>encode</filter-name>

    <filter-class>org.springframework.web.filter

.CharacterEncodingFilter</filter-class>

    <init-param>

      <param-name>encoding</param-name>

      <param-value>UTF-8</param-value>

    </init-param>

    <init-param>

         <param-name>forceEncoding</param-name>

         <param-value>true</param-value>

    </init-param>

  </filter>

  <filter-mapping>

    <filter-name>encode</filter-name>

    <url-pattern>/*</url-pattern>

</filter-mapping>

<servlet>

<servlet-name>springmvc</servlet-name>

<servlet-class>

org.springframework.web.servlet.DispatcherServlet

</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>springmvc</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

</web-app>

================================================================

 

步骤三:建立index.jsp,和hello.jsp,如下所示:

=========================index.jsp==============================

<body>

<h1><a href="root/show.do?theName=阿迪丽娜">点击我</a></h1>

 

<form action="root/path/jack.do"name="myFrm" method="post">

    <p><input type="submit" value="提交"/></p>

</form>

</body>

====================================================================

=========================hello.jsp==============================

<body>

<h1>查看信息:${requestScope.msg}</h1>

<h1>查看信息:${requestScope.pathName }</h1>

<h1>注册用户:${requestScope.myUser.email }</h1>

</body>

=====================================================================

 

步骤四:在com.wx.controls包下面编写控制器ClassAnnotationControl.java,如下:

================== ClassAnnotationControl.java======================

import java.io.UnsupportedEncodingException;

importjavax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.PathVariable;

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

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.servlet.ModelAndView;

 

@Controller

@RequestMapping("/root")

public class ClassAnnotationControl {

   

    @RequestMapping("/show.do")

    public ModelAndView showParam(@RequestParam String theName){

       ModelAndView mav=new ModelAndView("hello");

       try {

           theName=new String(theName.getBytes("iso-8859-1"),"utf-8");

       } catch (UnsupportedEncodingException e) {

           e.printStackTrace();

       }

       mav.addObject("msg", theName);

       return mav;

    }

   

    @RequestMapping("/path/{name}.do")

    public String showPathParam(@PathVariable String name,HttpServletRequestrequest){

       request.setAttribute("pathName", name);

       return "hello";

    }

}

 ==================================================================

知识讲解:(1)访问showParam方法

这样如果想访问到上面的两个方法都必须是以root作为开头。下面我们先对showParam方法进行访问测试,注意index.jsp页面中的如下代码:

<h1><a href="root/show.do?theName=阿迪丽娜">点击我</a></h1>

这样提交请求时,将会访问到showParam方法,并且theName会作为参数传递给此方法,这样我们便可以得到客户端输入的theName。@RequestParam注解:Annotation which indicates that amethod parameter should be bound to a web request parameter,意为此注解将会为方法中的参数绑定对应(对应是指名字上,比如这里表单和方法中参数名都用了theName)的web请求参数。强调:访问路径必须是以root作为一个基路径,因为类上配置了请求基路

径。@RequestParam注解实现web请求到方法参数的绑定。

(2)访问showPathParam方法

对于showPathParam方法它的访问路径应该是这样的:…/root/path/jack.do 这样我们得到@PathVariable:

Annotationwhich indicates that a method parameter should be bound to a URI templatevariable,意思是此注解将会把一个uri路径中对应的变量和方法中的参数绑定,这里我们用jack来代替来{name},所以实质就是把jack作为参数和方法中name参数绑定,如果想传递其它值,只须把jack换下就可以了,比如:…/root/path/tom.do等。

==================================================================

 

下面进行自动表单的开发步骤:

步骤五:建立Register.jsp,如下所示:

=========================Register.jsp==============================

<body>

<div id="show">

    <h2 align="center">用户注册</h2>

    <form action="showUser.do" method="post">

       <table border="1px"cellspacing="0">

           <tr><td>请输入用户名:</td><td><input type="text" name="userName"/></td></tr>

           <tr><td>请输入密码:</td><td><input type="password" name="pwd1"/></td></tr>

           <tr><td>请再次输入密码:</td><td><input type="password" name="pwd2"/></td></tr>

           <tr><td>请输入真实姓名:</td><td><input type="text" name="realName"/></td></tr>

           <tr><td>请输入电子邮箱:</td><td><input type="text" name="email"/></td></tr>

           <tr><td>请输入联系电话:</td><td><input type="text" name="phone"/></td></tr>

           <tr><td colspan="2"><input type="submit" value="提交"/>&nbsp;

               <input type="reset" value="重置"/></td></tr>

       </table>

    </form>

</div>

</body>

====================================================================

 

步骤六:建立实体类和控制器类

在com.wx.entitys包下面编写实体类UserEntity.java,如下:

==================UserEntity.java======================

public class UserEntity {

    private String userName;

    private String pwd1;

    private String realName;

    private String email;

    private String phone;

   

    public String getUserName() {

       return userName;

    }

//….

}

 ==================================================================

 

在com.wx.controls包下面编写控制器ModelDrivenAnno.java,如下:

================== ModelDrivenAnno.java======================

import javax.servlet.http.HttpServletRequest;

importorg.springframework.stereotype.Controller;

importorg.springframework.web.bind.annotation.ModelAttribute;

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

import com.wx.entitys.UserEntity;

@Controller

public class ModelDrivenAnno{

    /*

     * 执行流程:当前请求定位到这个类时,根据@ModelAttribute("theUser")的配置

     * 先执行initTheUser(注意和注解里面的参数theUser的关系,多了个init,这是系统

     * 设定的),然后会把注册表单里面的值给user对象初始化

     */

    @ModelAttribute("theUser")

    public UserEntity initTheUser(){

       UserEntity user=new UserEntity();

       System.out.println("这里执行了2222");

       return user;

    }

   

    /*

     * @ModelAttribute注解会把theUser对象赋值给user参数

     */

    @RequestMapping("/showUser.do")

    public String showUser(@ModelAttribute UserEntity user,

           HttpServletRequestrequest){

       request.setAttribute("myUser", user);

       return "hello";

    }

}

 ==================================================================

知识讲解:@ModelAttribute :Annotation that binds a method parameter ormethod return value to a named model attribute,exposed to a web view. Supportedfor RequestMapping annotated handler classes,此注解可以用于web请求参数和方法参数的绑定,也可用于方法的返回值作为模型数据(这种模型数据在类中全局有效,比如这里initTheUser方法绑定的模型数据在此类的任何方法中都能访问到这种模型数据)。

 

步骤七:在核心配置文件springmvc-servlet.xml里面完善如下配置

======================== springmvc-servlet.xml=======================

<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"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

                          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

                          http://www.springframework.org/schema/context

                          http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- 配置自动扫描 -->

    <context:component-scan base-package="com.wx.controls"></context:component-scan>

    <bean id="irvResolver"

       class="org.springframework.web.servlet.view.InternalResourceViewResolver">

       <property name="prefix" value="/"></property>

       <property name="suffix" value=".jsp"></property>

    </bean>

   

</beans>

====================================================================

 

步骤八: 启动tomcat,发布项目,在地址栏输入 http://localhost:8080/springmvc11/index.jsp 进行测试,观察结果。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

御前两把刀刀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值