(四)一步步来开始SSM:SpringMVC前后端传参实现

上一篇文章[(三)一步步来开始SSM:拦截器实现]

1、webapp下的文件夹访问方式

在开发过程中一直因为文件的访问路径问题反复修改代码,在终于调整完之后这里记录下

1、lib文件夹:该层级下的文件可以直接通过项目根目录访问到

2、WEB-INF:该目录下的所有文件都无法直接通过链接获取到,可以通过服务器的返回拿到

3、jsp页面读取文件:例如需要在index.jsp中访问lib目录里的文件,因为index.jsp与lib是同级的,"lib/xxx"可以直接拿到;例如需要在home.jsp中访问lib目录里的文件,"../lib/xxx"可以拿到;在adminManage.jsp可以通过"../../lib/xxx"拿到。

4、controller通过redirect跳转页面:

           "redirect:/index.jsp"该链接中有"/",访问的是根目录下的index.jsp页面;

           "redirect:home.do"访问的是同一类中的方法,它还有一种访问方式"redirect:/admin/home.do";

2、SpringMVC传递模型数据的方式

参考了:https://www.jianshu.com/p/4692eb52dce4,我在这里直接通过代码来展示比较直观

①:ModelAndView 要求:处理方法返回值类型为 ModelAndView。在方法体中我们通过该ModelAndView对象添加模型数据。

    @Controller
    public class HelloController {
 
        @RequestMapping(value = "/testModelAndView.do",method = RequestMethod.GET)
        public ModelAndView testModelAndView(){
            String viewName = "hello";//视图名
            ModelAndView modelAndView = new ModelAndView(viewName);

            //添加参数
            modelAndView.addObject("time",new Date()); 
            modelAndView.addObject("name","ModelAndView");
            return modelAndView;
        }
    }
    <html>
    <body>
    <!--以下的方法都可以拿到 -->
    <h2>method:${requestScope.name}</h2>
    ${requestScope.time}<br>
    ${requestScope.get("time")}<br>
    ${time}
    </body>
    </html>

②:Model/Map/ModelMap 要求:使用org.springframework.ui.Model、org.springframework.ui.ModelMap 或 Java.uti.Map 作为处理方法的入參时,当处理方法返回时,Map中的数据会自动添加到模型中,具体实例如下。

    @RequestMapping(value = "/testModel.do",method = RequestMethod.GET)
    public String testModel(Model model){
        model.addAttribute("time",new Date());
        model.addAttribute("name","Model");
        return "hello";
    }
 
    @RequestMapping(value = "/testMap.do",method = RequestMethod.GET)
    public String testMap(Map<String,Object> map){
        map.put("time",new Date());
        map.put("name","Map");
        return "hello";
    }
    <html>
    <body>
    <!--以下的方法都可以拿到 -->
    <h2>method:${requestScope.name}</h2>
    ${requestScope.time}<br>
    ${requestScope.get("time")}<br>
    ${time}
    </body>
    </html>

③:@SessionAttributes 使用该注解来注解某个类,使得将模型中的某个属性暂存到HttpSession 中,以便多个请求之间可以共享这个属性。

    @SessionAttributes({"name","time"})
    @Controller
    public class HelloController {
 
        @RequestMapping(value = "/testSessionAttribute.do",method = RequestMethod.GET)
        public String testSessionAttribute(Map<String,Object> map){
            map.put("time",new Date());
            map.put("name","SessionAttribute");
            return "sessionAttribute";
        }
    }
    <html>
    <body>
    <!--以下的方法都可以拿到 -->
    <h2>method:${requestScope.name}</h2>
    ${requestScope.time}<br>
    ${requestScope.get("time")}<br>
    ${time}
    sessionScope.time:${sessionScope.time}
    </body>
    </html>

④:@ModelAtrribute 该注解既可注解在有返回值的方法上,无返回值的方法上,还可以注解在方法入参上,当入參标注该注解后, 入参的对象就会放到数据模型中,具体如下。

    @ModelAttribute
    public User addUser(User user){//
        user.setName("Model Attribute in Mehtod ,this method has return value");
        return user;
 
    }
    @RequestMapping(value = "/testModelAttributeInReturnValueMethod.do",method = RequestMethod.GET)
    public String testModelAttributeInReturnValueMethod(){
        return "modelAttributeInRVMethod";
    }
    <html>
    <body>
    <h2>name:${user.name}</h2>
    </body>
    </html>

3、页面实现

首先我自己找了一份后台管理页面的模板,毕竟咱也不是学前端的,画不出那么好看的页面,直接借用现成的了。

将模板中的插件目录全部复制到项目的webapp文件夹下,并且将登录页作为网站访问的首页放进index.jsp中

下面是index.jsp的登录代码:

    <form class="form form-horizontal" action="admin/login.do" method="post" id="myForm" >
            <div class="row cl">
                <label class="form-label col-xs-3"><i class="Hui-iconfont">&#xe60d;</i></label>
                <div class="formControls col-xs-8">
                    <input id="name" name="name" value="${param.name}" type="text" placeholder="账户" class="input-text size-L">
                </div>
            </div>
            <div class="row cl">
                <label class="form-label col-xs-3"><i class="Hui-iconfont">&#xe60e;</i></label>
                <div class="formControls col-xs-8">
                    <input id="password" name="password" value="${param.password}" type="password" placeholder="密码" class="input-text size-L">
                </div>
            </div>
            <div class="row cl">
                <label class="form-label col-xs-3"></label>
                <div class="formControls col-xs-8" style="color:red" id="msg">
                    ${param.msg}
                </div>
            </div>
            <div class="row cl">
                <div class="formControls col-xs-8 col-xs-offset-3">
                    <input type="button" onclick="submitForm()" class="btn btn-success radius size-L" value="&nbsp;登&nbsp;&nbsp;&nbsp;&nbsp;录&nbsp;">
                    <input type="reset" class="btn btn-default radius size-L" value="&nbsp;取&nbsp;&nbsp;&nbsp;&nbsp;消&nbsp;">
                </div>
            </div>
    </form>

    <script>
    // 登录
    function submitForm() {
        var name = $('#name').val();
        var psw = $('#password').val();

        $('#msg').html();

        if (name == null || name.length == 0) {
            $('#msg').html('请输入用户名!');
            return;
        }
        if (psw == null || psw.length == 0) {
            $('#msg').html('请输入密码!');
            return;
        }
        $('#myForm').submit();
    }
    </script>
home.jsp的退出代码
<li class="dropDown dropDown_hover">
    <a href="#" class="dropDown_A">admin <i class="Hui-iconfont">&#xe6d5;</i></a>
    <ul class="dropDown-menu menu radius box-shadow">
        <li><a href="javascript:;" onClick="myselfinfo()">个人信息</a></li>
        <li><a href="signOut.do">退出</a></li>
    </ul>
</li>
AdminController.java  这里通过@SessionAttributes注释将管理员的登录信息保存到session中
package com.libraryManage.controller;

import com.libraryManage.model.Admin;
import com.libraryManage.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("/admin")
@SessionAttributes({"admin"})
public class AdminController {

    @Autowired
    private IAdminService adminService;

    /**
     * 管理员登录
     * @param request
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping("/login.do")
    public String adminLogin(HttpServletRequest request, Model model) {
        String name = request.getParameter("name");
        String password = request.getParameter("password");

        Admin admin = adminService.getAdminByName(name);

        if (admin == null) {
            model.addAttribute("msg", "用户名不存在");
            model.addAttribute("name", name);
            model.addAttribute("password", password);
            return "redirect:/index.jsp";
        } else if (!admin.getPassword().equals(password)) {
            model.addAttribute("msg", "密码错误");
            model.addAttribute("name", name);
            model.addAttribute("password", password);
            return "redirect:/index.jsp";
        }

        // 保存登录信息
        model.addAttribute("admin", admin);

        return "redirect:home.do";
    }
    
    /**
     * 管理员退出
     * @param session
     * @return
     */
    @RequestMapping("/signOut.do")
    public String adminSignOut(HttpSession session) {

        session.removeAttribute("admin");

        return "redirect:/index.jsp";
    }

    /**
     * 后台首页
     * @return
     */
    @RequestMapping("/home.do")
    public String home() {
        return "home";
    }
}

登录拦截器AdminLoginFilter   通过httpServletRequest.getSession().getAttribute("")获取到session中的管理员信息。

package com.libraryManage.filter;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AdminLoginFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                             Object o) throws Exception {
        HttpSession session = httpServletRequest.getSession();

        Object admin = session.getAttribute("admin");

        if (admin == null) {
            // 获取项目根路径
            ServletContext context = httpServletRequest.getServletContext();
            String basePath = String.valueOf(context.getAttribute("project_access_path"));
            httpServletResponse.sendRedirect(basePath + "/index.jsp");
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {

    }
}

4、界面效果

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值