概述
可以通过org.springframework.beans.factory.annotation.Autowired注解类型将依赖注入到一个属性或方法中。
如:
// 将服务依赖注入到属性userService
@Autowired
public UserService userService;
在Spring MVC中,为了能够被作为依赖注入,类必须使用org.springframework.stereotype.Service注解类型注明为@Service。
即创建service包,包下有两个类UserService.java和UserServiceImpl.java。
UserService接口如下:
package springmvcdemo.service;
import springmvcdemo.pojo.User;
public interface UserService {
/**
* 用户登录
*
* @param user 用户实体类对象
* @return 返回是否登录成功
*/
boolean login(User user);
/**
* 用户注册
*
* @param user 用户实体类对象
* @return 返回是否注册成功
*/
boolean register(User user);
}
UserServiceImpl实现类代码如下:
package springmvcdemo.service;
import org.springframework.stereotype.Service;
import springmvcdemo.pojo.User;
@Service
public class UserServiceImpl implements UserService {
@Override
public boolean login(User user) {
if ("hello".equals(user.getUsername()) && "world".equals(user.getPassword())) {
return true;
}
return false;
}
@Override
public boolean register(User user) {
if ("hello".equals(user.getUsername()) && "world".equals(user.getPassword())) {
return true;
}
return false;
}
}
除此之外,还需要在配置文件中使用<context:component-scan base-package="服务类所在的包"/>元素来扫描依赖基本包。
故配置文件中的需要配置的代码如下:
<!--使用扫描机制扫描服务类,服务类都在service包及其子包下-->
<context:component-scan base-package="springmvcdemo.service"/>
修改UserController控制器代码如下:
package springmvcdemo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import springmvcdemo.pojo.User;
import springmvcdemo.service.UserService;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class UserController {
// 将服务依赖注入到属性userService
@Autowired
public UserService userService;
@RequestMapping("/login")
public String login(User user, HttpSession session, Model model) {
if (userService.login(user)) {
System.out.println("登录成功");
session.setAttribute("user", user);
// 跳转到/WEB-INF/jsp/下的main.jsp
return "main";
} else {
System.out.println("登录失败");
model.addAttribute("messageError", "用户名或密码错误");
// 登录失败跳转到login.jsp
return "login";
}
}
@RequestMapping("/register")
public String register(User user, Model model) {
if (userService.register(user)) {
System.out.println("注册成功");
// 注册成功,跳转到login.jsp
return "login";
} else {
System.out.println("注册失败");
model.addAttribute("username", user.getUsername());
// 注册失败,跳转到register.jsp
return "register";
}
}
}
实例
在本实例中将login和register的业务逻辑单独分离出来,交给了service去处理。
创建spring mvc项目并且按照下图创建文件夹及文件:
各文件代码如下:
IndexController.java
package springmvcdemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/index")
public class IndexController {
@RequestMapping("/register")
public String register() {
return "register";
}
@RequestMapping("/login")
public String login() {
return "login";
}
}
UserController.java
package springmvcdemo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import springmvcdemo.pojo.User;
import springmvcdemo.service.UserService;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class UserController {
// 将服务依赖注入到属性userService
@Autowired
public UserService userService;
@RequestMapping("/login")
public String login(User user, HttpSession session, Model model) {
if (userService.login(user)) {
System.out.println("登录成功");
session.setAttribute("user", user);
// 跳转到/WEB-INF/jsp/下的main.jsp
return "main";
} else {
System.out.println("登录失败");
model.addAttribute("messageError", "用户名或密码错误");
// 登录失败跳转到login.jsp
return "login";
}
}
@RequestMapping("/register")
public String register(User user, Model model) {
if (userService.register(user)) {
System.out.println("注册成功");
// 注册成功,跳转到login.jsp
return "login";
} else {
System.out.println("注册失败");
model.addAttribute("username", user.getUsername());
// 注册失败,跳转到register.jsp
return "register";
}
}
}
User.java
package springmvcdemo.pojo;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserService.java
package springmvcdemo.service;
import springmvcdemo.pojo.User;
public interface UserService {
/**
* 用户登录
*
* @param user 用户实体类对象
* @return 返回是否登录成功
*/
boolean login(User user);
/**
* 用户注册
*
* @param user 用户实体类对象
* @return 返回是否注册成功
*/
boolean register(User user);
}
UserServiceImpl.java
package springmvcdemo.service;
import org.springframework.stereotype.Service;
import springmvcdemo.pojo.User;
@Service
public class UserServiceImpl implements UserService {
@Override
public boolean login(User user) {
if ("hello".equals(user.getUsername()) && "world".equals(user.getPassword())) {
return true;
}
return false;
}
@Override
public boolean register(User user) {
if ("hello".equals(user.getUsername()) && "world".equals(user.getPassword())) {
return true;
}
return false;
}
}
springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--使用扫描机制扫描控制器类,控制器类都在controller包及其子包下-->
<context:component-scan base-package="springmvcdemo.controller"/>
<!--使用扫描机制扫描服务类,服务类都在service包及其子包下-->
<context:component-scan base-package="springmvcdemo.service"/>
<!--配置视图解析器-->
<!--配置视图解析器成功后,RegisterController和LoginController控制器类的视图路径仅需提供register和login,视图解析器将会自动添加前缀和后缀-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<form action="/user/login" method="post">
姓名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
<span style="color:red"><%=request.getAttribute("messageError")%></span>
</form>
</body>
</html>
main.jsp
<%@ page import="springmvcdemo.pojo.User" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
</head>
<body>
<%
User user = (User)session.getAttribute("user");
%>
欢迎<%=user.getUsername()%>,访问本页面!
</body>
</html>
register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册</title>
</head>
<body>
<form action="/user/register" method="post">
姓名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="注册">
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--部署DispatcherServlet-->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载Spring MVC的配置文件,配置文件可以放在项目目录的任意位置,使用init-param元素加载配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<!--配置文件的位置-->
<param-value>/WEB-INF/config/springmvc-config/springmvc-servlet.xml</param-value>
</init-param>
<!--表示容器在启动时立即加载servlet-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<!--处理所有URL-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
</head>
<body>
未注册的用户,请<a href="/index/register">注册</a>!<br>
已注册的用户,去<a href="/index/login">登录</a>!<br>
</body>
</html>
运行效果如下: