SpringMVC注解开发
注解:
注解就是类似于添加注释,但是又不跟注释完全一样,注解可以理解为将类或者方法与特定的信息进行关联。
一.使用@Controller
@Controller继承@Component注解方法,将其以单例形成放置spring容器中,然后spring会通过配置文件中的<context:component-scan>的配置,进行如下操作
1.扫描class文件,并将包含@Component及元注解为@Component的注解@Controller、@Service、@Repository或者其他自定义的的bean注册到beanFactory中。
2.然后spring在注册处理器
3.实例化处理器,然后将其放到beanPostFactory中,然后我们就可以在类中进行使用了。
4.创建bean时,会自动调用相应的处理器进行处理。
举个具体使用@Controller的实例与@RequestMapping的例子,
UseController.java
package com.zk.Controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller//<bean id="UserController" class="UserController路径"> public class UserController { //@RequestMapping("hello") //访问路径注意更改 //请求映射value="/hello.do", //@RequestMapping("hello") //@RequestMapping("/hello.do") //@RequestMapping(value="/hello.do") @RequestMapping(value="/hello.do",method=RequestMethod.GET) //@RequestMapping(value="/hello.do",method={RequestMethod.GET,RequestMethod.POST}) public String myHello(){ return "hello"; } }
SpringMVC.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:p="http://www.springframework.org/schema/p" 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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:component-scan base-package="com.zk.Controller"></context:component-scan> <!-- 配置注解处理器映射器 功能:寻找执行类Controller --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean> <!-- 配置注解处理器适配器 功能:调用controller方法,执行controller --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
hello.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'Hello.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> Hello,UserController <br> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>Spring_005</display-name> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- Spring 默认加载SpringMVC的配置文件,这个需要满足一下规则: 命名规则:Servlet-name-servlet.xml========>SpringMVC-servlet.xml 路径规范SpringMVC-serlvet.xml必须放在WEB-INF下 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
运行结果如下:
二.向后台传递参数
1.传递string类型参数
可以使用@RequestMapping向后台传递参数
UserController.java
package com.zk.Controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.zk.data.User; import com.zk.data.UserCustom; @Controller//<bean id="UserController" class="UserController路径"> @RequestMapping("/user") public class UserController { @RequestMapping(value="/hello.do",method={RequestMethod.GET,RequestMethod.POST}) public String myHello(){ return "hello"; } @RequestMapping("/receiveInt") public String receiveInt(String id){ try { System.out.println(id); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "success"; } }
SpringMVC.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:p="http://www.springframework.org/schema/p" 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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:component-scan base-package="com.zk.Controller"></context:component-scan> <!-- 配置注解处理器映射器 功能:寻找执行类Controller --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean> <!-- 配置注解处理器适配器 功能:调用controller方法,执行controller --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
hello.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'Hello.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> Hello,UserController <br> <form action="${pageContext.request.contextPath}/user/receiveInt.do" method="post"> <input type="text" id="id" name="id" value="id"/> <input type="submit" value="提交"/> </form> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>Spring_007</display-name> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- Spring 默认加载SpringMVC的配置文件,这个需要满足一下规则: 命名规则:Servlet-name-servlet.xml========>SpringMVC-servlet.xml 路径规范SpringMVC-serlvet.xml必须放在WEB-INF下 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
运行结果:
2.传递对象类型参数
UserController.java
package com.zk.Controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.zk.data.User; import com.zk.data.UserCustom; @Controller//<bean id="UserController" class="UserController路径"> public class UserController { //访问路径注意更改 //请求映射value="/hello.do", //@RequestMapping("hello") //@RequestMapping("/hello.do") //@RequestMapping(value="/hello.do") //@RequestMapping(value="/hello.do",method=RequestMethod.GET) @RequestMapping(value="/hello.do",method={RequestMethod.GET,RequestMethod.POST}) public String myHello(){ return "hello"; } @RequestMapping("receive") public String receiveUser(UserCustom user){ System.out.println(user); //model.addAttribute("user", user); return "success"; } }
User.java
package com.zk.data; public class User { public String Sname; public String Sno; public String Sid; public String getSname() { return Sname; } public void setSname(String sname) { Sname = sname; } public String getSno() { return Sno; } public void setSno(String sno) { Sno = sno; } public String getSid() { return Sid; } public void setSid(String sid) { Sid = sid; } @Override public String toString() { return "User [Sname=" + Sname + ", Sno=" + Sno + ", Sid=" + Sid + "]"; } }
UserCustom.java
package com.zk.data; public class UserCustom { private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String toString() { return "UserCustom [user=" + user + "]"; } }
SpringMVC.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:p="http://www.springframework.org/schema/p" 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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:component-scan base-package="com.zk.Controller"></context:component-scan> <!-- 配置注解处理器映射器 功能:寻找执行类Controller --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean> <!-- 配置注解处理器适配器 功能:调用controller方法,执行controller --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
hello.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'Hello.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <!-- ID:<input type="text" name="id" id="id" />--> Hello,UserController <br> <form action="${pageContext.request.contextPath}/receive.do" method="post"> Sname:<input type="text" name="user.Sname" id="Sname"/> Sid:<input type="text" name="user.Sid" id="Sid"/> Sage:<input type="text" name="user.Sno" id="Sno"/> <input type="submit" value="提交"/> </form> </body> </html>
运行结果如下:
3.传递数组类型参数
hello2.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'Hello.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="${pageContext.request.contextPath}/receiveIds.do" method="post"> <!-- ID:<input type="text" name="id" id="id" />--> <input type="submit" value="提交"/> Id1:<input type="text" name="ids" id="ids" value="1"/> Id1:<input type="text" name="ids" id="ids" value="2"/> Id1:<input type="text" name="ids" id="ids" value="3"/> </form> </body> </html>
UserController.java
package com.zk.Controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.zk.data.User; import com.zk.data.UserCustom; @Controller//<bean id="UserController" class="UserController路径"> public class UserController { @RequestMapping(value="/hello2.do",method={RequestMethod.GET,RequestMethod.POST}) public String myHello2(){ return "hello2"; } //接受数组类型参数 @RequestMapping("receiveIds") public String receiveIds(Integer[] ids){ for(int id:ids){ System.out.println(id); } return "success"; } }
运行结果如下:
4.传递List类型参数
UserController.java
package com.zk.Controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.zk.data.User; import com.zk.data.UserCustom; @Controller//<bean id="UserController" class="UserController路径"> public class UserController { //访问路径注意更改 //请求映射value="/hello.do", //@RequestMapping("hello") //@RequestMapping("/hello.do") //@RequestMapping(value="/hello.do") //@RequestMapping(value="/hello.do",method=RequestMethod.GET) @RequestMapping(value="/hello.do",method={RequestMethod.GET,RequestMethod.POST}) public String myHello(){ return "hello"; } @RequestMapping(value="/hello2.do",method={RequestMethod.GET,RequestMethod.POST}) public String myHello2(){ return "hello2"; } @RequestMapping("receiveList") public String receiveUserList(UserCustom user){ for(int count=0;count<user.getUserList().size();count++){ System.out.println(user.getUserList().get(count)); } //model.addAttribute("user", user); return "success"; } }
User.java
package com.zk.data; public class User { public String Sname; public String Sno; public String Sid; public String getSname() { return Sname; } public void setSname(String sname) { Sname = sname; } public String getSno() { return Sno; } public void setSno(String sno) { Sno = sno; } public String getSid() { return Sid; } public void setSid(String sid) { Sid = sid; } @Override public String toString() { return "User [Sname=" + Sname + ", Sno=" + Sno + ", Sid=" + Sid + "]"; } }
UserCustom.java
package com.zk.data; import java.util.List; public class UserCustom { private User user; private List<User> userList; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public List<User> getUserList() { return userList; } public void setUserList(List<User> userList) { this.userList = userList; } @Override public String toString() { return "UserCustom [user=" + user + "]"; } }
success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form> <!-- ID:<input type="text" name="id" id="id" />--> success </form> </body> </html>
hello.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'Hello.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <!-- ID:<input type="text" name="id" id="id" />--> Hello,UserController <br> <form action="${pageContext.request.contextPath}/receiveList.do" method="post"> Sname:<input type="text" name="userList[0].Sname" id="Sname" value='Sname0'/> Sid:<input type="text" name="userList[0].Sid" id="Sid" value='Sid0'/> Sage:<input type="text" name="userList[0].Sno" id="Sno" value='Sno0'/><br> Sname:<input type="text" name="userList[1].Sname" id="Sname" value='Sname1'/> Sid:<input type="text" name="userList[1].Sid" id="Sid" value='Sid1'/> Sage:<input type="text" name="userList[1].Sno" id="Sno" value='Sno1'/> <input type="submit" value="提交"/> </form> </body> </html>
运行截图:
5.传递Map类型参数
UserController.java
package com.zk.Controller; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.zk.data.User; import com.zk.data.UserCustom; @Controller//<bean id="UserController" class="UserController路径"> public class UserController { //访问路径注意更改 //请求映射value="/hello.do", //@RequestMapping("hello") //@RequestMapping("/hello.do") //@RequestMapping(value="/hello.do") //@RequestMapping(value="/hello.do",method=RequestMethod.GET) @RequestMapping(value="/hello.do",method={RequestMethod.GET,RequestMethod.POST}) public String myHello(){ return "hello"; } @RequestMapping(value="/hello2.do",method={RequestMethod.GET,RequestMethod.POST}) public String myHello2(){ return "hello2"; } @RequestMapping("receiveMap") public String receiveUserMap(UserCustom user){ System.out.println(user.getUsermap().size()); Map<String,Object> usermap=user.getUsermap(); for(Entry<String, Object> MapObject : usermap.entrySet()){ System.out.println(MapObject.getKey()+":"+MapObject.getValue()); } //model.addAttribute("user", user); return "success"; } }
hello.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'Hello.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> Hello,UserController <br> <form action="${pageContext.request.contextPath}/receiveMap.do" method="post"> Sname:<input type="text" name="usermap['Sname']" id="Sname" value='Sname0'/> Sid:<input type="text" name="usermap['Sid']" id="Sid" value='Sid0'/> Sage:<input type="text" name="usermap['Sno']" id="Sno" value='Sno0'/><br> <input type="submit" value="提交"/> </form> </body> </html>
运行后结果为: