SpringMVC入门学习(二)
通过一个实体Bean来接收请求参数, 适用于get和pos提交请求方式. 需要注意的是, Bean的属性名称必须与请求参数名称相同.
<!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>
<display-name>Archetype Created Web Application</display-name>
<!-- 部署DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config/springmvc-servlet.xml</param-value>
</init-param>
<!-- 表示容器在启动时立即加载-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- 处理所有的URL-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
package cn.lacknb.pojo;
public class UserForm {
private String uname; // 与请求参数名称相同
private String upass;
private String reupass;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpass() {
return upass;
}
public void setUpass(String upass) {
this.upass = upass;
}
public String getReupass() {
return reupass;
}
public void setReupass(String reupass) {
this.reupass = reupass;
}
}
package cn.lacknb.controller;
import cn.lacknb.pojo.UserForm;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class UserController {
// 得到一个用来记录日志的对象, 这样在打印信息的时候能够标记打印的是哪个类的信息
private static final Log logger = LogFactory.getLog(UserController.class);
/*
* 处理登录
* 使用UserForm对象 user接收注册页面提交的请求参数
*/
@RequestMapping("/login")
public String login(UserForm user, HttpSession session, Model model){
if ("zhangsan".equals(user.getUname()) && "123456".equals(user.getUpass())){
session.setAttribute("u", user);
logger.info("成功");
return "main"; // 登录成功 跳转到main.jsp
}else{
logger.info("失败");
model.addAttribute("messageError", "用户名或密码错误");
return "login";
}
}
/*
* 处理注册
* 使用UserForm对象 user接收注册页面提交的请求参数
* */
@RequestMapping("/register")
public String register(UserForm user, Model model){
if ("zhangsan".equals(user.getUname()) && "123456".equals(user.getUpass())){
logger.info("成功");
return "login"; // 注册成功 跳转到login.jsp
}else{
logger.info("失败");
// 在register.jsp页面上可以使用EL表达式 取出model的uname值
model.addAttribute("uname", user.getUname());
return "register";
}
}
}
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="cn.lacknb.controller"/>
<mvc:annotation-driven/>
<!-- annotation-driven用于简化开发的配置, 注解DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapt -->
<!-- 使用resources过滤掉不需要DispatcherServlet的资源(即静态资源, 例如 css js html images) 在使用resources时 必须使用annotation-driven-->
<!-- 否则resources元素会阻止任意控制器被调用-->
<!--允许css目录下的所有文件可见-->
<mvc:resources mapping="/css/**" location="/css/"></mvc:resources>
<!-- 允许html目录下的所有文件可见-->
<mvc:resources mapping="/html/**" location="/html/"></mvc:resources>
<!--允许images目录下的所有文件可见-->
<mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
<!--配置视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp" />
</bean>
</beans>
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="cn.lacknb.controller"/>
<mvc:annotation-driven/>
<!-- annotation-driven用于简化开发的配置, 注解DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapt -->
<!-- 使用resources过滤掉不需要DispatcherServlet的资源(即静态资源, 例如 css js html images) 在使用resources时 必须使用annotation-driven-->
<!-- 否则resources元素会阻止任意控制器被调用-->
<!--允许css目录下的所有文件可见-->
<mvc:resources mapping="/css/**" location="/css/"></mvc:resources>
<!-- 允许html目录下的所有文件可见-->
<mvc:resources mapping="/html/**" location="/html/"></mvc:resources>
<!--允许images目录下的所有文件可见-->
<mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
<!--配置视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp" />
</bean>
</beans>
<%--
Created by 年少、.
User: nianshao
Date: 19-11-3
Time: 下午2:45
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false"%>
<html>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta charset="UTF-8">
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/register" method="post" name="registForm">
<table border="1" bgcolor="#add8e6" align="center">
<tr>
<td>姓名: </td>
<td><input type="text" name="uname" value="${uname}"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="upass" maxlength="20"></td>
</tr>
<tr>
<td>确认密码: </td>
<td><input type="password" name="reupass" maxlength="20"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="注册"></td>
</tr>
</table>
</form>
</body>
</html>
<%--
Created by 年少、.
User: nianshao
Date: 19-11-3
Time: 下午8:39
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta charset="UTF-8">
<head>
<title>Title</title>
</head>
<body>
<h1>欢迎你, ${u}</h1>
</body>
</html>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!-- <scope>test</scope>-->
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- 第三方jar-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>9.0.12</version>
</dependency>
</dependencies>
通过处理方法的形参接收请求参数也就是直接把表单参数写在控制器类相应方法的形参中, 即形参名称与请求参数名称完全相同. 该接收参数方式适用于get和post提交请求方式.
// 得到一个用来记录日志的对象, 这样在打印信息的时候能够标记打印的是哪个类的信息
private static final Log logger = LogFactory.getLog(UserController.class);
@RequestMapping("register")
public String register(String uname, String upass, Model model){
if ("zhangsan".equals(uname) && "123456".equals(upass)){
logger.info("成功");
return "login"; // 注册成功 跳转到login.jsp
}else{
logger.info("失败");
// 在register.jsp页面上可以使用EL表达式 取出model的uname值
model.addAttribute("uname", uname);
return "register";
}
}
通过HttpServletRequest接收请求参数适用于get和post提交请求方式
// 得到一个用来记录日志的对象, 这样在打印信息的时候能够标记打印的是哪个类的信息
private static final Log logger = LogFactory.getLog(UserController.class);
@RequestMapping("register")
public String register(HttpServletRequest request, Model model){
String uname = request.getParameter("uname");
String upass = request.getParameter("upass");
if ("zhangsan".equals(uname) && "123456".equals(upass)){
logger.info("成功");
return "login"; // 注册成功 跳转到login.jsp
}else{
logger.info("失败");
// 在register.jsp页面上可以使用EL表达式 取出model的uname值
model.addAttribute("uname", uname);
return "register";
}
}
127.0.0.1:8080/SpringMVC/user/login/zhangsan/123456
, 下面代码自动将URL中的模板变量{uname}和{upass}绑定到通过@PathVariable注解的同名参数上.package cn.lacknb.controller;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class UserController02 {
// 得到一个用来记录日志的对象, 这样在打印信息的时候能够标记打印的是哪个类的信息
private static final Log logger = LogFactory.getLog(UserController.class);
// 必须加method属性
/*
*
* 通过@PathVariable获取URL中的参数
* ps: 使用@PathVariable 不能接收表单的数据, 只能做URL上的 对应的 位置参数
* */
@GetMapping("/register/{uname}/{upass}/{reupass}")
public String register(@PathVariable String uname, @PathVariable String upass, @PathVariable String reupass, Model model){
System.out.println(reupass);
if ("zhangsan".equals(uname) && "123456".equals(upass)){
logger.info("成功");
return "login"; // 注册成功 跳转到login.jsp
}else{
logger.info("失败");
// 在register.jsp页面上可以使用EL表达式 取出model的uname值
model.addAttribute("uname", uname);
return "register";
}
}
@RequestMapping(value = "/login/{uname}/{upass}", method = RequestMethod.GET)
public String login(@PathVariable String uname, @PathVariable String upass, Model model, HttpSession session){
if ("zhangsan".equals(uname) && "123456".equals(upass)){
session.setAttribute("u", uname);
logger.info("成功");
return "main"; // 登录成功 跳转到main.jsp
}else{
logger.info("失败");
model.addAttribute("messageError", "用户名或密码错误");
return "login";
}
}
}
package cn.lacknb.controller;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class RequestParamController {
// 得到一个用来记录日志的对象, 这样在打印信息的时候能够标记打印的是哪个类的信息
private static final Log logger = LogFactory.getLog(UserController.class);
// 必须加method属性
/*
* @RequestParam可以接收get请求和post请求
*
* */
@RequestMapping("/register")
public String register(@RequestParam String uname, @RequestParam String upass, @RequestParam String reupass, Model model){
System.out.println(reupass);
if ("zhangsan".equals(uname) && "123456".equals(upass)){
logger.info("成功");
return "login"; // 注册成功 跳转到login.jsp
}else{
logger.info("失败");
// 在register.jsp页面上可以使用EL表达式 取出model的uname值
model.addAttribute("uname", uname);
return "register";
}
}
@RequestMapping("/login")
public String login(@RequestParam String uname, @RequestParam String upass, Model model, HttpSession session){
if ("zhangsan".equals(uname) && "123456".equals(upass)){
session.setAttribute("uname", uname);
logger.info("成功");
return "main"; // 登录成功 跳转到main.jsp
}else{
logger.info("失败");
model.addAttribute("messageError", "用户名或密码错误");
return "login";
}
}
}
当请求参数与接收参数不一致时, 通过处理方法的形参接收请求参数不会报404错误, 而通过@RequestParam接收请求参数时, 会报404错误.
当@ModelAttribute注解放在处理方法的形参上时, 用于将多个请求参数封装到一个实体对象, 从而简化数据绑定流程, 而且自动暴露为模型数据, 在视图页面展示时使用. 在前面的实体类Bean接收请求参数封装到一个对象, 并不能暴露为模型数据(需要使用model.addAttribute语句才能暴露为模型数据)
通过@ModelAttribute注解接收请求参数适用于get和post提交请求方式.