window.open弹出窗口调用controller

前台图片调用js函数

<img src='${pageContext.request.contextPath}/FlatUI/img/link.png' id='report' alt='"+data[i].report+"' οnclick='changeUrl(this,"+data[i].id+")' width=15px height=15px/>

js函数, 其中有一项重要处理, 在open窗口关闭的同时, 当前窗口刷新

function changeUrl(element,id){
				  //alert(element.alt);
				  //window.open("/trip/changeUrl?id="+id);
				 var winObj = window.open ("/portal/trip/changeUrl?id="+id+"&item="+element.id+"&value="+element.alt, "newwindow", "height=100, width=800, toolbar =no, menubar=no, scrollbars=no, resizable=no, location=no, status=no, top=50,left=1100");
				 var loop = setInterval(function() {       
				        if(winObj.closed) {      
				            clearInterval(loop);      
				            //alert('closed');      
				            window.location.reload();
				        }      
				    }, 1); 				 
			  }

 controller端 /portal/trip/changeUrl

@RequestMapping("/changeUrl")
	public String changeUrl(Long id, String item, String value, HttpServletRequest request){
		request.setAttribute("id",id);
		request.setAttribute("item",item);
		request.setAttribute("value",value);
		//System.out.println(id);
		return "/tripController/tripURL"; 
	}	

 tripURL.jsp, 其中有个处理, 提交保存后, 关闭当前页面

<form action="/portal/trip/updateTrip" οnsubmit="window.opener=null;window.close();">
	 	<font size="2"  color="#004779"> Change URL To:</font><br/> 
	 	 <input type="hidden" name="id" id="id" value="${id }">
	 	 <input type="hidden" name="item" id="item" value="${item }">
	 	 <input type="text" name="value" id="value" value="${value }" style="color:#95a5a6; padding-left:5px;border-radius:5px;  width:700px; height:28px; vertical-align:middle;">
	 	 <input type="submit"   value="Save" style="color:#2c3e50; font-size:12px;font-weight:bold; border-radius:5px; vertical-align:middle;height:30px;  width:60px; "/>
    </form>

 controller端 /portal/trip/updateTrip

@RequestMapping("/updateTrip")
	public String updateTrip(Long id,String item,String value,HttpServletResponse response){
		//String result = "{\"result\":\"success\"}";
		try {
			URLDecoder.decode(value,"utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		tripService.updateById(id,item,value);
		
		JSONObject data = new JSONObject();
		try {
			data.put("result", "success");
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		
		
		PrintWriter out = null;
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8"); 
	    try {
	    	out=response.getWriter();
	        out.write(data.toString());
	        out.flush();
			out.close();	
			return null;
	    } catch (IOException e) {
	        e.printStackTrace();
	    }	   
		return "redirect:/trip/getAllTrip";
	}

 

转载于:https://www.cnblogs.com/wujixing/p/5869249.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个基于Spring Security框架与微信小程序登录态关联的完整实例: 1.首先,我们需要引入相关依赖,在pom.xml文件添加以下配置: ```xml <dependency> <groupId>com.github.binarywang</groupId> <artifactId>weixin-java-miniapp</artifactId> <version>3.9.0</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.4.6</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.4.6</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>5.4.6</version> </dependency> ``` 2.接着,我们需要在Spring Security的配置类添加相关配置,代码如下: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private WeixinMaService weixinMaService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login/**", "/error/**").permitAll() // 放行登录页和错误页 .antMatchers("/**").authenticated(); // 其他请求需要认证 http.formLogin() .loginPage("/login") // 自定义登录页 .loginProcessingUrl("/login") // 登录请求的URL .successHandler(this::loginSuccessHandler) // 登录成功处理器 .failureHandler(this::loginFailureHandler) // 登录失败处理器 .permitAll(); http.logout() .logoutUrl("/logout") // 退出登录请求的URL .logoutSuccessUrl("/") // 退出登录成功后跳转的URL .invalidateHttpSession(true) .deleteCookies("JSESSIONID"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(new WeixinMaAuthenticationProvider(weixinMaService)); } private void loginSuccessHandler(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { String openid = (String) authentication.getPrincipal(); HttpSession session = request.getSession(); session.setAttribute("openid", openid); response.sendRedirect("/"); } private void loginFailureHandler(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException { response.sendRedirect("/login?error"); } } ``` 3.在上面的配置类,我们使用了WeixinMaAuthenticationProvider来实现微信小程序登录认证,该认证器的实现如下: ```java public class WeixinMaAuthenticationProvider implements AuthenticationProvider { private final WeixinMaService weixinMaService; public WeixinMaAuthenticationProvider(WeixinMaService weixinMaService) { this.weixinMaService = weixinMaService; } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String code = (String) authentication.getCredentials(); WxMaJscode2SessionResult result; try { result = weixinMaService.getUserService().getSessionInfo(code); } catch (WxErrorException e) { throw new BadCredentialsException("获取用户信息失败", e); } String openid = result.getOpenid(); if (StringUtils.isBlank(openid)) { throw new BadCredentialsException("获取用户信息失败"); } return new UsernamePasswordAuthenticationToken(openid, null, Collections.emptyList()); } @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } } ``` 4.接下来,我们需要在登录页添加微信小程序登录的按钮,并实现相关的逻辑,代码如下: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <h1>登录</h1> <form method="post"> <input type="text" name="username" placeholder="请输入用户名"> <input type="password" name="password" placeholder="请输入密码"> <button type="submit">登录</button> </form> <button id="loginBtn">微信登录</button> <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> <script> wx.miniProgram.getEnv(function (res) { if (res.miniprogram) { document.getElementById('loginBtn').addEventListener('click', function () { wx.miniProgram.login({ success: function (res) { const code = res.code; const xhr = new XMLHttpRequest(); xhr.open('POST', '/login'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { window.location.href = '/'; } else { alert('微信登录失败'); } } }; xhr.send('username=' + code + '&password='); }, fail: function () { alert('微信登录失败'); } }); }); } else { document.getElementById('loginBtn').style.display = 'none'; } }); </script> </body> </html> ``` 5.最后,我们需要在Controller实现登录页的访问和退出登录的处理逻辑,代码如下: ```java @Controller public class LoginController { @GetMapping("/login") public String login() { return "login"; } @PostMapping("/login") public void doLogin(HttpServletRequest request, HttpServletResponse response, String username, String password) throws IOException { Authentication authentication = new UsernamePasswordAuthenticationToken(username, password); Authentication result = SecurityContextHolder.getContext().getAuthenticationManager().authenticate(authentication); SecurityContextHolder.getContext().setAuthentication(result); } @GetMapping("/logout") public String logout(HttpSession session) { session.invalidate(); return "redirect:/"; } } ``` 至此,基于Spring Security框架与微信小程序登录态关联的完整实例就结束了。其,我们使用了WeixinMaAuthenticationProvider来实现微信小程序登录认证,使用了WeixinMaService来调用微信auth.code2Session方法获取用户信息,使用了HttpSession来存储用户登录态信息。同时,我们在登录页添加了微信小程序登录的按钮,并实现了相关的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值