欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring向页面传值和接受页面传过来的参数详解

程序员文章站 2023-12-20 22:30:46
本文主要给大家介绍了关于spring向页面传值和接受页面传过来的参数的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍: 一、从页面接收参数 spring m...

本文主要给大家介绍了关于spring向页面传值和接受页面传过来的参数的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍:

一、从页面接收参数

spring mvc接收请求提交的参数值的几种方法:

1、使用httpservletrequest获取。

 @requestmapping("/login.do") 
public string login(httpservletrequest request){ 
 string name = request.getparameter("name") 
 string pass = request.getparameter("pass") 
} 

2、使用@requestparam注解。

 @requestmapping("/login.do") 
 public string login(httpservletrequest request, 
  string name, 
 @requestparam("pass")string password) // 表单属性是pass,用变量password接收 
 { 
 syso(name); 
 syso(password) 
 } 

3、使用自动机制封装成实体参数。

 <form action="login.do"> 
 用户名:<input name="name"/> 
 密码:<input name="pass"/> 
 <input type="submit" value="登陆"> 
 </form> 
 
 //封装的user类 
 public class user{ 
 private string name; 
 private string pass; 
 } 
 @requestmapping("/login.do") 
 public string login(user user) 
 { 
 syso(user.getname()); 
 syso(user.getpass()); 
 } 

二、向页面传值

当controller组件处理后,需要向响应jsp传值时,可以使用的方法:

1),使用httpservletrequest 和 session  然后setattribute() ,就和servlet中一样

model数据会利用httpservletrequest的attribute传值到success.jsp中

 @requestmapping("/login.do") 
 public modelandview login(string name,string pass){ 
 user user = userservice.login(name,pwd); 
 map<string,object> data = new hashmap<string,object>(); 
 data.put("user",user); 
 return new modelandview("success",data); 
 } 

2),使用modelandview对象 

3),使用modelmap对象

使用modelmap参数对象示例:

modelmap数据会利用httpservletrequest的attribute传值到success.jsp中

 @requestmapping("/login.do") 
 public string login(string name,string pass ,modelmap model){ 
 user user = userservice.login(name,pwd); 
 model.addattribute("user",user); 
 model.put("name",name); 
 return "success"; 
 } 

4),使用@modelattribute注解

使用@modelattribute示例

在controller方法的参数部分或bean属性方法上使用@modelattribute数据会利用httpservletrequest的attribute传值到success.jsp中

 @requestmapping("/login.do") 
 public string login(@modelattribute("user") user user){ 
 //todo 
 return "success"; 
 } 
 
 @modelattribute("name") 
 public string getname(){ 
 return name; 
 } 

5)session存储:可以利用httpservletreequest的getsession()方法

 @requestmapping("/login.do") 
 public string login(string name,string pwd 
 modelmap model,httpservletrequest request){ 
 user user = serservice.login(name,pwd); 
 httpsession session = request.getsession(); 
 session.setattribute("user",user); 
 model.addattribute("user",user); 
 return "success"; 
 } 

6)自定义map

@responsebody
 @requestmapping(value = "/updatestatus", method = requestmethod.post)
 public map<string, object> updatestatus(httpservletrequest request) {
 map<string, object> result = new hashmap<string, object>();
 string id = request.getparameter("id");
 systemadministrator sysadmin=systemadminbiz.get(integer.valueof(id));
 sysadmin.setstatus(1);
 boolean flag = systemadminbiz.update(sysadmin);
 result.put("status", flag);
 return result;
 }
@requestmapping(value = "/list", method = {requestmethod.post,requestmethod.get})
 public string queryadministrator(httpservletrequest request,modelmap model) {
 integer roleid = request.getparameter("rolelistbyid") == null ? 0 : integer.parseint(request.getparameter("rolelistbyid"));
 map<string, object> properties = new hashmap<string, object>();
 if(roleid.intvalue() > 0) {
 properties.put("role:=", roleid);
 model.put("roleid", roleid);
 }
 list<systemadministrator> administrator = systemadminbiz.find(properties);
 list<systemrole> systemrole = systemrolebiz.getall();
 model.put("administratorlist", administrator);
 model.put("rolelist", systemrole);
 return "sys_admin_list";
 }

 7)spring mvc 默认采用的是转发来定位视图,如果要使用重定向,可以如下操作

1,使用redirectview

2,使用redirect:前缀

 public modelandview login(){ 
 redirectview view = new redirectview("regirst.do"); 
 return new modelandview(view); 
 } 

或者用如下方法,工作中常用的方法:

 public string login(){ 
 //todo 
 return "redirect:regirst.do"; 
} 

三、实例讲解:

步骤一:创建新web项目,导入spring mvc包和业务层userservice

1. 创建web项目导入相关的jar包:

Spring向页面传值和接受页面传过来的参数详解 

2. 导入前述业务层userservice类以及依赖的类,等。

user类代码如下:

package com.souvc.entity;

import java.io.serializable;

public class user implements serializable {
 private static final long serialversionuid = -603439325380668432l;
 private int id;
 private string name;
 private string pwd;
 private string phone;

 public user() {
 }

 public user(int id, string name, string pwd, string phone) {
 this.id = id;
 this.name = name;
 this.pwd = pwd;
 this.phone = phone;
 }

 public user(string name, string pwd, string phone) {
 super();
 this.name = name;
 this.pwd = pwd;
 this.phone = phone;
 }

 public int getid() {
 return id;
 }

 public void setid(int id) {
 this.id = id;
 }

 public string getname() {
 return name;
 }

 public void setname(string name) {
 this.name = name;
 }

 public string getpwd() {
 return pwd;
 }

 public void setpwd(string pwd) {
 this.pwd = pwd;
 }

 public string getphone() {
 return phone;
 }

 public void setphone(string phone) {
 this.phone = phone;
 }

 @override
 public int hashcode() {
 return id;
 }

 @override
 public boolean equals(object obj) {
 if (this == obj)
 return true;
 if (obj == null)
 return false;
 if (obj instanceof user) {
 user o = (user) obj;
 return this.id == o.id;
 }
 return true;
 }

 @override
 public string tostring() {
 return id + "," + name + "," + pwd + "," + phone;
 }
}

userdao接口代码如下:

package com.souvc.dao;

import com.souvc.entity.user;

/**
 * 用户数据访问对象接口
 */
public interface userdao {
 /** 根据唯一用户名查询系统用户, 如果没有找到用户信息返回null */
 public user findbyname(string name);
 // public user add(string name, string pwd, string phone);
 // public user find(int id);
 // public user delete(int id);
 // public void update(user user);
}

userservice类代码如下:

package com.souvc.service;

import java.io.serializable;

import javax.annotation.resource;

import org.springframework.stereotype.service;

import com.souvc.dao.userdao;
import com.souvc.entity.user;

/** 业务层 注解 */
@service
// 默认的bean id是 userservice
public class userservice implements serializable {
 private static final long serialversionuid = 7360372166489952236l;
 private userdao userdao;

 // @resource //自动匹配userdao对象并注入
 @resource(name = "userdao")
 public void setuserdao(userdao userdao) {
 this.userdao = userdao;//
 }

 public userdao getuserdao() {
 return userdao;
 }

 /** 登录系统功能 */
 public user login(string name, string pwd) throws nameorpwdexception,
 nullparamexception {
 if (name == null || name.equals("") || pwd == null || pwd.equals("")) {
 throw new nullparamexception("登录参数不能为空!");
 }
 user user = userdao.findbyname(name);
 if (user != null && pwd.equals(user.getpwd())) {
 return user;
 }
 throw new nameorpwdexception("用户名或者密码错误");
 }
}

nameorpwdexception类代码如下:

package com.souvc.service;

/** 用户名或者密码错误 */
public class nameorpwdexception extends exception {
 public nameorpwdexception() {
 }

 public nameorpwdexception(string message) {
 super(message);
 }

 public nameorpwdexception(throwable cause) {
 super(cause);
 }

 public nameorpwdexception(string message, throwable cause) {
 super(message, cause);
 }
}

nullparamexception类代码如下:

package com.souvc.service;

/** 参数为空 */
public class nullparamexception extends exception {
 public nullparamexception() {
 }

 public nullparamexception(string message) {
 super(message);
 }

 public nullparamexception(throwable cause) {
 super(cause);
 }

 public nullparamexception(string message, throwable cause) {
 super(message, cause);
 }
}

jdbcdatasource类代码如下:

package com.souvc.dao;

import java.io.serializable;
import java.sql.connection;
import java.sql.drivermanager;
import java.sql.sqlexception;
import org.springframework.beans.factory.annotation.value;
import org.springframework.stereotype.component;

/** 组件注解 */
@component
public class jdbcdatasource implements serializable {

 private static final long serialversionuid = -8925981939329398101l;

 private string driver;

 @value("#{jdbcprops.url}")
 private string url;

 @value("#{jdbcprops.user}")
 private string user;

 @value("#{jdbcprops.pwd}")
 private string pwd;

 public string getdriver() {
 return driver;
 }

 /** 必须使用bean属性输入, 否则不能进行jdbc driver注册 */
 @value("#{jdbcprops.driver}")
 public void setdriver(string driver) {
 try {
 // 注册数据库驱动
 class.forname(driver);
 this.driver = driver;
 } catch (exception e) {
 throw new runtimeexception(e);
 }
 }

 public string geturl() {
 return url;
 }

 public void seturl(string url) {
 this.url = url;
 }

 public string getuser() {
 return user;
 }

 public void setuser(string user) {
 this.user = user;
 }

 public string getpwd() {
 return pwd;
 }

 public void setpwd(string pwd) {
 this.pwd = pwd;
 }

 public connection getconnection() throws sqlexception {
 connection conn = drivermanager.getconnection(url, user, pwd);
 return conn;
 }

 public void close(connection conn) {
 if (conn != null) {
 try {
 conn.close();
 } catch (sqlexception e) {
 e.printstacktrace();
 }
 }
 }
}

mysqluserdao类代码如下:

package com.souvc.dao;

import java.io.serializable;
import java.sql.connection;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.sqlexception;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.beans.factory.annotation.qualifier;
import org.springframework.stereotype.repository;

import com.souvc.entity.user;

/** 持久层 注解 */
@repository("userdao")
// 指定特定的bean id 方便setuserdao注入
public class mysqluserdao implements userdao, serializable {
 private static final long serialversionuid = 7385842613248394287l;
 private jdbcdatasource datasource;

 public mysqluserdao() {
 }

 /** 创建 mysqluserdao 对象必须依赖于jdbcdatasource实例 */
 public mysqluserdao(jdbcdatasource datasource) {
 this.datasource = datasource;
 }

 @autowired
 // 按照类型自动装配
 public void setdatasource(@qualifier("jdbcdatasource")
 jdbcdatasource datasource) {
 this.datasource = datasource;
 }

 public jdbcdatasource getdatasource() {
 return datasource;
 }

 /** 根据唯一用户名查询系统用户, 如果没有找到用户信息返回null */
 public user findbyname(string name) {
 system.out.println("利用jdbc技术查找user信息");
 string sql = "select id, name, pwd, phone from users where name=?";
 connection conn = null;
 try {
 conn = datasource.getconnection();
 preparedstatement ps = conn.preparestatement(sql);
 ps.setstring(1, name);
 resultset rs = ps.executequery();
 user user = null;
 while (rs.next()) {
 user = new user();
 user.setid(rs.getint("id"));
 user.setname(rs.getstring("name"));
 user.setpwd(rs.getstring("pwd"));
 user.setphone(rs.getstring("phone"));
 }
 rs.close();
 ps.close();
 return user;
 } catch (sqlexception e) {
 e.printstacktrace();
 throw new runtimeexception(e);
 } finally {
 datasource.close(conn);
 }
 }
}

db.properties文件内容如下:

# config for mysql
driver=com.mysql.jdbc.driver
url=jdbc:mysql://localhost:3306/souvc
user=root
pwd=123456

spring-mvc.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:context="http://www.springframework.org/schema/context"
 xmlns:jdbc="http://www.springframework.org/schema/jdbc"
 xmlns:jee="http://www.springframework.org/schema/jee"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:jpa="http://www.springframework.org/schema/data/jpa"
 xmlns:util="http://www.springframework.org/schema/util"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemalocation="
 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
 http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
 http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

 <util:properties id="jdbcprops" location="classpath:db.properties" />

 <context:component-scan base-package="com.souvc" />
 <!-- 视图处理 -->
 <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>

mysql数据库初始化sql代码如下:

drop table users;
create table users 
(
 id double(7, 0) , 
 name varchar(50) , 
 pwd varchar(50), 
 phone varchar(50) ,
 primary key (id)
 );

insert into users (id, name, pwd, phone) values (1, 'tom', '123', '110');
insert into users (id, name, pwd, phone) values (2, 'jerry', 'abc', '119');
insert into users (id, name, pwd, phone) values (3, 'andy', '456', '112');

3. 为项目添加junit4 api,然后添加测试类testcase和测试方法testuserservice()用于测试上述配置是否正确。testcase类代码如下:

package com.souvc.test;

import java.util.properties;

import org.junit.test;
import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;

import com.souvc.dao.jdbcdatasource;
import com.souvc.entity.user;
import com.souvc.service.userservice;

public class testcase {

 @test
 public void testuserservice() throws exception {
 string cfg = "spring-mvc.xml";
 applicationcontext ac = new classpathxmlapplicationcontext(cfg);
 properties obj = ac.getbean("jdbcprops", properties.class);
 jdbcdatasource ds = ac.getbean("jdbcdatasource", jdbcdatasource.class);
 system.out.println(obj);
 system.out.println(ds);
 system.out.println(ds.getconnection());
 userservice service = ac.getbean("userservice", userservice.class);
 user user = service.login("tom", "123");
 system.out.println(user);
 }
}

执行测试方法testuserservice() ,在控制台输出的结果:

{user=root, url=jdbc:mysql://localhost:3306/souvc, driver=com.mysql.jdbc.driver, pwd=123456}
com.souvc.dao.jdbcdatasource@1cb1a4e2
com.mysql.jdbc.jdbc4connection@3d04fc23

利用jdbc技术查找user信息

1,tom,123,110

这个结果说明业务层userservice工作正常。

4. 配置spring mvc 核心控制器dispatcherservlet到web.xml。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">
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

 <servlet>
 <servlet-name>springmvc</servlet-name>
 <servlet-class>
 org.springframework.web.servlet.dispatcherservlet
 </servlet-class>
 <init-param>
 <param-name>contextconfiglocation</param-name>
 <param-value>classpath:spring-mvc.xml</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>springmvc</servlet-name>
 <url-pattern>*.form</url-pattern>
 </servlet-mapping>

</web-app>

5. 部署项目到tomcat并且启动,测试spring mvc配置是否正常。

在输出结果中出现内容, 并且没有异常就会说明spring mvc部署正常。

步骤二:实现login-action1.form登录流程,测试利用httpservletrequrst传值方法

1. 在web-inf/jsp文件夹下添加login-form.jsp文件,代码如下所示:

<%@ page pageencoding="utf-8" contenttype="text/html; charset=utf-8"%>
<!doctype html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:url var="base" value="/"></c:url>
<html>
 <head>
 <title>login form</title>
 <link rel="stylesheet" type="text/css" href="${base}styles.css" rel="external nofollow" rel="external nofollow" >
 </head>
 <body>
 <h6>${message}</h6>
 <form method="post" action="${base}login/login-action1.form">
 <div>
  <h2>登录 login-action1.form</h2>
  <p><label>用户</label><input type="text" name="name"></p>
  <p><label>密码</label><input type="password" name="pwd"></p>
  <h3><input type="submit" value="登录"></h3>
 </div>
 </form>
 
 <form method="post" action="${base}login/login-action2.form">
 <div>
  <h2>登录 login-action2.form</h2>
  <p><label>用户</label><input type="text" name="name"></p>
  <p><label>密码</label><input type="password" name="pwd"></p>
  <h3><input type="submit" value="登录"></h3>
 </div>
 </form>
 
 <form method="post" action="${base}login/login-action3.form">
 <div>
  <h2>登录 login-action3.form</h2>
  <p><label>用户</label><input type="text" name="name"></p>
  <p><label>密码</label><input type="password" name="pwd"></p>
  <h3><input type="submit" value="登录"></h3>
 </div>
 </form>
 
 <form method="post" action="${base}login/login-action4.form">
 <div>
  <h2>登录 login-action4.form</h2>
  <p><label>用户</label><input type="text" name="name"></p>
  <p><label>密码</label><input type="password" name="pwd"></p>
  <h3><input type="submit" value="登录"></h3>
 </div>
 </form>
 
 <form method="post" action="${base}login/login-action5.form">
 <div>
  <h2>登录 login-action5.form</h2>
  <p><label>用户</label><input type="text" name="name"></p>
  <p><label>密码</label><input type="password" name="pwd"></p>
  <h3><input type="submit" value="登录"></h3>
 </div>
 </form>
 
 <form method="post" action="${base}login/login-action6.form">
 <div>
  <h2>登录 login-action6.form</h2>
  <p><label>用户</label><input type="text" name="name"></p>
  <p><label>密码</label><input type="password" name="pwd"></p>
  <h3><input type="submit" value="登录"></h3>
 </div>
 </form>
 
 </body>
 </html>

方法一解释:

    利用httpservletrequest对象进行浏览器页面到控制器传值。

方法二解释:

    使用@requestparam注解声明表单密码输入框pwd的值注入到password变量,表单中用户名输入框根据名字映自动射注入name变量。 @requestmapping注解将login-action2.form映射到了checklogin2()方法。这样就与login- form.jsp表单对应。

方法三解释:

    这里采用user作为参数, spring会自动的将页面表单参数name,pwd注入到user对象的相应属性name,pwd传递到方法中。@requestmapping将请求login-action3.form映射到方法checklogin3()

方法四解释:

    在处理方法完成后返回一个modelandview对象。

方法五解释:

     modelmap属性值与页面login-form.jsp之间的数据对应。

方法六解释:

     @modelattribute声明的属性与login-form.jsp页面的值关系。

     用户名或者密码错误时候出现的时候,能够记住用户名。 

在前述案例中,用户登录成功以后, 可以利用httpservletrequest对象的getsession()方法访问session对象, 这样就可以保持用户登录状态了。

2. 为页面添加样式文件styles.css,样式文件保存在webroot文件夹下,styles.css文件代码如下所示:

* {
 margin: 0;
 padding: 0;
}

h6 {
 text-align: center;
 color: red;
 padding: 10px;
 font-size: 14px;
}

form {
 padding: 10px;
 float: left;
}

form div {
 border: 1px gray solid;
 width: 320px;
 padding: 8px;
}

form p input {
 width: 180px
}

form h2 input {
 text-align: center;
}

form h2 {
 background: black;
 color: white;
 padding: 4px;
}

form p {
 background: #ddd;
 padding: 4px 8px 0 8px;
}

form h3 {
 background: #ddd;
 padding: 8px;
}

3. 在web-inf/jsp文件夹下添加success.jsp文件,这个文件是登录成功以后显示的界面,代码如下所示:

<%@ page pageencoding="utf-8" contenttype="text/html; charset=utf-8"%>
<!doctype html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:url var="base" value="/"></c:url>
<html>
 <head>
 <title>success</title>
 <link rel="stylesheet" type="text/css" href="${base}styles.css" rel="external nofollow" rel="external nofollow" >
 </head>
 <body>
 <h6>
 ${user.name}登录成功!
 </h6>
 </body>
</html>

上述页面中,使用el表达式和标准标签库配合显示界面数据, 其中<c:url var="base" value="/"></c:url>${base}用于解决绝对路径问题。

4. 创建控制器类logincontroller,在该类中使用注解@controller的方式进行配置:

1)使用@controller将logincontroller声明为控制器bean组件。

2)使用@requestmapping("/login")声明对logincontroller组件的请求在/login 路径下。

3)流程控制方法loginform(),用于显示登录表单页面。使用@requestmapping注解将映射请求/login-form.form到loginform()方法。

4)增加userservice属性,并且使用@resource注解声明在运行期间注入userservice对象。

5)增加控制流程方法checklogin1() ,使用@requestmapping注解将请求/login-action1.form映 射到checklogin1()方法。checklogin1()方法调用userservice的login方法,实现登录流程。 checklogin1()方法主要是测试jsp页面到控制器的数据传输方式。

logincontroller类代码如下所示:

package com.souvc.controller;

import java.util.hashmap;
import java.util.map;
import java.util.random;

import javax.annotation.resource;
import javax.servlet.http.httpservletrequest;

import org.springframework.stereotype.controller;
import org.springframework.ui.modelmap;
import org.springframework.web.bind.annotation.modelattribute;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.servlet.modelandview;

import com.souvc.entity.user;
import com.souvc.service.nameorpwdexception;
import com.souvc.service.nullparamexception;
import com.souvc.service.userservice;

@controller
//@sessionattributes("user")
@requestmapping("/login")
public class logincontroller {

 @resource
 // 请求spring注入资源 userservice
 private userservice userservice;

 @requestmapping("/login.form")
 public string loginform() {
 // 可以向表单界面传递一些参数
 return "login-form";
 }

 @requestmapping("/login-action1.form")
 // spring mvc 自动参数注入httpservletrequest
 public string checklogin1(httpservletrequest req) {
 system.out.println("---方法一---");
 // 优点直接简洁,缺点需要自己处理数据类型转换, 不支持文件上传功能
 string name = req.getparameter("name");
 string pwd = req.getparameter("pwd");
 system.out.println(name);
 system.out.println(pwd);
 try {
  user user = userservice.login(name, pwd);
  // 登录成功将登录用户信息保存到当前会话中
  req.getsession().setattribute("user", user);
  return "success";
 } catch (nameorpwdexception e) {
  e.printstacktrace();
  req.setattribute("message", e.getmessage());
  return "login-form";
 } catch (nullparamexception e) {
  e.printstacktrace();
  req.setattribute("message", e.getmessage());
  return "redirect:login.form";
 } catch (runtimeexception e) {
  e.printstacktrace();
  req.setattribute("message", e.getmessage());
  return "error";
 }
 }

 @requestmapping("/login-action2.form")
 public string checklogin2(string name, @requestparam("pwd")
 string password, // 映射表单属性不同的参数
  httpservletrequest req) {
 system.out.println("---方法二---");
 // 优点, 自动转换数据类型, 缺点可能出现数据类型转换异常
 system.out.println(name);
 system.out.println(password);
 try {
  user user = userservice.login(name, password);
  // 登录成功将登录用户信息保存到当前会话中
  req.getsession().setattribute("user", user);
  return "success";
 } catch (nameorpwdexception e) {
  e.printstacktrace();
  req.setattribute("message", e.getmessage());
  return "login-form";
 } catch (nullparamexception e) {
  e.printstacktrace();
  req.setattribute("message", e.getmessage());
  return "login-form";
 } catch (runtimeexception e) {
  e.printstacktrace();
  req.setattribute("message", e.getmessage());
  return "error";
 }
 }

 @requestmapping("/login-action3.form")
 public string checklogin3(user user, httpservletrequest req) {
 system.out.println("---方法三---");
 // 自动填充到bean对象
 system.out.println(user);
 try {
  user = userservice.login(user.getname(), user.getpwd());
  // 登录成功将登录用户信息保存到当前会话中
  req.getsession().setattribute("user", user);
  return "success";
 } catch (nameorpwdexception e) {
  e.printstacktrace();
  req.setattribute("message", e.getmessage());
  return "login-form";
 } catch (nullparamexception e) {
  e.printstacktrace();
  req.setattribute("message", e.getmessage());
  return "login-form";
 } catch (runtimeexception e) {
  e.printstacktrace();
  req.setattribute("message", e.getmessage());
  return "error";
 }
 }

 @requestmapping("/login-action4.form")
 public modelandview checklogin4(string name, string pwd,
  httpservletrequest req) {
 system.out.println("---方法四---");
 map<string, object> data = new hashmap<string, object>();
 try {
  user user = userservice.login(name, pwd);
  // 登录成功将登录用户信息保存到当前会话中
  req.getsession().setattribute("user", user);
  return new modelandview("success", data);
 } catch (nameorpwdexception e) {
  e.printstacktrace();
  data.put("message", e.getmessage());
  return new modelandview("login-form", data);
 } catch (nullparamexception e) {
  e.printstacktrace();
  data.put("message", e.getmessage());
  return new modelandview("login-form", data);
 } catch (runtimeexception e) {
  e.printstacktrace();
  data.put("message", e.getmessage());
  return new modelandview("error", data);
 }
 }

 @requestmapping("/login-action5.form")
 public string checklogin5(string name, string pwd, modelmap model,
  httpservletrequest req) {
 system.out.println("---方法五---");
 try {
  user user = userservice.login(name, pwd);
  // 登录成功将登录用户信息保存到当前会话中
  req.getsession().setattribute("user", user);
  return "success";
 } catch (nameorpwdexception e) {
  e.printstacktrace();
  model.addattribute("message", e.getmessage());
  return "login-form";
 } catch (nullparamexception e) {
  e.printstacktrace();
  model.addattribute("message", e.getmessage());
  return "login-form";
 } catch (runtimeexception e) {
  e.printstacktrace();
  model.addattribute("message", e.getmessage());
  return "error";
 }
 }

 @requestmapping("/login-action6.form")
 public string checklogin6(
  @modelattribute("name") string name, 
  @modelattribute("password") string pwd,
  modelmap model, httpservletrequest req){
  system.out.println("---方法六---");
  try {
  user user = userservice.login(name, pwd);
  // 登录成功将登录用户信息保存到当前会话中
  req.getsession().setattribute("user", user);
  return "success";
  } catch (nameorpwdexception e) {
  e.printstacktrace();
  model.addattribute("message", e.getmessage());
  return "login-form";
  } catch (nullparamexception e) {
  e.printstacktrace();
  model.addattribute("message", e.getmessage());
  return "login-form";
  } catch (runtimeexception e) {
  e.printstacktrace();
  model.addattribute("message", e.getmessage());
  return "error";
  }
 }
 
 @requestmapping("/login-action7.form")
 public string checklogin7(modelmap model, httpservletrequest req) {
 system.out.println("---方法七---");
 string name1=req.getparameter("name");
 string pwd1=req.getparameter("pwd");
 try {
  user user = userservice.login(name1, pwd1);
  // 登录成功将登录用户信息保存到当前会话中
  req.getsession().setattribute("user", user);
  return "success";
 } catch (nameorpwdexception e) {
  e.printstacktrace();
  model.addattribute("message", e.getmessage());
  return "redirect:login";
 } catch (nullparamexception e) {
  e.printstacktrace();
  model.addattribute("message", e.getmessage());
  return "redirect:login";
 } catch (runtimeexception e) {
  e.printstacktrace();
  model.addattribute("message", e.getmessage());
  return "error";
 }
 }

 private string[] msg = { "再来一次", "下次就对了", "没关系还有机会" };

 @modelattribute("next")
 public string getnext() {
 random r = new random();
 return msg[r.nextint(msg.length)];
 }

}

5.测试login-action1.form登录流程

通过网址“http://localhost:8080/springvalues/login/login.form”请求tomcat服务器:

 访问请求的信息打印在控制台:

---方法一---
tom
123
利用jdbc技术查找user信息
---方法二---
tom
123
利用jdbc技术查找user信息
---方法三---
0,tom,123,null
利用jdbc技术查找user信息
---方法四---
利用jdbc技术查找user信息
---方法五---
利用jdbc技术查找user信息

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。

上一篇:

下一篇: