xmlHttpRequest GET/POST with Spring MVC - javascript

I am trying to find a workaround for using POST request, because I cannot use form, pass parameter and redirect to another page without displaying the parameter in the URL. I heard it is possible to do that via XHR GET request but I am not sure how. I have also tried it with POST.
Index.jsp (Peter is my example of POST via form, which works, but I cannot use. George is my example of GET. I can see that the function HttpGet is called and the responseText is the html of helloworld.jsp. Sam is my example of POST. I can see that the parameter is passed to the controller and added to mv but it stops short of redirecting to helloworld.jsp.)
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<!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=ISO-8859-1">
<title>Spring 4 MVC - HelloWorld Index Page</title>
<script type="text/javascript">
function httpGet(theUrl)
{
var xmlHttp = null;
alert('httpGet is called');
alert(theUrl);
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
alert(xmlHttp.responseText);
return xmlHttp.responseText;
}
function doPost() {
var url = "http://localhost:8080/HelloWorld/hello";
var params = "name=Sam";
alert('Entered Sam');
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);
}
</script>
</head>
<body>
<h2>Hello World</h2>
<form action="hello" id="test" method="POST" style="display:none;">
<input type="hidden" name="name" value="Eric" />
<input type="hidden" name="lastname" value="Peters" />
<button>Go to user 123</button>
</form>
<a href="javascript:;" onclick="javascript:
document.getElementById('test').submit()">Eric Peters</a><br/>
George
Sam
</body>
</html>
Controller:
package com.programcreek.helloworld.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class HelloWorldController {
String message = "Welcome to Spring MVC!";
#RequestMapping("/hello")
public ModelAndView showMessage(
#RequestParam(value = "name", required = true) String name,
#RequestParam(value = "lastname", required = false, defaultValue = "Doe") String lastname) {
System.out.println("in controller");
ModelAndView mv = new ModelAndView("helloworld");
mv.addObject("message", message);
mv.addObject("name", name);
mv.addObject("lastname", lastname);
return mv;
}
}
Helloworld.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Spring 4 MVC -HelloWorld</title>
</head>
<body>
<center>
<h2>Hello World</h2>
<h2>
${message} ${name} ${lastname}
</h2>
</center>
</body>
</html>
My questions are: 1) is it possible to use XHR get or post and not show the parameter in the URL? 2) which method (george or sam) is close, if any, and which files should I look at changing to make it redirect to helloworld.jsp (controller or index.jsp)? Thank you for your help.

Related

download a file on ajax success electron, jsp

i connected electron, jsp for login, sign up. electron is front side(html,js), jsp(jsp, java) is server side.
now i'm trying to download a file from server to electron.
(here i set a file (bullet01.png) for test.)
flow:
when user clicks a button(ajax get request)
server find file which from url parameter
success method gets result
myscript.js
function downloadClick() {
$.ajax({
url: 'http://localhost:8090/curriculum1.4/login_controller.jspx?cmd=downloadFile&bFile=bullet01.png',
type: 'get',
//dataType: 'json',
success: function(resp) {
console.log("success");
console.log(resp);
//window.open("C:\Users\CP\Desktop\테스트\core5.0.14\out\artifacts\unnamed\curriculum1.4\filedir\bullet01.png");
},
error: function(xhr, status, error) {
alert("err")
}
});
}
when i execute on jsp it downloads ok but from electron it doesn't download anything.
here is the code
public void downloadFile(ViewMeta view) throws IOException {
DataSet input = view.getInputDataSet();
HttpServletRequest request = view.getHttpServletRequest();
HttpServletResponse response = view.getHttpServletResponse();
String bFile = new String(input.getText("bFile").getBytes("UTF-8"), "ISO-8859-1");
String filePath = request.getServletContext().getRealPath("/curriculum1.4/filedir");
response.setHeader("Content-Disposition", "attachment;filename=\"" + bFile + "\";");
File file = new File(filePath + "/" + bFile);
FileInputStream fileInputStream = new FileInputStream(file);
ServletOutputStream servletOutputStream = response.getOutputStream();
byte b[] = new byte[1024];
int data = 0;
while ((data = (fileInputStream.read(b, 0, b.length))) != -1) {
servletOutputStream.write(b, 0, data);
}
servletOutputStream.flush();
servletOutputStream.close();
fileInputStream.close();
}
test.html in electron
<!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>
<script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>
<script language="JavaScript" type="text/javascript" src="js/jquery-3.2.1.js"></script>
<script src="js/myscript.js"></script>
<script>if (window.module) module = window.module;</script>
<body>
<h1 class="signUpTitle">test page</h1>
<!-- <input type="button" value="버튼" class="signUpButton" onclick="showOk()" > -->
<a onclick="downloadClick()">file</a>
</body>
</html>

I wanted to know how can I do get response and post response using ajax and jquery on jsp servlet web project

I wanted to know how can i do a get and post from a servlet and use jquery ajax i.e. in the jsp page to get response and post it .I have done doget .Also if possible I want to remove jstl from my jsp page.Please help me .And thanks in advance
Here is my controller class
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//get the data from database ie the model class
try {
List<Script> scriptitems=modelDBUtil.getScriptList();
request.setAttribute("scriptItems", scriptitems);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*String itemsfood[]={"biriyani","rice"};
request.setAttribute("itemsfood",itemsfood)*/;
//redirect to a different page
RequestDispatcher dispatcher =request.getRequestDispatcher("scriptviewer.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
}
Now my jsp page please help me here
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Menu</title>
</head>
<body>
<p>Script Items</p>
<c:forEach var="items" items="${scriptItems}">
${items.id} ${items.command}
</c:forEach>
<form action="appendfile.jsp" method="post">
<select name="department">
<c:forEach var="item" items="${scriptItems}">
<option value="${item.id}">${item.command}</option>
</c:forEach>
</select>
<button type="submit" id="idsubmit">Submit</button>
</form>
</body>
</html>
Here is how you can send json from JSP to Servlete please refer this code
with comments
$("#mForm").submit(function(e) { //your form ID chane it here
e.preventDefault();
var $form = $(this);
if (!$form.valid()) return false;
var url = "yourServeleteName";
$.ajax({
type: "POST", //the method you want invoke
url: "yourServeleteName", //Add here your servelete name
data: $("#mForm").serialize(), //your form ID remove default action from your form
success: function (data) //This is to handle if you want any response from Servlete
{
alert(data); //it will alret you message you send from servelete
//$("#mForm")[0].reset(); /if any form you can reset it option
}
});
});
}
Here is how you can remove jstl from my jsp page and can make it html.
you need to use these jquery cdn or you can use javascript directly.
Addtinaly you need to download Gson library to get response from servlet.
This code will work with get method.
This is how you can send your itemsfood to your html or jsp
Modify your doGet method as:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Script> scriptitems=modelDBUtil.getScriptList();
request.setAttribute("scriptItems", scriptitems);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
String itemsfood[]={"biriyani","rice"};
List<String> list = Arrays.asList(itemsfood);
String json = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
And HTML or jsp code for that is:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link
href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"
rel="stylesheet" type="text/css" />
<link
href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"
rel="stylesheet" type="text/css" />
<link rel='stylesheet' type='text/css'
href='http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css' />
<link rel="stylesheet"
href="https://jqueryvalidation.org/files/demo/site-demos.css">
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script
src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script
src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<script
src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(
function() {
$.get("appendfile or (add your serveletName here)", function(
responseJson) {
var $select = $("#item");
$select.find("option").remove();
$.each(responseJson, function(value, key) {
$("<option>").val(key).text(key).appendTo($select);
});
});
});
</script>
<title>Menu</title>
</head>
<body>
<form name=myform id="mForm">
<select name="item" required id="item">
<option value="Select">select</option>
</select>
<button type="submit" id="idsubmit">Submit</button>
</form>
</body>
</html>

Spring Controller not returning a html page after an Ajax get Request

So I have a "discount" html page, where a user is prompted to enter a promo code, by using an Ajax GET request from the buttons OnClick, I am able to transfer this promo code to my spring controller, where I manipulate the data appropriately.
For some reason I am unable to "return" a new page from this controller, I do not get any noticeable errors on my server side but on my client side I get this error:
I am not sure if this is related or relevant.
I was wondering is my logic behind this flawed or am I not implementing the correct syntax to return a new page after the AJAX call.
Note: The AJAX request works fine as I am able to get a system.out.print to the console at the bottom of the controller with the relevant info. that I passed.
Here is my html code:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"></meta>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></link>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
function myFunction(){
var code = document.getElementById("code").value;
var price = document.getElementById("price").value;
$.ajax({
type: "GET",
url: "/calculateDiscount",
data: {
code: code
}, // parameters
contentType: "application/json; charset=utf-8",
datatype: 'json'
//alert(status);
});
}
</script>
</head>
<body>
<div>
<center>
<h3>Total Price: $<text th:text="${totalPrice}" id="price"/> </h3>
<input type="text" name="firstname" id="code">
<button onclick="myFunction()">Calculate Discount</button>
<a style="color:blue" th:href="#{/welcome}">HomeScreen!</a>
<br />
<!-- <a style="color:blue" th:if="${myteam != null}" th:href="#{/leaveteam/{id}(id=${myteam?.id})}">Leave Team?!</a>
-->
</center>
</div>
</body>
</html>
Controller:
#RequestMapping(value="/calculateDiscount", method=RequestMethod.GET)
#ResponseBody
public String CalculateDiscount(Model model, #RequestParam("code") String code, RedirectAttributes redirectAttributes) {
///need to calculate price if codes correct then return page with card info then after proceed call purchasebooks controller!
System.out.println("Price: " + code );
Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
String email = loggedInUser.getName();
UserLogin user = uR.findByUserName(email);
int totalPrice = 0;
if (code.equals("Discount1010"))
{
Set<Book> books = user.getBooks();
for (Book b : books)
{
totalPrice = totalPrice + b.getPrice();
}
int discountPrice = (int) (totalPrice * .80);
model.addAttribute("totalPrice", totalPrice);
System.out.println("Price: " + discountPrice );
}
else {
Set<Book> books = user.getBooks();
for (Book b : books)
{
totalPrice = totalPrice + b.getPrice();
}
System.out.println("Price: " + totalPrice );
model.addAttribute("totalPrice", totalPrice);
}
return "payment";
}
The page I am trying to return:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"></meta>
<title>Insert title here</title>
</head>
<body>
<h3>Total Price: $<text th:text="${totalPrice}" id="price"/> </h3>
</body>
</html>
Any more info needed let me know.
K.
EDIT: In response to one of the answers below, I do have csrf disabled.
Here is my WebSecurityConfig class:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserLoginRepository userLoginRepository;
//http.authorizeRequests().antMatchers("/", "/home", "/registeruser").permitAll().antMatchers("/admin").hasRole("ADMIN")
#Autowired
DataSource dataSource;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/home", "/registeruser").permitAll().antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
.permitAll();
http.exceptionHandling().accessDeniedPage("/403");
http.csrf().disable();
//disable csrf to allow communication (we also dont need for this fyp as its not live)
}
#Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/fonts/**", "/images/**", "/css/**");
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select user_name,password,user_status from user_login where user_name=?")
.authoritiesByUsernameQuery("select user_name, password from user_login where user_name=?");
}
#Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
}
Update: #ResponseBody annotation was added to the controller method, problem still persists
I guess this is CSRF problem. You have Spring Security implemented (I can see
SecurityContexHolder class) and probably csrf enabled - this is default setting. If you want to disable it just use this
Java configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
XML:
<http>
<!-- ... -->
<csrf disabled="true"/>
</http>
But if you want to keep csrf enabled, you need to pass csrf token to ajax header. To do this, include csrf to meta tag:
<head>
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
And then include csrf to Ajax request:
var token = /*[[${_csrf.token}]]*/ '';
var header = /*[[${_csrf.headerName}]]*/ '';
$(document).ajaxSend(function(e,xhr,options) {
xhr.setRequestHeader(header, token);
});

How to Track visitor ip in html javascript [duplicate]

This question already has answers here:
How to get client's IP address using JavaScript? [closed]
(31 answers)
Closed 7 years ago.
How to make function to get visitor ip?
I try fixed using related post below
Tracking visitor IP/Clicks in PHP
How to get client's IP address using javascript only?
but cannot fixed yet..
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sample Tracking Visitor</title>
<script type="text/javascript">
function tracking_vistors(cid,url,curl,camp,type) {
var user_agent = getuseragent();
var ip = myIP(); // how to make this function track visitor ip
var publisher = "2000000001";
var data = "cid="+cid+"&curl="+curl+"&camp="+camp+"&type="+type+"&url="+url+"&ip="+ip+"&user_agent="+user_agent+"&publisher="+publisher;
$.ajax({
type: 'POST',
url: 'widget/clicktracker.php',
data: data
});
}
</script>
</head>
<body>
</body>
</html>
You can't find the IP from the javascript. You've to send the call to internet or any other service which can return your IP..
I'm adding one service url which will return your IP.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sample Tracking Visitor</title>
<script type="text/javascript" src="http://l2.io/ip.js?var=myip"></script>
<script type="text/javascript">
function tracking_vistors(cid,url,curl,camp,type) {
var user_agent = getuseragent();
var ip = myip; // how to make this function track visitor ip
var publisher = "2000000001";
var data = "cid="+cid+"&curl="+curl+"&camp="+camp+"&type="+type+"&url="+url+"&ip="+ip+"&user_agent="+user_agent+"&publisher="+publisher;
$.ajax({
type: 'POST',
url: 'widget/clicktracker.php',
data: data
});
}
</script>
</head>
<body>
</body>
</html>
This line will send the request to l2.io domain and return the ip in myip variable which I used in the code above.

Easy openid? .NET/JS?

I tried to understand dotnetopenid and failed. I dont know asp.net well enough and i want to do this problematically.
Is there a simple JS openid lib? or a simple/good openid example doing it for a C# desktop application?
Here is an example of open ID in c# .net . Not desktop but web.
http://www.nikhedonia.com/notebook/entry/openid-and-asp-net-mvc/
Here is my aspx file, i only added one line, the WebApplication1.openidtest.Authenticate line
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<% WebApplication1.openidtest.Authenticate("http://your_id.myopenid.com/"); %>
</div>
</form>
</body>
</html>
Here is the cs file. Note it works but doesnt handle things like errors and really is just for testing/breakpoints.
NOTE: If email is required and the user submit a persona that doesnt have an email there will be no email listed thus you must check and handle accordingly.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DotNetOpenAuth;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
namespace WebApplication1
{
static public class openidtest
{
static public void Authenticate(string openIdIdentifier)
{
var openId = new OpenIdRelyingParty();
var response = openId.GetResponse();
if (UserNeedsToLogin(response))
{
var request = openId.CreateRequest(openIdIdentifier);
request.AddExtension(new ClaimsRequest { Email = DemandLevel.Require });
request.RedirectingResponse.Send();
return;
}
HandleAuthenticationResponse(response);
}
static bool UserNeedsToLogin(IAuthenticationResponse response)
{
return response == null;
}
static void HandleAuthenticationResponse(IAuthenticationResponse response)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
{
var claims = response.GetExtension<ClaimsResponse>();
if (claims != null)
{
var s = claims.Email;
}
return;
//return HandleSuccessfulLogin(response);
}
case AuthenticationStatus.Canceled:
//_context.ErrorMessage = "Login was cancelled at the provider.";
break;
case AuthenticationStatus.Failed:
//_context.ErrorMessage = "Login failed at the provider.";
break;
case AuthenticationStatus.SetupRequired:
//_context.ErrorMessage = "The provider requires setup.";
break;
default:
//_context.ErrorMessage = "Login failed.";
break;
}
}
}
}

Categories

Resources