sm框架-登录界面小结

一、jsp页面
1.form表单提交
<form action="<%=request.getContextPath()%>/dologin" id="myform">
			<table id="mytable">
				<tr>
					<td>用户名:</td>
					<td><input type="text" id="username" name="username" style="height:30px"/></td>
				</tr>
				<tr>
					<td>密    码:</td>
					<td><input type="password" id="password" name="password"style="height:30px"/></td>
				</tr>
				<tr>
					<td>验证码:</td>
					<td>
						<input type="text"  id="code" name="code" style="height:30px"/>
					</td>
					<td>
					  <img id="checkcode" src="<%=request.getContextPath()%>/getYzm" width="80px" height="40px"/>
					</td>
				</tr>
				<tr>
					<td>
						<input type="button" value="登录" style="padding:5px 10px;"οnclick="fn()"/>
					</td>
					<td >
						<input type="button" value="注册" style="padding:5px 10px;margin-left: 40px;"οnclick="window.location.href='register'"/>
					</td>
				</tr>
			</table>
			</form>
注意: <%=request.getContextPath()%>是为了解决相对路径的问题,可返回站点的根路径。
其中本次是将表单内容提交到/dologin 目录下,提交方式采用了ajax的提交方式,但提交之前要
判断表单中是否有相应的数据,避免出现空值和空串:
function fn() {
				    var username=$("#username").val().trim();
				  	var password=$.trim($("#password").val());
				    var code=$("#code").val().trim();
				    if(code==""){
				    	alert("请输入验证码")
				    	return;
				    }
				  	if(username ==""){
				    	alert("用户名不能为空");
				        return;
				   	}
				   if(password ==""){
				    	alert("密码不能为空");
				        return;
				   	}
注意:trim()方法返回调用字符串对象的一个副本,但是所有起始和结尾的空格都被删除了
例:String s=" Hello World ".trim();就是把"Hello World"放入s中。
2.ajax提交表单
   $.ajax({
					   url:"${pageContext.request.contextPath}/dologin",
					   type:"post",
					   data:$("#myform").serialize(),
					   dataType:"json",
					   success:function(data){
						   if(data.status==0){
							   alert("验证码错误!");
						   }else  if(data.status==-1){
							   alert("用户名或密码错误!");
						   }else{
							   if(data.role=="普通用户"){
								   alert("登录成功!");
								   location.href="${pageContext.request.contextPath}/game";   
							   }
							   if(data.role=="管理员"){
								   alert("登录成功!");
								   location.href="${pageContext.request.contextPath}/user";   
							   } 
						   }   
					   }
				   })
注意: ajax属性很多,不需要每个属性都标上,其中几个常用的属性如下;
url:表单所提交的地址;form中的action
async: false(默认是true);当async: true 时,ajax请求是异步的。
type:提交方式
post:通过HTTP post机制,将表单内各个字段与其内容放置在HTML HEADER内一起
传送到ACTION属性所指的URL地址,是看不到相对安全一些;传递的参数无限制的。
get: 把参数数据队列加到提交表单的ACTION属性所指的URL中所以是信息不安全的;
并且url的长度是有限制的。
data:serialize()方法序列化表单内容为字符串,用于Ajax请求。

二、cotroller控制层
1.标签的注入:
ServiceImpl 实现类: 
添加@Service注解将Service 对象注入bean容器,
并使用@Autowired将 Dao层对象注入 Service对象中
@Service("userService")
public class UserServiceImp implements UserService {

	@Autowired
	private UserDao userDao;
	public void regist(User user) {
		userDao.addUser(user);
	}
Controller 类
使用@Controller将Controller对象注入bean容器中
并使用@Autowired将Service层对象注入Controller对象的属性中
@Controller
@RequestMapping("/")
public class UserController {
	@Autowired
	private GuessService guessService;	
	@Autowired	
	@Qualifier("userService")
	private UserService userService;
	
	@RequestMapping("/")  
    public ModelAndView getIndex(){    
	   ModelAndView mav = new ModelAndView(); 
	   mav.setViewName("index");
       return mav;  
    }
@Qualifier在使用Spring框架中@Autowired标签时默认情况下使用 @Autowired 注释进行自动注入时,Spring 容器中匹配的候选 Bean 数目必须有且仅有一个。
@RequestMapping注解的作用是映射路径标签
@ResponseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML

2.处理传入数据
对于ajax传入到controller层的数据需要接收处理,比如本次是将表单中的信息传入,首先判断其验证码是否正确,然后判断其用户名和密码是否正确,最后返回相应的状态码到原来的页面,显示相应的内容
@RequestMapping("dologin")  
	@ResponseBody
    public Map<String,Object> dologin(User user,HttpServletRequest request){
		Map<String,Object> map=new HashMap<String, Object>();
		String inputcode =request.getParameter("code");
		String checkcode =(String)request.getSession().getAttribute("_code"); 
		if(inputcode.equals(checkcode)){
			String username=user.getUsername();
			String password=user.getPassword();
		    List<User> list= userService.login(username, password);
		    if(list!=null&&list.size()>0){
		    	User resUser=list.get(0);
		    	map.put("status", 1);
		    	map.put("role", resUser.getRole()); 	
		    }else{
		    	map.put("status", -1);
		    }
		}else{
			map.put("status", 0);		
		}
		return map;	
	}
	
注意:
1、验证码是存放在session中的,当需要验证码时只需要从session中取出,不需要重新
创建session,使用HttpServletRequest 对象直接调用即可
2、Map<String,Object> map=new HashMap<String, Object>();
map中的数据以键值对的形式存在,我们知道某一个键时,我们很容易通过键找到对应的值
三、UUID的使用
当在做猜数字游戏的时候,需要把猜测记录回显到jsp时,但当时每次记录是插入数据库中的,造成数据太多,所以用到uuid,是每次猜测的记录生成唯一标识,重新计数
dao层
public interface GuessDao {
	public void insertGuess(Guess guess);
	public List<Guess> selectGuess(String uuid);
}
mapper数据接入层
<select id="selectGuess" resultType="com.itcast.domain.Guess" parameterType="string">
	select *from guess
	where 1=1
	<if test="_parameter!=null and _parameter!=''">
	  and uuid=#{uuid}
	</if>
</select
controller层
	@RequestMapping("guess")	
	@ResponseBody
    public Map<String,Object> guess(String num,String uuid,HttpServletRequest request,HttpServletResponse response){ 
        if(uuid==null||"".equals(uuid)){
        	uuid=getUUID();
        }
		Map<String,Object> map=new HashMap<String, Object>();
		String random=(String) request.getSession().getAttribute("random");
		if(random==null || "".equals(random)){
			random=Integer.toString((int)(Math.random()*100+1));
			request.getSession().setAttribute("random", random);
		}
		int result;
		if(num.compareTo(random)==0){
			result=0;
			random=Integer.toString((int)(Math.random()*100+1));
			request.getSession().setAttribute("random", random);		
		}else 
			if(num.compareTo(random)<0){			
			result=-1;
		}else{
			result=1;
		}
		//保存猜的記錄
		Guess guess =new Guess();
	    int num1=Integer.valueOf(num).intValue();
		guess.setGuessnum(num1);
		guess.setUuid(uuid);
		guessService.insertGuess(guess);
		map.put("result", result);
		//回显记录
	    List<Guess> guessList = guessService.selectGuess(uuid);      
	    map.put("guessList", guessList);	
	    map.put("uuid", uuid);
		return map;
    } 
	
	//生成唯一标识
	public static String getUUID(){
        UUID uuid=UUID.randomUUID();
        String str = uuid.toString(); 
        String uuidStr=str.replace("-", "");
        return uuidStr;
      }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值