实体:
先来看一段代码:
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonTypeId;
import org.springframework.format.annotation.DateTimeFormat;
import javax.management.relation.Role;
import java.util.Date;
@Entity
@Table(name="user")
public class User implements java.io.Serializable{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id; //实体的唯一标识
private String name;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createdate;
@ManytoOne
@JoinColumn(name="did")
@JsonBackReference
private Department department;
@ManytoMany(cascade={},fetch=FetchType.EAGER)
@JoinTable(name="user_role",
joinColumns={@JoinColumn(name="user_id")},
inverseJoinColumns={@JoinColumn(name="roles_id")})
private List<Role> roles;
public User(){}
......
}
这段代码注册了一个用户实体。注解功能如下:
注解 | 功能 |
---|---|
@Entity | 实体类标注 |
@Table(name=“user”) | 关联的数据库表名为"user" |
@Id | 主键,定义一条记录的唯一标识 |
@GeneratedValue | 自增长策略,设置为自动生成 |
@ManytoOne | 一个部门可以有多个用户 |
@ManytoMany | 一个用户可以有多个角色 |
@DateTimeFormat | 格式化日期类型数据 |
控制器Controller
来看一段控制器的代码:
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/hello")
public String Hello(){
return "Hello World";
}
@ResponseBody
@RequestMapping({"/","/index.html"})
public String MainPage(){
return "this is the main page";
}
}
这段控制器代码的功能是处理请求映射地址"/"、"/index.html"和"/hello"。
当在浏览器中输入localhost:8080/或者localhost:8080/index.html时会在页面显示"this is the main page";
当在浏览器中输入localhost:8080/hello时会在页面显示"Hello World"。
注解 | 功能 |
---|---|
@Controller | 表明该类是一个控制器 |
@RequestMapping(“url”) @RequestMapping({“url1”,“url2”}) | 可以作用在类上或者方法上,表明下方的类/方法是个映射器, 当浏览器输入地址为"url"时,会使用该映射器来进行处理 |
@ResponseBody | 作用在方法上, 表示方法返回的结果直接写入 HTTP response body 中 在上面这段代码里表示将字符串直接呈现在页面上 |
@PostMapping(value = "/user/login") // 映射一个post请求
// @RequestMapping(value = "/user/login", method = RequestMethod.POST)
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Map<String, Object> map, HttpSession session) {
if (!StringUtils.isEmpty(username) && "123456".equals(password)) {
session.setAttribute("loginUser", username);
return "redirect:/main.html";
} else {
map.put("msg", "用户名密码错误");
return "login";
}
}
注解 | 功能 |
---|---|
@PostMapping | 相当于@RequestMapping(method = RequestMethod.POST) 用于处理post请求 |
@RequestParam() | 表示post过来的参数中一定要有括号内的值,否则就报错 |
@GetMapping("/emp/{id}")
public String toEditPage(@PathVariable("id") Integer id,Model model){
Employee employee=employeeDao.get(id);
model.addAttribute("emp",employee);
// 修改和添加使用同一个html文件
return "emp/add";
}
这个控制器的功能是编辑员工的信息。
不同的员工有不同的id编号,因此会有不同的url地址。
@PathVariable 就可以将url地址中的这个具体的{id}提取出来,赋值给Integer id中的那个id。