一、从页面接收参数
Spring MVC接收请求提交的参数值的几种方法
- 使用HttpServletRequest获取
@RequestMapping("/login.do")
public String login(HttpServletRequest request) {
String name = request.getParameter("name")
String pass = request.getParameter("pass")
}
- 使用@RequestParam注解,和表单的name属性保持一致
@RequestMapping("/login.do")
public String login(HttpServletRequest request,
@RequestParam("pass") String name,
@RequestParam("pass") String password) { // 表单属性是pass,用变量password接收
syso(name);
syso(password)
}
- 自动注入Bean属性
<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());
}
二、向页面传值
-
使用Map、Model和ModelMap
Java代码:@RequestMapping("/test") public String test(Map<String, Object> map, Model model, ModelMap modelMap){ map.put("names", Arrays.asList("caoyc","zhh","cjx")); model.addAttribute("time", new Date()); modelMap.addAttribute("city", "ChengDu"); modelMap.put("gender", "male"); return "hello"; }
JSP页面:
1、time:${requestScope.time}<br/> 2、names:${requestScope.names }<br/> 3、city:${requestScope.city }<br/> 4、gender:${requestScope.gender }
-
使用ModelAndView ModelAndView(String viewName, Map model)
@RequestMapping("/test") public ModelAndView test(){ ModelAndView mav=new ModelAndView("hello"); mav.addObject("time", new Date()); mav.getModel().put("name", "caoyc"); return mav; }
-
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"; }
-
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
- 创建Web项目导入相关的jar包:
- 导入前述业务层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');
- 为项目添加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工作正常。
- 配置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>
- 部署项目到Tomcat并且启动,测试Spring MVC配置是否正常。
在输出结果中出现内容, 并且没有异常就会说明Spring MVC部署正常。
步骤二:实现login-action1.form登录流程,测试利用HttpServletRequrst传值方法
- 在WEB-INF/jsp文件夹下添加login-form.jsp文件,代码如下所示:
原文
网友评论