SpringMVC注解应用
注解标记只能应用于类,方法,变量的前面
springMVC实例实现(hello)
1.搭建Spring Web MVC开发环境,引入IOC,webmvc开发包;在src下添加applicationContext.xml
2.在web.xml中配置dispatcherServlet
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <servlet> <servlet-name>hello</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <!-- 启动服务器的时候,优先级是1 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
3.在applicationContext.xml中配置相关组件
A.定义Handlermapping
<!-- 定义handlermapping --> <mvc:annotation-driven/>
B.开启组建扫描Controller
<!-- 开启Controller扫描 --> <context:component-scan base-package="com.day04"/>
C.定义配置viewResolver
<!-- 配置ViewResolver --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/"></property> <property name="suffix" value=".jsp"></property> </bean>
完整代码如下:
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 定义handlermapping --> <mvc:annotation-driven/> <!-- 开启Controller扫描 --> <context:component-scan base-package="com.day04"/> <!-- 配置ViewResolver --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
2.编写和HelloController实现
注意:使用注解取消了实现Controller接口及方法约定,可以允许程序员需要灵活定义业务方法定义request, session...(Controller需要扫描到spring容器,对应类前必须使用@Controller注解)
package com.day04.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.swing.plaf.basic.BasicInternalFrameTitlePane.SystemMenuBar; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.day04.entity.user; @Controller public class HelloController { //进入hello页面 @RequestMapping("/hello.do") public String toHello(){ return "hello";//返回视图名称 } }
注意:@RequestMapping("/xxx.do"):该标记用在Controller业务方法前面
Controller如何使用SpringMVC接受参数
1.利用HttpServletRequest
@Controller public class LoginController { //登录按钮处理 @RequestMapping("/login.do") public String checkLogin(HttpServletRequest request){ String name=request.getParameter("username"); String password=request.getParameter("password"); if("root".equals(name)&&"1234".equals(password)){ return "ok";//正确进入OK.jsp }else{ return "login";//错误进入login.jsp } } }
2.利用业务方法参数
请求页面:请求参数分别为username和password
<%@ 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=ISO-8859-1"> <title></title> </head> <body> <h1>用户登录</h1> <form action="login.do" method="post"> 用户名:<input type="text" name="username"><br> 密码:<input type="password"><br> <input type="submit" value="登录"> </form> </body> </html>
参数名与请求参数key保持一致:参数名一致
public class LoginController { //登录按钮处理 @RequestMapping("/login.do") public String checkLogin(HttpServletRequest request){ String name=request.getParameter("username"); String password=request.getParameter("password"); if("root".equals(name)&&"1234".equals(password)){ return "ok";//正确进入OK.jsp }else{ return "login";//错误进入login.jsp } } //测试使用方法参数接受request信息 @RequestMapping("/login1.do") public String checkLogin1String username,String password){ System.out.println("------执行checkLogin-------"); System.out.println("username"+username); System.out.println("password"+password); return "login"; } }
利用@RequestMapping("key"):参数名不一致
//测试使用方法参数接受request信息 @RequestMapping("/login1.do") public String checkLogin1(@RequestParam("username")String name,String password){ System.out.println("------执行checkLogin-------"); System.out.println("username"+name); System.out.println("password"+password); return "login"; }
3.利用实体对象当方法参数
创建一个相关类user
package com.day04.entity; import java.io.Serializable; public class user implements Serializable{ private String username;//保持与请求key一致 private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
直接向Controller传参
@RequestMapping("/login2.do") public String checkLogin2(user user){ System.out.println("--------执行checkLogin--------"); System.out.println("username"+user.getUsername()); System.out.println("password"+user.getPassword()); return "login"; }
使用建议:少量参数使用业务方法参数;大量参数使用实体对象传参;如果客户端没有格式检查,遇到非字符串参数建议使用HttpServletRequest
Controller如何向响应jsp传值
1.利用HttpServletRequest
2.利用ModelAndView做返回值
package com.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; public class HelloController implements Controller{ public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav=new ModelAndView(); mav.setViewName("hello");//设置视图名字 mav.getModel().put("msg", "模型数据");//等价于request.setAttribute("msg","模型数据"); return mav; } }
3.利用ModelMap方法参数
@RequestMapping("/login3.do") public String checkLogin3(String username,String password,ModelMap model){ if("root".equals(username)&&"1234".equals(password)){ model.put("user", username);//ok.jsp使用${user} return "ok"; }else{ model.put("msg", "用户名或密码错误"); return "login"; } }
4.使用@ModelAttribute("key")
public String checkLogin(@ModelAttribute("user")String username){ return "ok";//ok.jsp使用${user} }
Controller如何使用session
1.在Controller中定义传入参数HttpSession
@RequestMapping("/login3.do") public String checkLogin3(String username,String password,ModelMap model,HttpSession session){ if("root".equals(username)&&"1234".equals(password)){ model.put("user", username);//ok.jsp使用${user} session.setAttribute("username", username); return "ok"; }else{ model.put("msg", "用户名或密码错误"); return "login"; } }
2.在相关jsp页面调用
<%@ 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=ISO-8859-1"> <title></title> </head> <body> <h1>ok</h1> <h2>${user}登录成功</h2> session内容:${sessionScope.username} </body> </html>