比尔云BierYun--阿里云最新优惠活动
阿里云优惠码丨阿里云代金券

Spring MVC的Controller接受请求方式以及编写请求处理方法

Spring MVC的Controller接受请求方式以及编写请求处理方法

Controller接受请求参数的常见方法:

1、通过Bean接受请求参数:

创建POJO实体类

创建pojo包,并在该包中创建实体类UserForm,代码:

复制代码
package 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;
    }
}
复制代码

创建控制器类,在controller包中创建控制器类IndexController和UserController

其中@RequestMapping注解的作用个人浅显的理解就是将方法或类注解为一个“路径”的名称,以便在HTML,JSP(视图)向控制器发送请求时寻找到。

IndexController代码:

复制代码
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller//在这里@Controller相当于@Controller(“indexController”)
@RequestMapping("/index")
public class IndexController {
    @RequestMapping("/login")
    public String login() {
        return "login";//跳转到“/WEB-INF/jsp/login.jsp”
    }
    @RequestMapping("/register")
    public String register() {
        return "register";
    }
}
复制代码

UserController代码:

复制代码
package controller;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.UserForm;
import service.UserService;
@Controller//在这里@Controller相当于@Controller(“userController”)
@RequestMapping("/user")
public class UserController {
    //得到一个用来记录日志的对象,这样打印信息的时候能够标记打印的是那个类的信息
    private static final Log logger = LogFactory.getLog(UserController.class);
    //将服务依赖注入到属性userService
    @Autowired
     public UserService userService;
    /**
     * 处理登录
     */
    @RequestMapping("/login")
    public String login(UserForm user, HttpSession session, Model model) {
        if(userService.login(user)){
            session.setAttribute("u", user);
            logger.info("成功");
            return "main";//登录成功,跳转到main.jsp
        }else{
            logger.info("失败");
            model.addAttribute("messageError", "用户名或密码错误");
            return "login";
        }    
    }
    /**
     *处理注册
     */
    @RequestMapping("/register")
    public String register(@ModelAttribute("user") UserForm user) {
        if(userService.register(user)){
            logger.info("成功");
            return "login";//注册成功,跳转到login.jsp
        }else{
            logger.info("失败");
            //使用@ModelAttribute("user")与model.addAttribute("user", user)功能相同
          //在register.jsp页面上可以使用EL表达式${user.uname}取出ModelAttribute的uname值
            return "register";//返回register.jsp
        }
    }
}
复制代码

创建页面视图,结合视图中更能理解@RequestMapping注解的作用,其中关于本次知识的核心代码为<body>标签中的内容:

创建register.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=UTF-8">
<style type="text/css">
    .textSize{
        width: 100pt;
        height: 15pt
    }
</style>
<title>注册画面</title>
<script type="text/javascript">
    //注册时检查输入项
    function allIsNull(){
        var name=document.registForm.uname.value;
        var pwd=document.registForm.upass.value;
        var repwd=document.registForm.reupass.value;
        if(name==""){
            alert("请输入姓名!");
            document.registForm.uname.focus();
            return false;
        }
        if(pwd==""){
            alert("请输入密码!");
            document.registForm.upass.focus();
            return false;
        }
        if(repwd==""){
            alert("请输入确认密码!");
            document.registForm.reupass.focus();
            return false;
        }
        if(pwd!=repwd){
            alert("2次密码不一致,请重新输入!");
            document.registForm.upass.value="";
            document.registForm.reupass.value="";
            document.registForm.upass.focus();
            return false;
        }
        document.registForm.submit();
        return true;
    }
</script>
</head>
<body>
    <form action="${pageContext.request.contextPath }/user/register" method="post" name="registForm">
        <table 
        border=1 
        bgcolor="lightblue" 
        align="center">
            <tr>
                <td>姓名:</td>
                <td>
                    <input class="textSize" type="text" name="uname" value="${user.uname }"/>
                </td>
            </tr>
            
            <tr>
                <td>密码:</td>
                <td><input class="textSize" type="password" maxlength="20" name="upass"/></td>
            </tr>
            
            <tr>
                <td>确认密码:</td>
                <td><input class="textSize" type="password" maxlength="20" name="reupass"/></td>
            </tr>
            
            <tr>
                <td colspan="2" align="center"><input type="button" value="注册" onclick="allIsNull()"/></td>
            </tr>
        </table>
    </form>
</body>
</html>
复制代码

创建login.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=UTF-8">
    <title>后台登录</title>
    <style type="text/css">
    table{
        text-align: center;
    }
    .textSize{
        width: 120px;
        height: 25px;
    }
    * {
        margin: 0px;
        padding: 0px;
    }
    body {
        font-family: Arial, Helvetica, sans-serif;
        font-size: 12px;
        margin: 10px 10px auto;
        background-image: url(${pageContext.request.contextPath }/images/bb.jpg);
    }
    </style>
    <script type="text/javascript">
    //确定按钮
    function gogo(){
        document.forms[0].submit();
    }
    //取消按钮
    function cancel(){
        document.forms[0].action = "";
    }
    </script>
  </head>
  <body>
      <form action="${pageContext.request.contextPath }/user/login" method="post">
    <table>
        <tr>
            <td colspan="2"><img src="${pageContext.request.contextPath }/images/login.gif"></td>
        </tr>
        <tr>
            <td>姓名:</td>
            <td><input type="text" name="uname" class="textSize"></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="upass" class="textSize"></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="image" src="${pageContext.request.contextPath }/images/ok.gif" onclick="gogo()" >
                <input type="image" src="${pageContext.request.contextPath }/images/cancel.gif" onclick="cancel()" >
            </td>
        </tr>
    </table>
    ${messageError }
    </form>
  </body>
</html>
复制代码

2、通过处理方法的形参接收请求参数

即将控制类UserConttroller中的register方法的代码修改如下:

复制代码
@RequestMapping("/register")
/**
*通过形参的计收请求参数,形参名称与请求参数名称完全相同
*/
    public String register(String uname,String upass,Model model) {
        if(userService.equals(uname)&&userService.equals(upass)){
            logger.info("成功");
            return "login";//注册成功,跳转到login.jsp
        }else{
            logger.info("失败");
            return "register";//返回register.jsp
        }
    }
复制代码

3、通过HttpServetRequest接受请求参数(推荐使用):

即将控制类UserConttroller中的register方法的代码修改如下:

复制代码
    @RequestMapping("/register")
    public String register(HttpServletRequest request,Model model) {
               String uname = request.getParameter("uname");
               String upass = request.getParameter("upass");
        if(userService.equals(uname)&&userService.equals(upass)){
            logger.info("成功");
            return "login";//注册成功,跳转到login.jsp
        }else{
            logger.info("失败");
            return "register";//返回register.jsp
        }
    }
复制代码

其他@PathVariable、@RequestParam等不多赘述,原理相同。

原文地址https://www.cnblogs.com/linchenguang/archive/2019/07/25/11243444.html

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

强烈推荐

高性能SSD云服务器ECS抗攻击,高可用云数据库RDS