学习spring mvc 之路二 spring mvc 里的一些注解

我是接着上一节来继续写的;一些新的注解

@RequestMapping("/springmvc")
@Controller
public class SptringMVCTest {
private static final String SUCCESS ="success";

@RequestMapping("/testMap")
public String testMap(Map<String,Object> map){
map.put("names", Arrays.asList("Tom", "Jerry", "Mike"));
return SUCCESS;
}

/*
* 目标方法的返回值可以是modelandView 类型
* 其中可以包含视图和模型信息
* SpringMVC 会把modelandView 的model 中数据放入到request 域对象中
* */
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
String viewName = SUCCESS;
ModelAndView modelAndView = new ModelAndView(viewName);

// 添加模型数据到modelAndView 中
modelAndView.addObject("time",new Date());
return modelAndView;
}
/*可以使用servlet 原生的api作为目标方法的参数  具体具体支持一下类型

* HttpServletRequest 
* HttpServletResponse 
* HttpSession
* java.security.Principal 
* Locale InputStream 
* OutputStream 
* Reader 
* Writer
* */
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request,HttpServletRequest response){
System.out.println("testServletAPI,"+request+","+response);
return SUCCESS;
}

@RequestMapping("/testPojo")
public String testPojo(User user){
System.out.println("testPojo: "+user);
return SUCCESS;
}

/*
* 了解:
* @cookievalue :映射一个cookieValue
* */
@RequestMapping("testCookieValue")
public String testCookieValue(@CookieValue("JSESSIONID") String session){
System.out.println("testCookieValue:"+session);
return SUCCESS;
}
/*
* @RequestParam 来映射请求参数
* value 值即请求参数名
* required 该参数是否必须,默认为true
* defaultValue 请求参数的默认值
* */
@RequestMapping(value="/testRequestParam")
public String testRequestParam(@RequestParam(value="username") String un,@RequestParam(value="age") Integer age){
System.out.println("testRequestParam,username: "+un+",age:"+age);
return SUCCESS;
}

/*
* @PathVariable 可以用来映射url 中的占位符到目标方法的参数中。
* 例:http://localhost:8080/test_springmvc1/springmvc/testPathVariable/111
* */
@RequestMapping("/testPathVariable/{id}")
public String testPathVariable(@PathVariable("id") Integer id){
System.out.println("testPathVariable:"+id);
return SUCCESS;
}

// 带参数的
@RequestMapping(value="testParamsAndHeaders",params={"username","age!=10"})
public String testParamsAndHeaders(){
return SUCCESS;
}

// 使用method属性来指定请求方式
@RequestMapping(value="/testMethod",method=RequestMethod.POST)
public String testMethod(){
System.out.println("testMethod");
return SUCCESS;
}

/*
* 1.@RequestMapping 除了修饰方法,还可以修饰类

* 1>.类定义处:提供初步的请求映射信息。相对于web应用的根目
* 2>.方法处:提供进一步的细分映射信息。


* */
@RequestMapping("/testRequestMapping")
public String testRequestMapping(){
System.out.println("testRequestMapping");
return SUCCESS;
}


/**
* 1. 在 @ExceptionHandler 方法的入参中可以加入 Exception 类型的参数, 该参数即对应发生的异常对象
* 2. @ExceptionHandler 方法的入参中不能传入 Map. 若希望把异常信息传导页面上, 需要使用 ModelAndView 作为返回值
* 3. @ExceptionHandler 方法标记的异常有优先级的问题. 
* 4. @ControllerAdvice: 如果在当前 Handler 中找不到 @ExceptionHandler 方法来出来当前方法出现的异常, 
* 则将去 @ControllerAdvice 标记的类中查找 @ExceptionHandler 标记的方法来处理异常. 
*/
// @ExceptionHandler({ArithmeticException.class})
// public ModelAndView handleArithmeticException(Exception ex){
// System.out.println("出异常了: " + ex);
// ModelAndView mv = new ModelAndView("error");
// mv.addObject("exception", ex);
// return mv;
// }
}


如何返回一个json呢?

SpringMVC返回json数据的三种方式

1、第一种方式是spring2时代的产物,也就是每个json视图controller配置一个Jsoniew。

如:<bean id="defaultJsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/> 

或者<bean id="defaultJsonView" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>

同样要用jackson的jar包。

2、第二种使用JSON工具将对象序列化成json,常用工具Jackson,fastjson,gson。

利用HttpServletResponse,然后获取response.getOutputStream()或response.getWriter()

直接输出。

示例:

复制代码
public class JsonUtil  
{  
      
    private static Gson gson=new Gson();  
  
  
    /** 
     * @MethodName : toJson 
     * @Description : 将对象转为JSON串,此方法能够满足大部分需求 
     * @param src 
     *            :将要被转化的对象 
     * @return :转化后的JSON串 
     */  
    public static String toJson(Object src) {  
        if (src == null) {  
            return gson.toJson(JsonNull.INSTANCE);  
        }  
        return gson.toJson(src);  
    }  
}  
复制代码

3、第三种利用spring mvc3的注解@ResponseBody

例如:

复制代码
@ResponseBody  
  @RequestMapping("/list")  
  public List<String> list(ModelMap modelMap) {  
    String hql = "select c from Clothing c ";  
    Page<Clothing> page = new Page<Clothing>();  
    page.setPageSize(6);  
    page  = clothingServiceImpl.queryForPageByHql(page, hql);  
      
    return page.getResult();  
  }  
复制代码

然后使用spring mvc的默认配置就可以返回json了,不过需要jackson的jar包哦。

注意:当springMVC-servlet.xml中使用<mvc:annotation-driven />时,如果是3.1之前已经默认注入AnnotationMethodHandlerAdapter,3.1之后默认注入RequestMappingHandlerAdapter只需加上上面提及的jar包即可!

如果是手动注入RequestMappingHandlerAdapter 可以这样设置

配置如下:

复制代码
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"  
        p:ignoreDefaultModelOnRedirect="true" >  
            <property name="messageConverters">  
                <list>  
                    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>  
                </list>  
            </property>  
        </bean>  
复制代码

添加包
jackson-mapper-asl-*.jar
jackson-core-asl-*.jar

 我更偏向于这样的写法:

@ResponseBody
@RequestMapping("/testjson")
public String  testJson() throws JsonProcessingException{
getData();
String viewName = name;
ModelAndView modelAndView = new ModelAndView(viewName);

// 添加模型数据到modelAndView 中
modelAndView.addObject("time",new Date());

 
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString=objectMapper.writeValueAsString(employees);
        System.out.println(jsonString);
        return jsonString;

}
private static Map<Integer, Employee> employees = null;

public void getData(){
employees = new HashMap<Integer, Employee>();


employees.put(1001, new Employee(1001, "E-AA", "[email protected]", 1));
employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1));
employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0));
employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0));
employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 1));
}


import java.util.Date;


import javax.validation.constraints.Past;


import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
public class Employee {


private Integer id;
@NotEmpty
private String lastName;


@Email
private String email;
//1 male, 0 female
private Integer gender;




@Past
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birth;

@NumberFormat(pattern="#,###,###.#")
private Float salary;


public Integer getId() {
return id;
}


public void setId(Integer id) {
this.id = id;
}


public String getLastName() {
return lastName;
}


public void setLastName(String lastName) {
this.lastName = lastName;
}


public String getEmail() {
return email;
}


public void setEmail(String email) {
this.email = email;
}


public Integer getGender() {
return gender;
}


public void setGender(Integer gender) {
this.gender = gender;
}






public Float getSalary() {
return salary;
}


public void setSalary(Float salary) {
this.salary = salary;
}


@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email="
+ email + ", gender=" + gender + ", salary=" + salary + "]";
}


public Employee(Integer id, String lastName, String email, Integer gender
) {
super();
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
}


public Employee() {
// TODO Auto-generated constructor stub
}
}

它会直接返回一个字符串;


http://download.csdn.net/detail/qq_25909453/9826395

猜你喜欢

转载自blog.csdn.net/qq_25909453/article/details/70804873
今日推荐