I want to get first name by html template with i show it by method Get.
I did controller and it doesnt't see name which I give by the html template.
This controller should get this paramert from template. I have exeption on my browser There was an unexpected error (type=Bad Request, status=400).
Required String parameter 'first_name' is not present
Please can u tell me where i did mistake ?
this is my service:
public class ReadFamily {
#Autowired
ChildRespository childRespository;
private RestTemplate restTemplate;
public ReadFamily(){
restTemplate = new RestTemplate();
}
public ChildForm findChild(String firstName){
return restTemplate.getForObject("http://localhost:8080/findP/"+firstName,ChildForm.class);
}
public String firstNameFormat(ChildForm childForm) {
return childForm.getFirstName();
}
public String secondNameFormat(ChildForm childForm) {
return childForm.getSecondName();
}
public String sexFormat(ChildForm childForm) {
return childForm.getSex();
}
public String peselFormat(ChildForm childForm) {
return childForm.getPesel();
}
}
controller:
#Autowired
ReadFamily readFamily;
#GetMapping("findP")
public String findPerson(Model model){
model.addAttribute("childForm",new ChildForm());
return"Find";
}
#RequestMapping (value = "findPersonResult", method = RequestMethod.POST)
public String findPerson(Model model,
#RequestParam ("first_name") String firstName) {
System.out.println(firstName);
ChildForm childInfo = readFamily.findChild(firstName);
model.addAttribute("firstName",readFamily.firstNameFormat(childInfo));
model.addAttribute("secondName",readFamily.secondNameFormat(childInfo));
model.addAttribute("pesel",readFamily.peselFormat(childInfo));
model.addAttribute("sex",readFamily.sexFormat(childInfo));
return "Find";
}
and template:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Find person</title>
</head>
<body>
<form th:object="${childForm}" action="/findPersonResult" method="post">
<input type="text" th:field="*{firstName}" placeholder="firstName"> <br/>
<input type="submit" value="Find">
</form>
<h2>Persons</h2>
<form action="/findP" method="get">
<div id="show" >
<h1 th:text="${firstName} "></h1>
<h1 th:text="${secondName} "></h1>
<h1 th:text="${pesel} "></h1>
<h1 th:text="${sex} "></h1>
</div>
</form>
</body>
</html>
Change
#RequestParam ("first_name") String firstName
to
#RequestParam ("firstName") String firstName
Related
I simply forgot how to work with freemarker. I tried to create input, after submission which value of it gonna be displayed on the other page. It looks awful but here is my code :
#GetMapping("/form1")
public String getForm(){
return "form1";
}
#GetMapping("/name11/{Name}")
public String formPos(#PathVariable("Name") String name, Model model){
model.addAttribute("name", name);
return "name11";
}
html named form1
<form action="/name11" method="post">
<input name="Name" >
<button>put</button>
</form>
html named name11
<body>
<h1>${name}</h1>
</body>
#GetMapping("/form1")
public String getForm() {
return "form1";
}
#PostMapping("/name11")
public String formPos(#RequestParam("Name") String name, Model model) {
model.addAttribute("name", name);
return "name11";
}
form1 in static directory as form1.html
name11 in template directory as name11.ftlh
I'm new using Apache Wicket. I'm creating a panel to add articles on a web site. My panel to edit an article is formed with a TabbedPanel: the first tab is to edit and the second tab is to preview the article.
If after I entered some text in the editor (textarea), I switch to the preview and go back to the editor, le textarea is empty.
Here a part of the code for the panel with the TabbedPanel:
public AddArticlePanel(String id, ArticleEdit articleEdit) {
super(id);
final List<AbstractTab> tabList = new ArrayList<>();
tabList.add(new AbstractTab(new Model<String>("Editor")) {
#Override
public WebMarkupContainer getPanel(String panelId) {
return new ArticleEditorPanel(panelId, articleEdit);
}
});
tabList.add(new AbstractTab(new Model<String>("Preview")) {
#Override
public WebMarkupContainer getPanel(String panelId) {
return new ArticlePreviewPanel(panelId, articleEdit);
}
});
tabs = new TabbedPanel<AbstractTab>("tabs", tabList);
final SubmitLink submitButton = new SubmitLink("submit") {
#Override
public void onSubmit() {
// TODO
}
};
addArticleForm = new Form<ArticleEdit>("add-article-form", new Model<ArticleEdit>(articleEdit));
addArticleForm.add(tabs);
addArticleForm.add(submitButton);
add(addArticleForm);
}
Here the HTML for the editor panel:
<wicket:panel>
<div wicket:id="feedback"></div>
<div class="fields">
<label for="title">Title</label>
<input type="text" name="title" wicket:id="title">
</div>
<div class="fields">
<label for="text">Text</label>
<textarea class="notab" name="text" wicket:id="text"></textarea>
</div>
<div class="fields">
<label for="keywords">Keywords</label>
<input type="text" name="keywords" wicket:id="keywords">
</div>
</wicket:panel>
The code for this editor panel:
public ArticleEditorPanel(String id, ArticleEdit articleEdit) {
super(id);
final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
title = new TextField<String>("title", new PropertyModel<String>(articleEdit, "title"));
title.setRequired(true);
text = new TextArea<String>("text", new PropertyModel<String>(articleEdit, "text"));
text.setRequired(true);
keywords = new TextField<String>("keywords", new PropertyModel<String>(articleEdit, "keywords"));
keywords.setRequired(true);
add(title);
add(text);
add(keywords);
add(feedbackPanel);
}
Finally, the source code of the ArticleEdit class:
public class ArticleEdit implements Serializable {
private String title;
private String text;
private String keywords;
private String preview;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public String getPreview() {
return preview;
}
public void setPreview(String preview) {
this.preview = preview;
}
}
Why it doesn't work out of the box ? Where is my mistake ?
Thank you for your help.
You do not save the state from your EDIT tab before navigating to the PREVIEW tab.
By clicking the "Preview" link the browser will make a new request to the server and Wicket will re-render the whole page, so any data entered in the form fields will be lost.
You can easily save the data by adding AjaxFormComponentUpdatingBehavior to the form fields. For example for the title field:
title = new TextField<String>("title", new PropertyModel<String>(articleEdit, "title"));
title.setRequired(true);
title.add(new AjaxFormComponentUpdatingBehavior("change") {
#Override public void onUpdate(AjaxRequestTarget target) {}
#Override public void onError(AjaxRequestTarget target) {
target.add(feedbackPanel);
}
});
I currently have an ASP.NET Core 2.0 Web Application (built in VS 2017 from the default web application template). I have a RazorPage with a dropdown built in that I would like to populate via a SQL Query. I've used Entity Framework Core to build a model of my database as follows:
public partial class INVOPEContext : DbContext
{
public virtual DbSet<PmeFundData> PmeFundData { get; set; }
modelBuilder.HasAnnotation"Relational:DefaultSchema", "Server\\User");
modelBuilder.Entity<PmeFundData>(entity =>
{
entity.ToTable("PME_FUND_DATA", "dbo");
entity.Property(e => e.Firm).HasMaxLength(255);
});
}
public partial class PmeFundData
{
public string Firm { get; set; }
}
I've updated the RazorPage PageModel (pmepe.cshtml.cs) to include the DBContext and Query:
public class pmepeModel : PageModel
{
private readonly INVOPEContext _db;
public pmepeModel(INVOPEContext db)
{
_db = db;
}
public IActionResult dropdowns()
{
List<PmeFundData> firmList = new List<PmeFundData>();
firmList = (from Firm in _db.PmeFundData
select Firm).Distinct().ToList();
firmList.Insert(0, new PmeFundData {Firm = "All Firms" });
ViewBag.ListofFirms = firmList;
return View();
}
}
Finally, the view with the dropdown (pmepe.cshtml) is as follows:
#page
#model pmepeModel
#{
ViewData["Title"] = "pmepe";
}
<select asp-for="dropdowns"
id="firm"
class="dropdown"
asp-items= "#(new SelectList(ViewBag.ListofFirms, "Firm"))">
</select>
I am getting errors that neither ViewBag nor View exist in the current context in the PageModel (no errors in the view - Intellisense picks it up). Every example I've found on the web is for MVC rather than RazorPages. The solution commonly provided for MVC is imbedding the query in a Controller and adjusting the MVC version in the web.config file. But the RazorPages template doesn't have Controllers and I can't find a web.config file - so I haven't been able to get it to work in my app. Any help you can provide would be most appreciated.
There are multiple issues in your code.
PmeFundData should have Id property, otherwise, you will receive error while running update-database command.
public partial class PmeFundData
{
public int Id { get; set; }
public string Firm { get; set; }
}
ViewBag is not supported in RazorPage, you could trace this issue from Add ViewBag to PageModel #6754, you could try ViewData or PageModel Property to bind the object.
Here is a simple code for ViewData.
public class PmepeModelModel : PageModel
{
private readonly CoreRazor2_1.Data.ApplicationDbContext _context;
public PmepeModelModel(CoreRazor2_1.Data.ApplicationDbContext context)
{
_context = context;
}
public IActionResult OnGet()
{
return Page();
}
[BindProperty]
public int SelectedFirm { get; set; }
[ViewData]
public IList<PmeFundData> ListofFirms { get {
return Dropdowns();
}
}
public IList<PmeFundData> Dropdowns()
{
List<PmeFundData> firmList = new List<PmeFundData>();
firmList = new List<PmeFundData> {
new PmeFundData{ Id = 1, Firm = "F1"},
new PmeFundData{ Id = 2, Firm = "F3"},
new PmeFundData{ Id = 3, Firm = "F2"}
};
//firmList = (from Firm in _context.PmeFundData
// select Firm).Distinct().ToList();
firmList.Insert(0, new PmeFundData { Firm = "All Firms" });
return firmList;
//ViewData["ListofFirms"] = firmList;
}
public async Task<IActionResult> OnPostAsync()
{
var value = SelectedFirm;
if (!ModelState.IsValid)
{
return Page();
}
_context.PmeFundData.Add(PmeFundData);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
View
#page
#model CoreRazor2_1.Pages.PmepeModelModel
#{
ViewData["Title"] = "PmepeModel";
}
<h2>PmepeModel</h2>
<h4>PmeFundData</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<select asp-for="#Model.SelectedFirm"
class="dropdown"
asp-items="#(new SelectList((IEnumerable<PmeFundData>)#ViewData["ListofFirms"], "Id" ,"Firm"))">
</select>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
</div>
<div>
<a asp-page="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
You may also learn Razor Page from Introduction to Razor Pages in ASP.NET Core
I am using a simple form where a user can input some JSON.
I add that input to the body of the request.
When I retrieve the value from the body, it is not formatted/encoded as JSON.
Instead I get something like json=%7B%22vrt%22%3A%7B ...
How/where do I specify that the value in the body must be JSON in such way that my controller can parse it using GSON?
Thanks in advance.
Regards
The controller
#PostMapping(value = "/api/sendMessage")
public ModelAndView sendIoTMessage(#RequestBody String json) {
VehicleMessage vehicleMessage = new Gson().fromJson(json, VehicleMessage.class);
MessageProcessor.postVehicleMessage(vehicleMessage);
ModelAndView mav = new ModelAndView();
mav.setViewName("iot");
return mav;
}
The form
<form id="sendMessage" th:action="#{/api/sendMessage}" method="post">
<div class="form-group">
<input class="form-control" th:value="*{json}" id="json" name="json">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
By default, Spring uses Jackson convertor for APPLICATION JSON, if you want to use GSON convertors, then you need to add GSONConvertor.
I personly perfer Option 1
Different ways to add GSONConvertor:
Using JavaConfig
#Configuration #EnableWebMvc
public class Application extends WebMvcConfigurerAdapter {
#Override
public void configureMessageConverters(List<HttpMessageConverter < ? >> converters) {
GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
converters.add(gsonHttpMessageConverter);
}
}
Using customize converters
#Configuration
public class CustomConfiguration {
#Bean
public HttpMessageConverters customConverters() {
Collection<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
messageConverters.add(gsonHttpMessageConverter);
return new HttpMessageConverters(true, messageConverters);
}
}
Using Auto-configuration ..follow this link
Why not let Spring (de)serialize JSON for you? This functionality should work out of the box without any custom configuration.
#PostMapping(value = "/api/sendMessage", consumes="application/json")
public ModelAndView sendIoTMessage(#RequestBody VehicleMessage vehicleMessage) {
MessageProcessor.postVehicleMessage(vehicleMessage);
ModelAndView mav = new ModelAndView();
mav.setViewName("iot");
return mav;
}
This question already has an answer here:
Authentication filter and servlet for login
(1 answer)
Closed 7 years ago.
I have created a simple login page in which user will give an username and password. After clicking on submit button it will show welcome user. But it is not giving any result
This is my index page
This is my index login page :
<%# 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">
<link rel="stylesheet" type="text/css" href="style.css"/>
<title>Login</title>
</head>
<body>
<%
String error_msg = "";
Object error = request.getAttribute("error");
if (error != null) error_msg = error.toString();
%>
<div id="Container">
<div id="Header">
<h1>Online File Management System</h1>
</div>
Home
<div id="Content">
<div id="Login">
<form action="login">
<table align = "center" bgcolor=#66CCFF>
<tr><td align = "left">Username: </td>
<td rowspan="7" valign="middle">
<font color="red"> <%= error_msg %> </font>
<p>You can also Login using Google</p>
<p class="Google"><input name="Submit" type="Submit" value="Login with Google Account"></p>
</td>
</tr>
<tr>
<td><input name="username" type="text" size="30"></td>
<td></td>
</tr>
<tr><td align = "left">Password:</td></tr>
<tr><td><input name="password" type="password" size="30"></td></tr>
<tr><td align = "left">Forgot your password?</td></tr>
<tr><td align = "left">Remember me <input type="checkbox" name="checkbox" value="checkbox"></td></tr>
<tr><td align = "left"><input type="Submit" value="LOGIN"></td></tr>
</table>
</form>
<hr>
</div>
</div>
<div id="Footer">
Copyright © 2014 Office of the Vice Chancellor.
</div>
</div>
</body>
</html>
This is my Database conectivity page :
package org.form.login;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.catalina.connector.Request;
public class database {
#SuppressWarnings("null")
public String validateUserLogin (String username, String password) throws SQLException{
Connection connection = null;
ResultSet resultset = null;
Statement statement = null;
String fullname = "";
String DRIVER = "com.mysql.jdbc.Driver";
String URL = "jdbc:mysql://localhost:3306/onfms";
String USER = "root";
String PASS = "";
String QUERY = "SELECT * FROM tblUser WHERE fldUser_Name = '"+
username+"' AND fldPassword = '"+password+"' ";
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL,USER,PASS);
resultset = statement.executeQuery(QUERY);
} catch (Exception e){
e.printStackTrace();
} finally {
if (resultset != null)
resultset.close();
if (statement != null)
statement.close();
if (connection != null)
connection.close();
}
}
}
This is my login servlet page:
package org.form.login;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.form.login.database;
/**
* Servlet implementation class login
*/
#WebServlet("/login")
public class login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public login() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String url = "/main.jsp";
String user = request.getParameter("username");
String pass = request.getParameter("password");
if (user == null || user.length() == 0 ||pass == null || pass.length() == 0) {
url = "/index.jsp";
request.setAttribute("error", "Username & Password must not be empty.");
}else{
try {
String fullname = new database().validateUserLogin(user, pass);
request.setAttribute("fullname", fullname);
if (fullname != null || fullname.length() != 0){
request.setAttribute("sucess", "Sucessfull Connection");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
This is my final Page where I display my result
<%# 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>Desk Board</title>
</head>
<body>
Hello
<%
String sucess_message ="";
Object sucess = request.getAttribute("sucess");
if (sucess != null ) sucess_message = sucess.toString();
%>
<%= sucess_message %>
</body>
</html>
use this code it is working
// index.jsp or login.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>Insert title here</title>
</head>
<body>
<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>
</body>
</html>
// authentication servlet class
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class auth extends HttpServlet {
private static final long serialVersionUID = 1L;
public auth() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String sql = "select * from reg where username='" + username + "'";
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
"root", "");
Statement s = conn.createStatement();
java.sql.ResultSet rs = s.executeQuery(sql);
String un = null;
String pw = null;
String name = null;
/* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */
PrintWriter prwr1 = response.getWriter();
if(!rs.isBeforeFirst()){
prwr1.write("<h1> No Such User in Database<h1>");
} else {
/* Conditions to be executed after at least one row is returned by query execution */
while (rs.next()) {
un = rs.getString("username");
pw = rs.getString("password");
name = rs.getString("name");
}
PrintWriter pww = response.getWriter();
if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
// use this or create request dispatcher
response.setContentType("text/html");
pww.write("<h1>Welcome, " + name + "</h1>");
} else {
pww.write("wrong username or password\n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
You Can simply Use One Jsp Page To accomplish the task.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String username=request.getParameter("user_name");
String password=request.getParameter("password");
String role=request.getParameter("role");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
Statement st=con.createStatement();
String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
session.setAttribute( "user_name",rs.getString(2));
session.setMaxInactiveInterval(3000);
response.sendRedirect("homepage.jsp");
}
%>
<%}
catch(Exception e)
{
out.println(e);
}
%>
</body>
I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.