iT邦幫忙

2024 iThome 鐵人賽

0
Software Development

從Servlet到Spring MVC系列 第 36

Day35 Spring MVC - Project

  • 分享至 

  • xImage
  •  

前言

今日將Day23 Servlet - Project專案將它改寫為Spring MVC版本

0、創建module

(1) 請參考Day27 module
(2) 使用JSON相關設置請參考Day29
(3) 參考Day23 project,將servlet package重寫並將對應Service與Dao改寫

一、xml配置

springmvc-servlet.xml

<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/static/"/>
    <property name="suffix" value=".html"/>
</bean>

二、創建Controller

創建Controller package取代原先servlet package

(1)創建RootController

創建RootController導向靜態頁面

@Controller
public class RootController {

    @GetMapping("/")
    public String index(){
        System.out.println("hello index");
        return "index";
    }
    @GetMapping("crud")
    public String crud(){
        System.out.println("hello crud");
        return "crud";
    }
}

(2) 創建EmpController

@RestController
@RequestMapping("/api/employees")
public class EmpController extends HttpServlet {
    private EmployeeService employeeService;

    @Autowired
    public EmpController(EmployeeService employeeService) {
        this.employeeService =employeeService;
    }

    @GetMapping
    protected  Result<List<Employee>> readEmps()  {
        List<Employee> employees = employeeService.getAllEmployees();
        Result<List<Employee>> result = new Result<>(true, "Employees fetched successfully", employees);

        return result;
    }

    @PostMapping
    protected Result createEmp(@RequestBody Employee employee) {
        employeeService.createEmployee(employee);
        Result result = new Result(true, "Employee saved successfully");

        return result;
    }

    @PutMapping(path = "/{empId}")
    protected Result updateEmp(@RequestBody Employee employee,@PathVariable("empId") String empId){
        boolean isSuccess = employeeService.updateEmployee(Integer.parseInt(empId), employee);
        String message = isSuccess?"Employee updated successfully":"Employee update failed";
        Result result = new Result(isSuccess, message);

        return result;
    }

    @DeleteMapping(path = "/{empId}")
    public Result deleteEmp(@PathVariable("empId") String empId){
        boolean isSuccess = employeeService.deleteEmployee(Integer.parseInt(empId));
        String message = isSuccess?"Employee deleted successfully":"Employee deleted failed";
        Result result = new Result(isSuccess, message);

        return result;

    }
}

(3) 創建LoginController

僅修改login方法

@PostMapping("login")
    public void login(HttpServletResponse response,@RequestBody User user){
        Result result = new Result();

        if (authenticate(user)) {
            // 創建token
            String token = JwtUtils.createToken(user.getUsername());
            System.out.println(token);
            // 設置 Cookie
            Cookie jwtCookie = new Cookie("token", token);
            jwtCookie.setHttpOnly(true); // 防止 JavaScript 存取,減少 XSS 攻擊風險
            jwtCookie.setPath("/");
            jwtCookie.setMaxAge(24 * 60 * 60); // 1 天

            response.addCookie(jwtCookie);
            result.setSuccess(true);
            result.setMessage("Login successful!");
        } else {
            // 如果驗證失敗
            result.setSuccess(false);
            result.setMessage("Invalid username or password.");
        }

        JsonUtils.writeJson(response,result);

    }

加入Service層與Dao層註解

@Component
public class EmployeeDao {
  //略
}

修改EmployeeService層annotation

@Service
public class EmployeeService {

    private EmployeeDao employeeDao;

    @Autowired
    public EmployeeService(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }
//其他略
}

Demo

https://ithelp.ithome.com.tw/upload/images/20241020/201280845KXnfsGRyR.png
https://ithelp.ithome.com.tw/upload/images/20241020/20128084RlxtQMyyR2.png

Reference


上一篇
Day34 Spring MVC - RESTful
系列文
從Servlet到Spring MVC36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言