Spring的一些基本使用方法
spring的一些标签用法
REST服务方式
package my;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StudentController
{
// @RequestMapping("/query")
// localhost:8080/xxx/app/query?form=100&to=200
@GetMapping("/query")
public List<Student> query(Integer from, Integer to)
{
List<Student> stu = new ArrayList();
for(Student s : DemoDB.list)
{
if(s.getId() >=from && s.getId() <= to)
{
stu.add(s);
}
}
return stu;
}
//REST服务第二种形式,ajax方式上传
@PostMapping("/add")
public Map add(int id, String name, boolean sex, String cellphone)
{
Student stu = new Student(id,name,sex,cellphone);
DemoDB.list.add(stu);
System.out.println("添加了一条记录: " + name);
Map<String, Object> result = new HashMap<>();
result.put("error", 0); // 错误码,0表示成功
result.put("reason", "OK"); // 错误描述
return result;
}
//REST服务第三种形式
// @RequestBody 从请求body里面获取数据 然后自动转成 Student
/* 默认地 jquery 按表单格式上传数据
jQuery.ajax({
url: 'app/add2',
method: "POST",
contentType: 'application/json',
processData: false,
data: JSON.stringify(req),
dataType: 'json', // 将应答数据转成json
success: function(ans){
alert('成功');
},
error: function(jqXHR, textStatus, errorThrown){
alert('出错');
}
});
*/
@PostMapping("/add2")
public Map add2( @RequestBody Student stu)
{
DemoDB.list.add(stu);
System.out.println("添加了一条记录: " + stu.getName());
Map<String, Object> result = new HashMap<>();
result.put("error", 0); // 错误码,0表示成功
result.put("reason", "OK"); // 错误描述
return result;
}
}
自定义REST类型
@Controller
public class StudentController
{
// localhost:8080/xxxx/app/query
//这里不用spring提供的 jackson的jar包了
@GetMapping("/query")
public ResponseEntity<String> query(@RequestParam("from") Integer from,
@RequestParam("to") Integer to)
{
List<Student> stu = new ArrayList();
for(Student s : DemoDB.list)
{
if(s.getId() >=from && s.getId() <= to)
{
stu.add(s);
}
}
//构造一个JSON对象(不再使用Jackson JSON,用你熟悉的JSON库)
JSONArray jresp = new JSONArray(stu);
String str = jresp.toString(2);
//构造 ResponseEntity 对象返回
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(str);
}
}
Spring其他路径的写法
package my;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
//共享路径前最
@RequestMapping("/student")
public class StudentController
{
//最终路径 app/student/query
@GetMapping("/query")
public ResponseEntity<String> query( @RequestParam("from") Integer n1
, @RequestParam("to") Integer n2)
{
List<Student> result = new ArrayList<>();
for(Student s : DemoDB.list)
{
if(s.getId() >= n1 && s.getId() <= n2)
{
result.add( s );
}
}
// 构造一个JSON对象 (不使用Jackson JSON,用你自己熟悉的JSON库 )
JSONArray jresp = new JSONArray( result);
// 构造 ResponseEntity 对象返回
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(jresp.toString(2));
}
//最终路径 app/student/add
@PostMapping("/add")
public ResponseEntity<String> add( @RequestBody String content)
{
JSONObject jreq = new JSONObject(content);
Student stu = new Student();
stu.setId( jreq.optInt("id"));
stu.setName(jreq.optString("name"));
stu.setSex(jreq.optBoolean("sex",true));
stu.setCellphone(jreq.optString("cellphone"));
DemoDB.list.add( stu );
System.out.println("添加了一条记录: " + stu.getName());
JSONObject jresp = new JSONObject();
jresp.put("error", 0); // 错误码,0表示成功
jresp.put("reason", "OK"); // 错误描述
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(jresp.toString(2));
}
//可变路径
//最终路径 app/student/201700/info
@GetMapping("/{id}/info")
public ResponseEntity<String> get(@PathVariable("id") int ids)
{
Student stu = null;
for(Student s : DemoDB.list)
{
if(s.getId() == ids)
{
stu = s;
break;
}
}
JSONObject jresp = new JSONObject();
if(stu == null)
{
jresp.put("error", -1);
jresp.put("reason", "无此记录");
}
else
{
jresp.put("error", 0); // 错误码,0表示成功
jresp.put("reason", "OK"); // 错误描述
jresp.put("data", new JSONObject(stu));
}
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(jresp.toString(2));
}
//最终路径 app/student/remove?id=100
@GetMapping("/remove")
public ResponseEntity<String> remove(int id
, HttpSession session
, HttpServletRequest request
, HttpServletResponse response)
{
String requestUri = request.getRequestURI();
//从列表中删除
Iterator<Student> iter = DemoDB.list.iterator();
while(iter.hasNext())
{
Student s = iter.next();
if(s.getId() == id)
{
iter.remove();
break;
}
}
//返回应答
JSONObject jresp = new JSONObject();
jresp.put("error", 0);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(jresp.toString(2));
}
}
本文仅供自我参考,侵权立删