我是Spring Boot的新手我正在学习本教程 https://github.com/netgloo/spring-boot-samples/tree/master/spring-boot-mysql-springdatajpa-hibernate
我所做的就是下载这个jar并构建它并在localhost:8080
上运行它我的Application.java是主文件,如下所示:
package netgloo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
我的主控制器如下:
package netgloo.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MainController {
@RequestMapping("/")
@ResponseBody
public String index() {
return "Proudly handcrafted by " +
"<a href='http://netgloo.com/en'>netgloo</a> :)";
}
}
我的用户控制器如下:
package netgloo.controllers;
import netgloo.models.User;
import netgloo.models.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value="/user")
public class UserController {
@Autowired
private UserDao _userDao;
@RequestMapping(value="/delete")
@ResponseBody
public String delete(long id) {
try {
User user = new User(id);
_userDao.delete(user);
}
catch(Exception ex) {
return ex.getMessage();
}
return "User succesfully deleted!";
}
@RequestMapping(value="/get-by-email")
@ResponseBody
public String getByEmail(String email) {
String userId;
try {
User user = _userDao.getByEmail(email);
userId = String.valueOf(user.getId());
}
catch(Exception ex) {
return "User not found";
}
return "The user id is: " + userId;
}
@RequestMapping(value="/save")
@ResponseBody
public String create(String email, String name) {
try {
User user = new User(email, name);
_userDao.save(user);
}
catch(Exception ex) {
return ex.getMessage();
}
return "User succesfully saved!";
}
} // class UserController
当我输入localhost:8080时,我看到主控制器中定义的消息。
当我在UserController中键入任何其他端点时,例如 localhost:8080 / user 或 localhost:8080 / get-by-email?email=a@gmail.com 它会抛出404.
请告知我在此代码中缺少的内容。
答案 0 :(得分:1)
您正在尝试使用错误的网址。
试试这些:
localhost:8080/user/save?email=a@gmail.com&name=a
localhost:8080/user/get-by-email?email=a@gmail.com
由于您在类@RequestMapping("/user")
上使用UserController
注释,因此路径"/user"
会在此类中的所有请求映射上添加前缀。有关详细信息,请参阅here。