第十二周作业(二)

1、学习参数绑定

(1)url地址栏参数传递与绑定

  • 体会通过url地址栏参数的传递原理

通过ur1传递的参数,只能到达第二个页面,没法保存,所以不能传递到第三个页面。

url.jsp

<body>
    <a href="url?Uid=123">传递id参数</a>
    </body>

UidController.java

package controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UidController {

    @RequestMapping("url")
    public ModelAndView getUrlid(Integer Uid){
        ModelAndView mav= new ModelAndView("urlid");

         System.out.println(Uid);  //会输出到控制台,不是jsp页面中 
         mav.addObject("aa", Uid);
        mav.setViewName("urlid");
        return mav;
    }
}

urlid.jsp

<body>
<p>欢迎访问!</p>
aa的值是:${aa}<br>
Uid的值是:${Uid}
</body>

运行结果如下:

 点击进入下一级:

 此时控制台显示:

(2)表单参数的传递与绑定

  • 练习how2j,练习传递表单元素的值并显示

MVC系列教材 (四)- 使用SERVLET 验证用户是否登陆

关键想法如下:

①在LoginServlet 把验证成功的用户加入到 Session

如果用户输入正确的账号密码,就跳转到 listHero,并且把用户名以"userName"放进session
如果用户输入错误的账号密码,就跳转到 login.html,让用户重新登陆

import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class LoginServlet extends HttpServlet {
 
    private static final long serialVersionUID = 1L;
 
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
 
        if ("admin".equals(name) && "123".equals(password)) {
            request.getSession().setAttribute("userName", name);
            response.sendRedirect("listHero");
        } else {
            response.sendRedirect("login.html");
        }
 
    }
}

②在HeroListServlet判断Session中是否有数据

从session中取出userName,如果是空,就表示用户没有登录,或者登录已经超过了30分钟。 客户端跳转到login.html,让用户重新登陆

package servlet;
 
import java.io.IOException;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import bean.Hero;
import dao.HeroDAO;
 
public class HeroListServlet extends HttpServlet {
 
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        String userName = (String) request.getSession().getAttribute("userName");
        if (null == userName) {
            response.sendRedirect("login.html");
            return;
        }
 
        int start = 0;
        int count = 5;
 
        try {
            start = Integer.parseInt(request.getParameter("start"));
        } catch (NumberFormatException e) {
            // 当浏览器没有传参数start时
        }
 
        int next = start + count;
        int pre = start - count;
 
        int total = new HeroDAO().getTotal();
 
        int last;
        if (0 == total % count)
            last = total - count;
        else
            last = total - total % count;
 
        pre = pre < 0 ? 0 : pre;
        next = next > last ? last : next;
 
        request.setAttribute("next", next);
        request.setAttribute("pre", pre);
        request.setAttribute("last", last);
 
        List<Hero> heros = new HeroDAO().list(start, count);
        request.setAttribute("heros", heros);
 
        request.getRequestDispatcher("listHero.jsp").forward(request, response);
 
    }
}

最后的运行结果如下:

 提交数据后显示:

  •  练习注册案例

reg.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Insert title here</title>
</head>
<body>
<form action="regsubmit" method="post">
        姓名:<input type="text" name="name" /> <br/>
        性别:<input type="text" name="xingbie" /> <br/>
        爱好:
        <input type="checkbox" name="hobby" value="football" />足球
        <input type="checkbox" name="hobby" value="bascketball" />蓝球
        <input type="checkbox" name="hobby" value="dance" />跳舞
        <input type="checkbox" name="hobby" value="sing" />唱歌<br/>
        <input type="submit" value="注册" />
    </form>
</body>
</html>

 RegController.java

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import pojo.Reg;

@Controller
public class RegController {
@RequestMapping("/regsubmit")

public ModelAndView reg(Reg reg){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("reglist");
    return modelAndView;
}
    
}

Reg.java

package pojo;

public class Reg {
    public String name;
    public String xingbie;
    public String[] hobby;
    public String hobbys;
    
public String getHobbys() {
        hobbys="";
        for(int i=0;i<hobby.length;i++)
        {
            hobbys+=hobby[i]+"   ";
        }
        return hobbys;
    }
    public void setHobbys(String hobbys) {
        this.hobbys = hobbys;
    }
    
public String[] getHobby() {
        return hobby;
    }
public void setHobby(String[] hobby) {
        this.hobby = hobby;
    }
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getXingbie() {
    return xingbie;
}
public void setXingbie(String xingbie) {
    this.xingbie = xingbie;
}
}

 reglist.jsp

<%@ page language="java" import="java.sql.*"
    contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
body {font-size:30px;}

</style>
</head>
<body>
    姓名:${reg.name }<br />
     性别:${reg.xingbie }<br />
     爱好:${reg.hobbys}
</body>
</html>

运行结果为:

点击注册提交后显示:

 问题:在这里时又遇到了中文乱码的情况,最后发现只要加上method="post"就正常显示中文字符,同时在web.xml配置过滤器即可解决。

2、计算器练习

大致思路:web目录下的jisuan.jsp用来显示计算器页面并提交计算,在Calculator类中书写利用if语句求结果,output.jsp用来呈现最后计算结果。

jisuan.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>计算器</title>
</head>
<body>
    <form action="addcalculator" method="post">
    <p>第一个数:<input type="text" name="numOne"></p>
    <p>运算符:<select name="yunSuan">
        <option>+</option>
        <option>-</option>
        <option>*</option>
        <option>/</option>
    </select></p>
    <p>第二个数:<input type="text" name="numTwo"></p>
    <input type="submit" value="计算">
</form>
</body>
</html>

CalculatorController.java

package com.mr.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.mr.entity.Calculator;

@Controller
public class CalculatorController {
    @RequestMapping("/addcalculator")
    public ModelAndView add(Calculator calculator) throws Exception{
    	ModelAndView modelAndView = new ModelAndView("output");
    	return modelAndView;
    }
}

Calculator.java

package com.mr.entity;

public class Calculator {
	private int numOne;
    private int numTwo;
    private String yunSuan;
    private int result;
    
    public int getNumOne(){
        return numOne;
    }

    public void setNumOne(int numOne){
        this.numOne = numOne;
    }
    public int getNumTwo(){
        return numTwo;
    }
    public void  setNumTwo(int numTwo){
        this.numTwo=numTwo;
    }
    public String getYunSuan(){
        return yunSuan;
    }
    public void setYunSuan(String yunSuan){
        this.yunSuan=yunSuan;
    }
    
    public int getResult(){
        if (yunSuan.equals("+")){
        	result = numOne + numTwo;
        }
        if (yunSuan.equals("-")){
        	result = numOne - numTwo;
        }
        if (yunSuan.equals("*")){
        	result = numOne * numTwo;
        }
        if (yunSuan.equals("/")){
        	result = numOne / numTwo;
        }
        return result;
    }
    public void setResult(int result){
    	this.result = result;
    }
}

output.jsp

<%@ page language="java" import="java.sql.*"
    contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
您选择的运算符是:${calculator.yunSuan}<br/>
您的运算结果为:${calculator.result}
</body>
</html>

SpringMVC.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/context         
	http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	
	<context:component-scan base-package="com.mr.controller" />
	<bean id="irViewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

最后呈现的结果:

 减

 乘

 除

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值