springMVC用户登录实例(二)

SpringMVC使用拦截器(Interceptor)实现用户登录校验 在系统中,经常需要在处理用户请求之前和之后执行一些行为,例如检测用户的权限,或者将请求的信息记录到日志中。当然不仅仅这些,所以需要一种机制,拦截用户的请求,在请求的前后添加处理逻辑。 SpringMVC提供了Interceptor拦截器机制,用于请求的预处理和后处理。在SpringMVC中定义一个拦截器有两种方法:第一种是实现HandlerInterceptor接口,或者继承实现了Handler... 阅读详情


1.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>02_spring_mvc_user</display-name>
  
   <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- springMVC 1.创建servlet -->
  <servlet>
  	<!-- 需要在WEB-INF下面创建对应的hello-servlet.xml -->
  	<servlet-name>user</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  	<servlet-name>user</servlet-name>
  	<!-- 捕获所有请求,基于rest -->
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  
  
  <!-- 
  		OS(OpenSymphony)的SiteMesh是一个用来在JSP中实现页面
  		布局和装饰(layout and decoration)的框架组件,
  		能够帮助网站开发人员较容易实现页面中动态内容和静态装饰外观的分离
   -->
  <filter>
    <filter-name>sitemesh</filter-name>
    <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>sitemesh</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

2.user-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- springMVC 2.创建对应的servlet -->
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        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">
        
        
    <!-- 开启SpringMVC -->
        <mvc:annotation-driven/>
        <context:component-scan base-package="cn.edu.zttc.controller"></context:component-scan>
        
        <mvc:resources location="/resources/" mapping="/resources/**"/>
        
	<!-- 配置视图的前缀和后缀 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        	<!-- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> -->
        	<property name="prefix" value="/WEB-INF/jsp/"></property>
        	<property name="suffix" value=".jsp"></property>
        </bean>
        
	    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	    	<property name="maxUploadSize" value="5000000"></property>
	    </bean>
</beans>

3.decorators.xml

<?xml version="1.0" encoding="UTF-8"?>

<!-- 
	装饰者,将所有页面都潜入basic的页面之中,使用
	<decorator:body />标签
	被嵌入的页面不用填写html的头标签等,只需要写body信息
 -->
<decorators defaultdir="/WEB-INF/temp/">
    <!-- Any urls that are excluded will never be decorated by Sitemesh -->
    <excludes>
        <pattern>/json*</pattern>
    </excludes>
    <decorator name="main" page="basic.jsp">
        <pattern>/*</pattern>
    </decorator>
</decorators>

4.basic.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>
<!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>
<h1>
User Manager
</h1>
<hr/>
<decorator:body />
</body>
</html>

5.error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!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>error</title>
</head>
<body>
${ex.message }
</body>
</html>

6.login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!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>
<form method="post">
	username<input type="text" name="username"/><br/>
	password<input type="password" name="password"/><br/>
	<input type="submit"/>
</form>
</body>
</html>

7.add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!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>
<sf:form method="post" modelAttribute="user" enctype="multipart/form-data">
	username<sf:input path="username"/><sf:errors path="username"/><br/>
	password<sf:input path="password"/><sf:errors path="password"/><br/>
	nickname<sf:input path="nickname"/><br/>
	email<sf:input path="email"/><sf:errors path="email"/><br/>
	file<input type="file" name="files"/><br/>
	file<input type="file" name="files"/><br/>
	<input type="submit"/>
</sf:form>
</body>
</html>

8.list.jsp

<%@ page language="java" 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">
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/resources/css/main.css">
<title>Insert title here</title>
</head>
<body>
${loginUser.nickname}----${redir}<br/>
<a href="add">添加用户</a>
<a href="login">用户登录</a><br/>
<!-- 获取的是map,所以需要先.value -->
<c:forEach items="${users }" var="user">
	<a href="${user.value.username}">查看用户</a><a href="${user.value.username}/update">更新</a><a href="${user.value.username}/delete">删除</a>${user.value.username }=====${user.value.nickname }<br/>
</c:forEach>
</body>
</html>

9.show.jsp

<%@ page language="java" 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>
${user.username }=====${user.nickname }=====${user.email }<br/>
</body>
</html>

10.update.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!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>
<sf:form method="post" modelAttribute="user">
	username<sf:input path="username"/><sf:errors path="username"/><br/>
	password<sf:input path="password"/><sf:errors path="password"/><br/>
	nickname<sf:input path="nickname"/><br/>
	email<sf:input path="email"/><sf:errors path="email"/><br/>
	<input type="submit"/>
</sf:form>
</body>
</html>

11.UserController

package cn.edu.zttc.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import cn.edu.zttc.vo.User;
import cn.edu.zttc.vo.UserException;
/**
 * springMVC加入了JSR303(Bean Validate的功能)
 * @author admin
 */
@Controller
@RequestMapping("/user")
@SessionAttributes(value="loginUser")
public class UserController {
	private final static Map<String, User> users = new HashMap<String, User>();
	public UserController(){
		users.put("ldh", new User("ldh", "123", "ldh@163.com", "华仔"));
		users.put("zxy", new User("zxy", "123", "ldh@163.com", "学友"));
		users.put("gfc", new User("gfc", "123", "ldh@163.com", "郭富城"));
		users.put("lm", new User("lm", "123", "ldh@163.com", "黎明"));
	}
	/**
	 * 获取用户列表
	 * @param model
	 * @return
	 */
	@RequestMapping({"/users","/"})
	public String list(Model model){
		model.addAttribute("users",users);
		return "user/list";
	}
	/**
	 * 跳转到添加页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String add(Model model){
		model.addAttribute(new User());
		return "user/add";
	}

	/**
	 * 
	 * 添加页面提交请求,post方式
	 * @param user
	 * @param file 上传文件方式
	 * @param binding 接收错误信息的(必须要在要进行验证的对象之后)
	 * @return
	 */
	//参数user与页面的form表单中的modelAttribute的值一样
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public String add(@Valid User user,BindingResult binding,@RequestParam MultipartFile[] files,HttpServletRequest req){
		if (binding.hasErrors()) {
			return "user/add";
		}
//		System.out.println(file.getContentType()+","+file.getName()+","+file.getOriginalFilename());
		String realPath = req.getSession().getServletContext().getRealPath("/resources/upload");
		for(MultipartFile file:files){
			try {
				System.out.println(realPath);
				FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath+"/"+file.getOriginalFilename()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		users.put(user.getUsername(), user);
		//执行客户端跳转
		return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"/user/users";
	}
	
	/**
	 * 显示用户信息
	 * @param username
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/{username}",method=RequestMethod.GET)
	public String show(@PathVariable String username,Model model){
		model.addAttribute(users.get(username));
		return "user/show";
	}
	
	/**
	 * 跳转到更新页面
	 * @param username
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/{username}/update",method=RequestMethod.GET)
	public String update(@PathVariable String username,Model model){
		model.addAttribute(users.get(username));
		return "user/update";
	}
	/**
	 * 更新页面提交请求
	 * @param username
	 * @param user
	 * @param br 接收错误信息的
	 * @return
	 */
	//参数user与页面的form表单中的modelAttribute的值一样
	@RequestMapping(value="/{username}/update",method=RequestMethod.POST)
	public String update(@PathVariable String username,@Valid User user,BindingResult br){
		if (br.hasErrors()) {
			return "user/update";
		}
		users.put(username, user);
		return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"/user/users";
	}
	
	/**
	 * 删除操作
	 * @param username
	 * @return
	 */
	@RequestMapping(value="/{username}/delete",method=RequestMethod.GET)
	public String delete(@PathVariable String username){
		users.remove(username);
		return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"/user/users";
	}

	/**
	 * 跳转到登录页面
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String login(){
		return "user/login";
	}
	/**
	 * 登录提交页面
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(String username,String password,Model model){
		if (!users.containsKey(username)) {
			throw new UserException("用户名不存在");
		}
		if (!password.equals(users.get(username).getPassword())) {
			throw new UserException("用户名密码不正确");
		}
		model.addAttribute("loginUser",users.get(username));
		return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"/user/users";
	}
	
	/**
	 * 捕获异常执行的方法
	 * @return
	 */
	@ExceptionHandler(UserException.class)
	public String handlerException(Exception ex,HttpServletRequest req){
		req.setAttribute("ex", ex);
		return "error";
	}
	
	/**
	 * redirect方式传request范围的对象
	 * @param model
	 * @param ra
	 * @return
	 */
	@RequestMapping(value="/redir")
	public String redir(Model model,RedirectAttributes ra){
		ra.addFlashAttribute("redir","我的redirect方式传request范围的对象");
		return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"/user/users";
	}
}

12.User

package cn.edu.zttc.vo;

import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotEmpty;


public class User {
	private String username;
	private String password;
	private String email;
	private String nickname;
	
	public User() {
		super();
	}
	public User(String username, String password, String email, String nickname) {
		super();
		this.username = username;
		this.password = password;
		this.email = email;
		this.nickname = nickname;
	}
	
	@NotEmpty(message="用户名不能为空")
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}

	@NotEmpty(message="密码不能为空")
	@Size(min=1,max=20,message="密码长度应在1-20之间")
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	@Pattern(regexp="^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$",message="邮箱格式不正确")
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getNickname() {
		return nickname;
	}
	public void setNickname(String nickname) {
		this.nickname = nickname;
	}
}

13.UserException

package cn.edu.zttc.vo;

public class UserException extends RuntimeException {
	private static final long serialVersionUID = 1L;

	public UserException() {
		super();
		// TODO Auto-generated constructor stub
	}

	public UserException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}

	public UserException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	public UserException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}

}

项目结构图:


引入的包:


SpringMVC + Mybatis 实现用户登录功能 因业务需要,刚刚接触Web编程。之前仅有移动端经验,一个简单的登录功能,都花费了不少功夫,当然部分原因是想尽量遵循框架的规范。 实现过程参考了 Spring学习之SpringMVC框架快速搭建实现用户登录功能 mybatis实战教程(mybatis in action),mybatis入门到精通 感谢两位的分享。 1.首先配置web.xml,以.do结尾的请求,将通过Disp 阅读详情

相关推荐

spring mvc 登陆验证

最简单的Spring MVC 架构的登陆验证系统。

使用springmvc框架完成登录

GoodsController类。UserController类。index.jsp页面。login.jsp页面。zhuye.jsp页面。error.jsp页面。

wangzhigang0926的博客 755

springmvc框架的用户登录注册的简单实现

spring初学这可以参考的用户登录注册简单的例子,mvc设计模式的spring框架,适合初学者,比较简单,容易理解和入门

SpringMvc简单使用——用户登录注册

SpringMvc简单使用——用户登录注册

qq_54000767的博客 5092

springMVC实现用户注册及登陆

Java+tomcat+springMVC;实现用户注册及登陆 .没有Service与dao

SpringMVC实现简单登录配置

SpringMVC实现简单登录配置,其中各种具体的配置文件编写,实现了一个简单的使用springmvc的登录例子

SpringMVC登录

1.创建数据库chapter13,表t_user 2.创建项目并导入jar包 3.创建相关文件,结构如下 MyController01.java package com.sunhuimin.controller; import java.io.IOException; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import org.springframework.stereo

weixin_45911547的博客 588

Git系列(一)、Git基础教程【建议收藏】

Git一、Git简介1.1、什么是Git? 一、Git简介 1.1、什么是Git? Git是一个开源的分布式版本控制系统,用于敏捷高效地处理任何或大或小的项目。 Git是Linus Torvalds为了帮助管理Linux内核开发而开发的一个开放源代码的版本控制软件。 Git与常用的版本控制工具CVS、Subversion等不同,它采用了分布式版本库的方式,不用服务器端软件支持。 .........

一宿君 4万+

SpringMVC案例 - 简单登录

springmvc 的简单登陆

高冷的上官梓芸的博客 6850

EDEM在农业机械设计中的实战应用:以谷物收割机优化为例

本文以谷物收割机优化为例,详细阐述了EDEM离散元仿真软件在农业机械设计中的实战应用。通过构建精准的“数字谷物”模型与农机部件动态界面,利用GPU加速完成大规模颗粒系统仿真,有效诊断并解决了籽粒夹带损失与清选负荷不均等田间难题,实现了从仿真分析到田间验证的设计优化闭环。

weixin_29256771的博客 108

NSIDC海冰运动产品-速度矢量场图绘制(数据下载和处理--年、季节平均)【python/basemap】

入门级NSIDC海冰运动产品速度矢量场图绘制(数据下载和处理--年、季节平均)【python/basemap】

Mluoo的博客 2959

SpringMVC学习之用户登录(二)

SpringMVC 参数传递与接受

何大江的博客 742

飞控芯片的隐形战场:传感器冗余与实时OS的可靠性革命

本文深入探讨飞控芯片在工业级无人机中的可靠性设计,聚焦传感器冗余架构与实时操作系统(RTOS)的容错机制。通过多IMU备份、自适应加权融合算法及NuttX、ChibiOS等RTOS的故障隔离技术,确保系统在极端环境下毫秒级自愈。文章还涵盖开源生态如PX4的跨平台移植及RISC-V架构的应用,为高可靠性飞控系统提供关键技术参考。

z5a6b的博客 877

用户登录和授权(二)springmvc+security实现

全部代码地址: https://github.com/pshdhx/security-springmvc-pshdhx.git 首先,拦截用户的请求就不用web.xml或者是spring-mvc.xml来做了。直接上security的配置文件; /** * security配置 */ @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter {..

pshdhx的博客 312

【异常】安装hermes-agent时Git克隆大仓库报错:error: RPC failed; curl 92 HTTP/2 stream 5 was not closed cleanly: CAN

摘要:本文分析了Ubuntu服务器执行Git递归克隆时出现的网络传输中断错误(HTTP/2流异常关闭、数据截断)。主要原因是网络限制、协议兼容问题和缓冲区不足。提供了四种解决方案:1)扩大Git HTTP缓冲区;2)切换为HTTP/1.1协议;3)采用浅克隆+分步拉取子模块;4)网络优化措施。重点推荐浅克隆分步拉取作为最有效方案,所有方法无需重启即可生效,可快速解决大仓库递归克隆失败问题。

奶爸的编程之路,也就一周冷个三天 670

【Bug已解决】Claude Code WebFetch 报错 Unable to verify if domain is safe to fetch 解决方案

方案适用场景推荐指数放行域名校验接口根本解决方式,需要网络管理员配合⭐⭐⭐⭐⭐curl 手动验证具体拦截环节精确定位问题,避免排查方向跑偏⭐⭐⭐⭐⭐排查企业 SSL 中间人代理证书企业统一代理策略较严格的环境⭐⭐⭐⭐检查系统时间准确性排除证书有效期误判的可能性⭐⭐⭐手动复制内容作为过渡方案网络策略调整周期较长的场景⭐⭐⭐报错的本质是**WebFetch。

一键难忘的博客 4503

SpringMVC+Apache Shiro+JPA(hibernate)案例教学(二)基于SpringMVC+Shiro的用户登录权限验证...

序:   在上一篇中,咱们已经对于项目已经做了基本的配置,这一篇文章开始学习Shiro如何对登录进行验证。 教学: 一、Shiro配置的简要说明。   有心人可能注意到了,在上一章的applicationContext.xml配置文件中,包含以下配置。 <!-- 項目自定义的Realm --> <bean id="shiroDbReal...

diaojie7665的博客 164

攻克低照度检测难题:YOLOv11主干网络增强新方案PE-YOLO详解

编码器部分# 解码器部分self.dec_conv2 = nn.Conv2d(512, 128, 3, padding=1) # 跳跃连接self.dec_conv3 = nn.Conv2d(256, 64, 3, padding=1) # 跳跃连接self.dec_conv4 = nn.Conv2d(128, 32, 3, padding=1) # 跳跃连接# 编码路径# 解码路径(带跳跃连接)

FJN110的博客 106

JAVA面试题分享五百二十三:SpringBoot不用ThreadLocal实现登录用户上下文

我在实际的工作中,经常遇见ThreadLocal污染的局面(A用户登录了,上下文取到的却是B用户的信息),基本上都是没有及时销毁ThreadLocal所致。用户调用业务接口,Filter拦截,校验JWT,并将Redis存储的用户信息写入ThreadLocal,例如LoginUserContext等。虽然也很容易规避,但我一直想着能否不用ThreadLocal,毕竟我能力有限,才疏学浅,一看有“Thread”字样的,就犯怵。一般来说,用户登录成功,服务端下发JWT,并将用户信息写入Redis。

之乎者也·的博客 833

innovus:像ICC2一样设置placement label

ICC2有placement label/placement rule功能,能控制各种类型cell 之间的spacing规则,包括top和bottom edge的spacing。innovus也有相同的功能,以下示例方便大家了解用法。我们需要给所有OAI* cell之间设置一个spacing rule,让他们不要上下或者挨着。效果如下图,这个spacing指的是同一边的间距,不是cell间距。我正在「拾陆楼」和朋友们讨论有趣的话题,你⼀起来吧?

m0_61544122的博客 833

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

mvc java 实现文件下载_SpringMVC实现文件下载功能

本文实例为大家分享了SpringMVC文件下载的具体代码,供大家参考,具体内容如下两个案例1.为登录用户提供下载服务。2.阻止仅通过输入网址即可获取下载。文件下载概览为了将文件发送给浏览器,我们需要在控制器中完成以下操作:对请求处理方法使用void返回类型,并且在方法中添加HttpServletResponse参数。将响应的内容类型设为文件的内容类型。Content-Type标题在某个实体的bod...

weixin_39557199的博客 231

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

自定义SpringMVC参数解析器(1128_二_下午)

resolveArgument方法是自定义参数解析器的核心,先获取请求对象request,通过CookieUtil工具类中的getCookie方法获取到token令牌,如果token不为空,则通过myReidsTemplate中的get方法把user获取到。WebConfig是一个配置类,它实现了WebMvcConfigurer接口,并且重写了addArgumentResolvers方法,在该方法中可以将将咱们自己定义参数解析器添加到SpringMVC框架的参数解析器列表中,从而使其生效。

weixin_64760330的博客 381

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

微服务获取用户信息和OpenFeign传递用户

请求,因此我们可以将用户信息以请求头的方式传递到下游微服务。考虑到微服务内部可能很多地方都需要用到登录用户信息,因此我们可以利用SpringMVC的拦截器来实现登录用户信息获取,并存入。下单的过程中,需要调用商品服务扣减库存,调用购物车服务清理用户购物车。前端发起的请求都会经过网关再到微服务,由于我们之前编写的过滤器和拦截器功能,微服务可以轻松获取登录用户信息。编写微服务拦截器,拦截请求获取用户信息,保存到ThreadLocal后放行。改造网关过滤器,在获取用户信息后保存到请求头,转发到下游微服务。

sdg_advance的博客 1306

mvc php session,SpringMVC存取Session的两种方法

WEB 应用通常会引入 Session,用来在服务端和客户端之间保存一系列动作/消息的状态,比如网上购物维护 user 登录信息直到 user 退出。SpringMVC存取Session的两种方法,具体如下:方法一:使用servlet-api@Controllerpublic class ManagerController {@Resourceprivate ManagerService mana...

weixin_34576293的博客 172

Spring学习之SpringMVC框架快速搭建实现用户登录功能

关于SpringMVC的介绍我就不多说了,网上一搜一大堆,好多大鸟的博客都有详细的描述,之前看的跟开涛学SpringMVC,写的非常好,SpringMVC运行的流程和原理讲的非常的细致在此我引用一下开涛前辈的图片和文字,大家要是想看原文就点击上面的链接。 SpringMVC处理请求的流程图 大家一定要仔细的看,最好是拿张纸,画一画,可比你光看有效果,大家可以与纯MVC模式对

766
上一篇: springMVC简单的实现代码(一)
下一篇: maven的环境搭建与测试编写(一)
阳小良
博客等级 码龄17年 54粉丝 155原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值