美文网首页
springmvc02

springmvc02

作者: 编程_书恨少 | 来源:发表于2018-09-13 18:32 被阅读0次

1. 参数绑定之数组

可以直接提交Integer[]

//删除多个
    @RequestMapping(value = "/deletes.action")
    public ModelAndView deletes((Integer[] ids)){
        
        ModelAndView mav = new ModelAndView();
        mav.setViewName("success");
        return mav;
    }

也可以将数组放入包装类中

public class QueryVo {

    
    //商品
    private Items items;
    
    // 数组绑定
    Integer[] ids;
    
  // List绑定
    private List<Items> itemsList;
    
}

2. 参数绑定之List

List绑定只能用包装类来写,直接在请求出写成List springmvc不支持

//修改
    @RequestMapping(value = "/updates.action",method = {RequestMethod.POST,RequestMethod.GET})
    public ModelAndView updates(QueryVo vo){
        
        
        ModelAndView mav = new ModelAndView();
        mav.setViewName("success");
        return mav;
    }

3. @RequestMapping

3.1 URL路径映射,多个路径访问同一个方法
@RequestMapping(value = { "itemList", "itemListAll" })
public ModelAndView queryItemList() {
}
3.2 添加在类上面

在class上添加@RequestMapping(url)指定通用请求前缀, 限制此类下的所有方法请求url必须以请求前缀开头

@Controller
@RequestMapping("item")
public class ItemController {
}
3.3 请求方法限定

不加限制默认就都可以访问

只能POST访问
@RequestMapping(value = "itemList",method = RequestMethod.POST)

GET和POST都可以
@RequestMapping(method = {RequestMethod.GET,RequestMethod.POST})

4. Controller层方法返回值

@Autowired
    private ItemService itemService;
    /**
     * 1.ModelAndView  无敌的    带着数据  返回视图路径           不建议使用
     * 2.String    返回视图路径     model带数据      官方推荐此种方式   解耦   数据  视图  分离  MVC  建议使用  
     * 3.void       ajax  请求  
     */
    @RequestMapping(value = {"/item/itemlist.action","/item/itemlisthaha.action"})
    public String itemList(Model model,HttpServletRequest request,HttpServletResponse response) throws MessageException{

        List<Items> list = itemService.selectItemsList();
        
        model.addAttribute("itemList", list);
        return "itemList";
}
        // 重定向
        return "redirect:/itemEdit.action?id=" + vo.getItems().getId();
        // 转发
        return "forward:/item/itemlist.action";

5. 异常处理

  1. 在springmvc.xml中配置异常处理类
<!-- Springmvc的异常处理器 -->
        <bean class="com.itheima.springmvc.exception.CustomExceptionResolver"/>
  1. CustomExceptionResolver实现处理异常的接口
/**
 * 异常处理器的自定义的实现类
 * @author lx
 *
 */
public class CustomExceptionResolver implements HandlerExceptionResolver {

    public ModelAndView resolveException(HttpServletRequest request, 
            HttpServletResponse response, Object obj,
            Exception e) {
        // TODO Auto-generated method stub  发生异常的地方 Serivce层  方法  包名+类名+方法名(形参) 字符串
        //日志    1.发布 tomcat war  Eclipse  2.发布Tomcat  服务器上  Linux  Log4j
        
        ModelAndView mav = new ModelAndView();
        //判断异常为类型
        if(e instanceof MessageException){
            //预期异常
            MessageException me = (MessageException)e;
            mav.addObject("error", me.getMsg());
        }else{
            mav.addObject("error", "未知异常");
        }
        mav.setViewName("error");
        return mav;
    }

}

  1. 书写预期异常类 MessageException
public class MessageException extends Exception{

    
    private String msg;

    public MessageException(String msg) {
        super();
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
    
}
  1. 在请求中触发异常
@RequestMapping(value = {"/item/itemlist.action","/item/itemlisthaha.action"})
    public String itemList(Model model,HttpServletRequest request,HttpServletResponse response) throws MessageException{
        
// 运行时异常
//      Integer i = 1/0;
        
        // 预期异常
        if(null == null){
            throw new MessageException("商品信息不能为空");
        }
        
        return "itemList";
    }

6. 图片上传

导包commons-fileupload-1.2.2.jar和commons-io-2.4.jar

在springmvc.xml中配置上传接口的实现类

<!-- 上传图片配置实现类 -->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- 上传图片的大小   B   5M  1*1024*1024*5-->
            <property name="maxUploadSize" value="5000000"/>
        </bean>
    @RequestMapping(value = "/updateitem.action")
//  public ModelAndView updateitem(Items items){
    public String updateitem(QueryVo vo,MultipartFile pictureFile) throws Exception{

        //生成图片名 
        String name = UUID.randomUUID().toString().replaceAll("-", "");
        //jpg
        String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename());
        // 图片保存到D盘
        pictureFile.transferTo(new File("D:\\upload\\" + name + "." + ext));
        
        vo.getItems().setPic(name + "." + ext);
        //修改
        itemService.updateItemsById(vo.getItems());
        
        return "success";
        
    }

7. json数据交互

@RequestBody注解:用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容(json数据)转换为java对象并绑定到Controller方法的参数上。

@ResponseBody注解:用于将Controller的方法返回的对象,通过springmvc提供的HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端

    //json数据交互
    @RequestMapping(value = "/json.action")
    public @ResponseBody Items json(@RequestBody Items items){
        
//      System.out.println(items);
        
        return items;
    }

8. RestFul风格的开发

前端的访问链接是:http://localhost:8088/item/itemlist/2.action
将2作为id传入到后端作为参数查询items表

//RestFul风格的开发
    @RequestMapping(value = "/itemEdit/{id}.action")
    public ModelAndView toEdit1(@PathVariable Integer id,
            HttpServletRequest request,HttpServletResponse response
            ,HttpSession session,Model model){
        
        
        //查询一个商品
        Items items = itemService.selectItemsById(id);
        ModelAndView mav = new ModelAndView();
        //数据
        mav.addObject("item", items);
        mav.setViewName("editItem");
        return mav;
        
    }

9. 拦截器

在springmvc.xml中配置拦截器

<!-- SPringmvc的拦截器 -->
        <mvc:interceptors>
            <!-- 多个拦截器 -->
            <mvc:interceptor>
                <mvc:mapping path="/**"/>
                <!-- 自定义的拦截器类 -->
                <bean class="interceptor.Interceptor1"/>
            </mvc:interceptor>
    <!--        <mvc:interceptor>
                <mvc:mapping path="/**"/>
                自定义的拦截器类
                <bean class="interceptor.Interceptor2"/>
            </mvc:interceptor> -->
        </mvc:interceptors>

拦截器1

public class Interceptor1 implements HandlerInterceptor{

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("方法前 1");
        return true;
    }
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // TODO Auto-generated method stub
        System.out.println("方法后 1");
        
    }
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
        System.out.println("页面渲染后 1");
        
    }



}

拦截器2

public class Interceptor1 implements HandlerInterceptor{

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("方法前 2");
        return true;
    }
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // TODO Auto-generated method stub
        System.out.println("方法后 2");
        
    }
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
        System.out.println("页面渲染后 2");
        
    }
}
多个拦截器的方法调用顺序

总结:
preHandle按拦截器定义顺序调用
postHandler按拦截器定义逆序调用
afterCompletion按拦截器定义逆序调用

postHandler在拦截器链内所有拦截器返成功调用
afterCompletion只有preHandle返回true才调用

10.拦截器应用,拦截登录请求

public class Interceptor1 implements HandlerInterceptor{

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("方法前 1");
        //判断用户是否登陆  如果没有登陆  重定向到登陆页面   不放行   如果登陆了  就放行了
        // URL  http://localhost:8080/springmvc-mybatis/login.action
        //URI /login.action
        String requestURI = request.getRequestURI();
        if(!requestURI.contains("/login")){
            String username = (String) request.getSession().getAttribute("USER_SESSION");
            if(null == username){
                response.sendRedirect(request.getContextPath() + "/login.action");
                return false;
            }
        }
        return true;
    }
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // TODO Auto-generated method stub
        System.out.println("方法后 1");
        
    }
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
        System.out.println("页面渲染后 1");
        
    }



}

相关文章

  • springmvc02

    1. 参数绑定之数组 可以直接提交Integer[] 也可以将数组放入包装类中 2. 参数绑定之List List...

网友评论

      本文标题:springmvc02

      本文链接:https://www.haomeiwen.com/subject/vqywgftx.html