Spring MVC应用@Autowired和@Service进行依赖注入(5)

Spring MVC应用@Autowired和@Service进行依赖注入

  • 工程目录结构

工程目录结构

Spring MVC应用@Autowired和@Service进行依赖注入(5)_第1张图片

UserServiceImpl.java

package service;

import org.springframework.stereotype.Service;
import pojo.UserForm;

@Service
public class UserServiceImpl implements UserService {
    @Override
    public boolean login(UserForm user) {
        if("zhw".equals(user.getUname()) && "zhw".equals(user.getUpass())){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean register(UserForm user) {
        if("zhw".equals(user.getUname()) && "zhw".equals(user.getUpass())){
            return true;
        }else {
            return false;
        }
    }
}

usercontrol.java

package control;

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;
import service.UserServiceImpl;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    public UserServiceImpl userService;

    @RequestMapping("/login")
    public String login(UserForm userForm,HttpSession httpSession,Model model){
        if (userService.login(userForm)){
            httpSession.setAttribute("u",userForm);
            return "main";
        }else {
            model.addAttribute("messagError","用户名密码错误");
            return "login";
        }
    }

    @RequestMapping("/register")
    public String register(@ModelAttribute("user") UserForm user) {
        if (userService.register(user)) {
            return "login"; // 注册成功,跳转到 login.jsp
        } else {
            return "register"; // 返回register.jsp
        }
    }
}

配置包扫描器
Spring MVC应用@Autowired和@Service进行依赖注入(5)_第2张图片
测试
Spring MVC应用@Autowired和@Service进行依赖注入(5)_第3张图片

你可能感兴趣的:(#,Spring,MVC)