Spring MVC的Controller接受请求方式以及编写请…

2019-08-16 11:08:11来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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/p/11243444.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:JAVA中为什么要配置环境变量?怎么配置环境变量?

下一篇:从零探索Java网络编程01之 TCP/IP 与 Socket