本文主要給大家介紹了關於Spring向頁面傳值和接受頁面傳過來的參數的相關內容,分享出來供大家參考學習,下面來一起看看詳細的介紹:
一、從頁面接收參數
spring MVC接收請求提交的參數值的幾種方法:
1、使用HttpServletRequest獲取。
1
2
3
4
5
|
@RequestMapping
(
"/login.do"
)
public
String login(HttpServletRequest request){
String name = request.getParameter(
"name"
)
String pass = request.getParameter(
"pass"
)
}
|
2、使用@RequestParam註解。
1
2
3
4
5
6
7
8
|
@RequestMapping
(
"/login.do"
)
public
String login(HttpServletRequest request,
String name,
@RequestParam
(
"pass"
)String password)
// 表單屬性是pass,用變量password接收
{
syso(name);
syso(password)
}
|
3、使用自動機制封裝成實體參數。
1
2
3
4
5
6
7
8
9
10
11
|
<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;
}
|
1
2
3
4
5
6
|
@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中
1
2
3
4
5
6
7
|
@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中
1
2
3
4
5
6
7
|
@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中
1
2
3
4
5
6
7
8
9
10
|
@RequestMapping
(
"/login.do"
)
public
String login(
@ModelAttribute
(
"user"
) User user){
//TODO
return
"success"
;
}
@ModelAttribute
(
"name"
)
public
String getName(){
return
name;
}
|
5)Session存儲:可以利用HttpServletReequest的getSession()
方法
1
2
3
4
5
6
7
8
9
|
@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
1
2
3
4
5
6
7
8
9
10
11
|
@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;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@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:前綴
1
2
3
4
|
public
ModelAndView login(){
RedirectView view =
new
RedirectView(
"regirst.do"
);
return
new
ModelAndView(view);
}
|
或者用如下方法,工作中常用的方法:
1
2
3
4
|
public
String login(){
//TODO
return
"redirect:regirst.do"
;
}
|
三、實例講解:
步驟一:創建新Web項目,導入Spring MVC包和業務層UserService
1. 創建Web項目導入相關的jar包:
2. 導入前述業務層UserService類以及依賴的類,等。
User類代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
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接口代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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類代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
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類代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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類代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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類代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
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類代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
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文件內容如下:
1
2
3
4
5
|
# config
for
Mysql
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:
//localhost:3306/souvc
user=root
pwd=
123456
|
spring-mvc.xml文件代碼如下:
MySQL數據庫初始化SQL代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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類代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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()
,在控制檯輸出的結果:
1
2
3
|
{user=root, url=jdbc:mysql://localhost:3306/souvc, driver=com.mysql.jdbc.Driver, pwd=123456}
|
利用JDBC技術查找User信息
1
|
1,Tom,123,110
|
這個結果說明業務層UserService工作正常。
4. 配置Spring MVC 核心控制器DispatcherServlet到web.xml。web.xml配置部分代碼參考如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
<?
xml
version
=
"1.0"
encoding
=
"UTF-8"
?>
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
<
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文件,代碼如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
<%@ 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"
|