This question already has answers here:
javax.servlet.ServletException: javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in <forEach>
(3 answers)
Closed 6 years ago.
MainServ.java
package servs.com;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
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 serv.com.Users;
#WebServlet(name="mainServ",urlPatterns={"/mainServ"})
public class haha extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// JDBC driver name and database URL
final String DB_URL="jdbc:mysql://localhost/test";
// Database credentials
final String USER = "root";
final String PASS = "root";
Connection conn = null;
Statement stmt = null;
ArrayList<Users> usersArr = new ArrayList<Users>();
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n");
try{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
Users u = new Users();
u.setAge(age);
u.setId(id);
u.setFirst(first);
u.setLast(last);
usersArr.add(u);
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
} //end try
request.setAttribute("users", usersArr);
request.getRequestDispatcher("NewFile.jsp").forward(request,response);
System.out.println(usersArr.size());
}
}
NewFile.JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>
<c:forEach items="${users}" var="rowss">
<c:forEach items="${rowss}" var="item">
<c:out value="${item}"/>
</c:forEach>
</c:forEach>
<!--
<c:forEach var="user" items="${users}">
<c:out value="${users.first}"/>
<c:out value="${users.last}"/>
<c:out value="${users.ageIp}"/>
<c:out value="${users.id}"/>
</c:forEach>
-->
</body>
</html>
Users.java
package servs.com;
final public class Users {
private int id;
private int age;
private String first;
private String last;
public void setId(int i){
this.id=i;
}
public void setAge(int i){
this.age=i;
}
public void setFirst(String i){
this.first=i;
}
public void setLast(String i){
this.last=i;
}
}
When I am trying to print in NewFile.jsp I am getting following error.
javax.servlet.jsp.JspTagException: Don't know how to iterate over
supplied "items" in <forEach>
I don't know the error is in printing or I am doing something wrong while putting the objects into the Arraylist (userArr). I am getting the data successfully out of the database as I did print it first.
Could you please let me know what I can modify in order to print the data. I would be open If there is any different approach for the same.
After adding Getter methods in class Users the issue was resolved. But I still Havea doubt I never used getter methods anywhere. How come getter methods played any role.??
public String getFirst(){
return this.first;
}
public String getLast(){
return this.last;
}
public int getId(){
return this.id;
}
public int getAge(){
return this.age;
}
This is what I appended at the end of Users.java
Related
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 2 years ago.
Exact error: The requested resource [/Register/] is not available. Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
I am using tomcat and Eclipse.
Here is the code:
RegisterDao.java
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class RegisterDao {
private String dbUrl = "jdbc:mysql://localhost:3306/explorecalifornia";
private String dbUname = "dbuser";
private String dbPassword = "dbpassword";
private String dbDriver = "com.mysql.cj.jdbc.Driver";
public void loadDriver(String dbDriver)
{
try {
Class.forName(dbDriver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Connection getConnection()
{
Connection con = null;
try {
con = DriverManager.getConnection(dbUrl, dbUname, dbPassword);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public String insert(Member member)
{
loadDriver(dbDriver);
Connection con = getConnection();
String result = "Data entered successfully";
String sql = "insert into member values(?,?,?,?)";
PreparedStatement ps;
try {
ps = con.prepareStatement(sql);
ps.setString(1, member.getUname());
ps.setString(2, member.getPassword());
ps.setString(3, member.getEmail());
ps.setString(4, member.getPhone());
ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = "Data not entered";
}
return result;
}
}
Register.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Register")
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Register() {
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
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uname = request.getParameter("uname");
String password = request.getParameter("password");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
Member member = new Member(uname, password, email, phone);
RegisterDao rDao = new RegisterDao();
String result = rDao.insert(member);
response.getWriter().print(result);
}
}
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Registration</display-name>
<welcome-file-list>
<welcome-file>memberRegistration.jsp</welcome-file>
</welcome-file-list>
</web-app>
and memberRegistration.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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 action="memberRegistration" method="post">
<table>
<tr><td>User Name: </td><td><input type="text" name="uname"></td></tr>
<tr><td>Password: </td><td><input type="password" name="password"></td></tr>
<tr><td>Email: </td><td><input type="text" name="email"></td></tr>
<tr><td>phone: </td><td><input type="text" name="phone"></td></tr>
<tr><td></td><td><input type="submit" value="register"></td></tr>
</table>
</form>
</body>
</html>
Need to place the servlet class in a java package. You should always put publicly reusable Java classes in a package, otherwise they are invisible to classes which are in a package, such as the server itself.
I'm new to Spring Framework. I'm trying to get #Valid to work. Data Binding is happening properly but not the validation. hasErrors() is always returning False in the Controller class. Please see below code.
I'm utilizing Spring 4.1.3 and Hibernate validator 6.0.16.
Context xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<context:property-placeholder location="classpath:/config.properties"/>
<context:annotation-config />
<mvc:annotation-driven />
<context:component-scan base-package="com.personal, com.documentum" />
</beans>
Controller:
package com.personal.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.personal.search.model.SearchForm;
import com.personal.search.service.SearchService;
#Controller
public class SearchController {
private SearchService service;
#Autowired
public SearchController(SearchService service) {
this.service = service;
}
#RequestMapping(value="/", method=RequestMethod.GET)
public String searchHome(Model model) {
model.addAttribute(new SearchForm());
return "search/search";
}
#RequestMapping(value="/", method=RequestMethod.POST)
public String searchResults(#Valid SearchForm searchForm, BindingResult errors, Model model) {
if (!errors.hasErrors()) {
System.out.println(searchForm.getObjectName());
model.addAttribute(service.getResults(searchForm));
}
return "search/search";
}
}
View:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<%# page session="false" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<sf:form method="POST" commandName="searchForm">
<sf:errors path="*" />
<label>Enter Object Name:</label>
<sf:input path="objectName"/><sf:errors path="objectName" /><br>
<button type="submit" value="Submit">Submit</button>
</sf:form>
<h3>For your search term "${searchForm.objectName}" below are the results: </h3>
<c:forEach items="${searchResultList}" var="searchResult" >
<li>
<div>
<span>
(<c:out value="${searchResult.objectName}" />,
<c:out value="${searchResult.title}" />)</span>
</div>
</li>
</c:forEach>
</body>
</html>
Model:
SearchForm Model:
package com.personal.search.model;
import javax.validation.constraints.NotBlank;
public class SearchForm {
#NotBlank
private String objectName;
public SearchForm() {
}
public SearchForm(String objectName) {
this.objectName = objectName;
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
}
SearchResult Model:
package com.personal.search.model;
public class SearchResult {
private String objectName;
private String title;
public SearchResult() {
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String name) {
this.objectName = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Service:
package com.personal.search.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.personal.search.dao.SearchDAO;
import com.personal.search.model.SearchForm;
import com.personal.search.model.SearchResult;
#Service
public class SearchService implements ISearchService {
private SearchDAO dao;
public SearchService() {
}
#Autowired
public SearchService(SearchDAO dao) {
this.dao = dao;
}
#Override
public List<SearchResult> getResults(SearchForm searchform) {
return dao.getSearchObjects(searchform);
}
}
DAO:
package com.personal.search.dao;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import com.documentum.com.DfClientX;
import com.documentum.fc.client.DfServiceException;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfCollection;
import com.documentum.fc.client.IDfQuery;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.IDfLoginInfo;
import com.personal.search.model.SearchForm;
import com.personal.search.model.SearchResult;
#Repository
public class SearchDAO {
private String repository;
private String userName;
private String password;
private IDfSessionManager sessionMgr = null;
public SearchDAO() {
}
#Autowired
public SearchDAO(
#Value("${docbase.repository}") String repository,
#Value("${docbase.user}") String userName,
#Value("${docbase.password}") String password)
{
this.repository = repository;
this.userName = userName;
this.password = password;
System.out.println(repository + " " + userName + " " + password);
}
/**
* Creates a IDfSessionManager
*/
private IDfSessionManager getSessionManager()
{
// create a client object using a factory method in DfClientX
DfClientX clientx = new DfClientX();
IDfClient client;
IDfSessionManager sessionMgr = null;
try {
client = clientx.getLocalClient();
// call a factory method to create the session manager
sessionMgr = client.newSessionManager();
addIdentity(clientx, sessionMgr);
} catch (DfException e) {
e.printStackTrace();
}
return sessionMgr;
}
private void addIdentity(DfClientX clientx, IDfSessionManager sessionMgr)
{
// create an IDfLoginInfo object and set its fields
IDfLoginInfo loginInfo = clientx.getLoginInfo();
loginInfo.setUser(userName);
loginInfo.setPassword(password);
if (sessionMgr != null) {
if (sessionMgr.hasIdentity(repository))
{
sessionMgr.clearIdentity(repository);
}
}
try {
sessionMgr.setIdentity(repository, loginInfo);
} catch (DfServiceException e) {
e.printStackTrace();
}
}
public IDfSession getDBSession() {
IDfSession sess = null;
// Get a session using a factory method of session manager.
try {
sess = sessionMgr.getSession(repository);
} catch (DfServiceException e) {
System.out.println(e.getStackTraceAsString());
}
return sess;
}
public void releaseDBSession(IDfSession sess) {
sessionMgr.release(sess);
}
public List<SearchResult> getSearchObjects(SearchForm searchform) {
List<SearchResult> lst = new ArrayList<SearchResult>();
this.sessionMgr = getSessionManager();
IDfSession sess = null;
try
{
sess = getDBSession();
if (sess != null) {
IDfQuery query = new DfClientX().getQuery();
String dqlStr = "select object_name, title from dm_sysobject where object_name like '%" + searchform.getObjectName() + "%'";
System.out.println(dqlStr);
query.setDQL(dqlStr);
IDfCollection co = query.execute(sess, IDfQuery.DF_READ_QUERY);
while (co.next()) {
SearchResult searchresult = new SearchResult();
searchresult.setObjectName(co.getString("object_name"));
searchresult.setTitle(co.getString("title"));
lst.add(searchresult);
}
if (co != null)
co.close();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (sess != null)
releaseDBSession(sess);
}
return lst;
}
}
I expect the hasErrors() output to be True.
This could be because you have defined the validation as,
#Null
#Size(min=1, max=30)
private String objectName;
Check if when you submit the request to controller the objectName has NULL value or empty string?
For String you must use #NotBlank and not #Null
I am trying to get a simple Jetty/SpringMVC example going and have hit on a problem that I cannot resolve.
The classes I am using look like this:
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class JettyTest {
public static void main(String[] args) throws Exception {
AnnotationConfigWebApplicationContext spring = new AnnotationConfigWebApplicationContext();
spring.scan("controllers");
DispatcherServlet servlet = new DispatcherServlet(spring);
ServletHolder servletHolder = new ServletHolder(servlet);
servletHolder.setName("spring");
ServletContextHandler springHandler = new ServletContextHandler(
ServletContextHandler.NO_SESSIONS);
springHandler.setContextPath("/");
springHandler.addServlet(servletHolder, "/*");
springHandler.setErrorHandler(null);
springHandler.addEventListener(new ContextLoaderListener(spring));
Server server = new Server(5050);
server.setHandler(springHandler);
server.setStopAtShutdown(true);
server.start();
server.join();
}
}
A controller:
package controllers;
import model.MessageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class TestController {
#RequestMapping(value = "/message", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<String> testPost(#RequestBody MessageRequest messageRequest) {
return new ResponseEntity<>("POST Response: " + messageRequest.getMessage(), null,
HttpStatus.OK);
}
}
And finally the MessageRequest class:
package model;
public class MessageRequest {
private String message;
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
However, when I start this application and send a POST request with the following request body:
{
"message" : "test"
}
I get the following response:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 415 Unsupported Media Type</title>
</head>
<body>
<h2>HTTP ERROR 415</h2>
<p>Problem accessing /message. Reason:
<pre> Unsupported Media Type</pre>
</p>
<hr>
Powered by Jetty:// 9.4.8.v20171121
<hr/>
</body>
</html>
What am I doing wrong? I have gotten a similar example to work with Springboot, but here I am somehow lost.
Try adding
produces = "application/json"
as well.
I am trying to learn Hibernate Search.
I have an existing SpringMVC+Hibernate CRUD project with Form Validations.
The project works perfectly, but after I add Hibernate Search functionality,
The following error is shown
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.config.SpringConfig: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
My code :
/////////////////////////////SpringConfig.java///////////////////////////
package com.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.model.Person;
import com.service.PersonService;
#Configuration
#EnableWebMvc
#ComponentScan({ "com.*" })
#EnableTransactionManagement
public class SpringConfig extends WebMvcConfigurerAdapter {
#Autowired
private Environment environment;
#Autowired
private PersonService ps;
#Bean #Autowired
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setAnnotatedClasses(Person.class);
sessionFactory.setPackagesToScan(new String[] { "com.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean #Autowired
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/myschema");
dataSource.setUsername("root");
dataSource.setPassword("admin123");
return dataSource;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
registry.addResourceHandler("/resources/**").addResourceLocations(
"/resources/*");
}
#Bean #Autowired
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver res = new InternalResourceViewResolver();
res.setPrefix("/WEB-INF/view/");
res.setSuffix(".jsp");
return res;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect",
"org.hibernate.dialect.MySQL5Dialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.search.default.directory_provider", "org.hibernate.search.store.impl.FSDirectoryProvider");
properties.put("hibernate.search.default.indexBase", "H:/MyWorkspace/MainAssignment3/indexes");
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
//////////////////////////////Controller/////////////////////////////
package com.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
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.servlet.ModelAndView;
import com.model.Person;
import com.service.PersonService;
#Controller
public class MainController {
#Autowired
private PersonService ps;
#RequestMapping("/")
public ModelAndView listPersons(ModelAndView model) throws Exception {
ps.indexPersons();
List<Person> listper = ps.list();
model.addObject("personsList", listper);
model.setViewName("index");
return model;
}
#RequestMapping(value = "/newPerson", method = RequestMethod.GET)
public ModelAndView newPerson(ModelAndView model) throws IOException {
#SuppressWarnings("unused")
Person p = new Person();
model.addObject("person", new Person());
model.setViewName("AddPerson");
return new ModelAndView("AddPerson", "person", new Person());
}
#RequestMapping(value="/save")
public String save(/*#ModelAttribute*/ #Valid Person p, BindingResult result) {
if(result.hasErrors())
{
return "AddPerson";
}
else
{
ps.save(p);
return "redirect:http://localhost:8080/MainAssignment3/";
}
}
#RequestMapping("/removePerson")
public String remove(HttpServletRequest req) {
int id = Integer.parseInt(req.getParameter("id"));
ps.removePerson(id);
return "redirect:http://localhost:8080/MainAssignment3/";
}
#RequestMapping("/update")
public String update(/*#ModelAttribute*/ #Valid Person p1,BindingResult result,Model p) {
System.out.println(p1.getName());
int id=p1.getId();
// ps.getPersonById(p.getId());
p.addAttribute("p1", p1);
p.addAttribute("id", id);
p.addAttribute("name", p1.getName());
p.addAttribute("gender", p1.getGender());
p.addAttribute("address", p1.getAddress());
p.addAttribute("salary", p1.getSalary());
if(result.hasErrors())
{
return "redirect:http://localhost:8080/MainAssignment3/updatePerson";
}
else{
ps.save(p1);
return "redirect:http://localhost:8080/MainAssignment3/";
}
}
#RequestMapping("/updatePerson")
public ModelAndView updatePerson(HttpServletRequest req, ModelMap p1,#ModelAttribute Person p) {
p1.addAttribute("person",new Person());
int id = Integer.parseInt(req.getParameter("id"));
String name = req.getParameter("name");
String address = req.getParameter("address");
String gender = req.getParameter("gender");
String salary = req.getParameter("salary");
p1.addAttribute("id", id);
p1.addAttribute("name", name);
p1.addAttribute("gender", gender);
p1.addAttribute("address", address);
p1.addAttribute("salary", salary);
p1.addAttribute("p1",new Person());
return new ModelAndView("updatePerson", "person", new Person());
}
#RequestMapping(value = "/search", method = RequestMethod.GET)
public ModelAndView searchPage()
{
ModelAndView mav = new ModelAndView("search");
return mav;
}
#RequestMapping(value = "/doSearch", method = RequestMethod.POST)
public ModelAndView search(#RequestParam("searchText")String searchText) throws Exception
{
List<Person> allFound = ps.searchForPerson(searchText);
List<Person> bookModels = new ArrayList<Person>();
for (Person p : allFound)
{
Person pm = new Person();
pm.setName(p.getName());
pm.setAddress(p.getAddress());
pm.setGender(p.getGender());
pm.setSalary(p.getSalary());
bookModels.add(pm);
}
ModelAndView mav = new ModelAndView("foundPersons");
mav.addObject("foundPersons", bookModels);
return mav;
}
}
////////////////////////////////Repository////////////////////////
package com.dao;
import java.util.List;
import com.model.Person;
public interface PersonDAO {
public void save(Person p);
public List<Person> list();
public void updatePerson(Integer id);
public Person getPersonById(int id);
public void removePerson(Integer id);
public void indexPersons() throws Exception;
public List<Person> searchForPerson(String searchText) throws Exception;
}
////////////////////////////////Implementation////////////////////////
package com.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.model.Person;
#Transactional
#Repository
public class PersonDAOImpl implements PersonDAO, java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger logger = (Logger) LoggerFactory
.getLogger(PersonDAOImpl.class);
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
public void save(Person p) {
// TODO Auto-generated method stub
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
s.saveOrUpdate(p);
tx.commit();
s.close();
System.out.println("Record successfully inserted");
}
#SuppressWarnings("deprecation")
public List<Person> list() {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
#SuppressWarnings("unchecked")
List<Person> personsList = session.createQuery("from Person").list();
for (Person p : personsList) {
logger.info("Person List::" + p);
}
return personsList;
}
public void updatePerson(Integer id) {
Session session = new Configuration().configure().buildSessionFactory()
.openSession();
Person p = new Person();
Person person = session.get(Person.class, p.getId());
//Transaction t = session.beginTransaction();
Query query = session.createQuery("from Person");
person.setName(p.getName()); // modify the loaded object somehow
session.update(person);
//t.commit();
session.close();
}
public Person getPersonById(int id) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
Person p = (Person) session.load(Person.class, new Integer(id));
logger.info("Person loaded successfully, Person details=" + p);
return p;
}
public void removePerson(Integer id) {
Session session = sessionFactory.getCurrentSession();
// Transaction t = session.beginTransaction();
Person p = (Person) session.load(Person.class, new Integer(id));
session.delete(p);
// t.commit();
logger.info("Person deleted successfully, person details=");
}
#Transactional
public void indexPersons() throws Exception{
// TODO Auto-generated method stub
try
{
Session session = sessionFactory.getCurrentSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
fullTextSession.createIndexer().startAndWait();
}
catch(Exception e)
{
throw e;
}
}
public List<Person> searchForPerson(String searchText) throws Exception{
// TODO Auto-generated method stub
try
{
Session session = sessionFactory.getCurrentSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
QueryBuilder qb = fullTextSession.getSearchFactory()
.buildQueryBuilder().forEntity(Person.class).get();
org.apache.lucene.search.Query query = qb
.keyword().onFields("name", "address", "salary","gender")
.matching(searchText)
.createQuery();
org.hibernate.Query hibQuery =
fullTextSession.createFullTextQuery(query, Person.class);
List<Person> results = hibQuery.list();
return results;
}
catch(Exception e)
{
throw e;
}
}
}
//////////////////////////MODEL////////////////////////////
package com.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Store;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;
#Entity
public class Person {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#NotEmpty #NotNull(message="Name is required!")
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String name;
#Size(min=5, max=10, message="Your address should be between 5 - 10 characters.")
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String address;
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private Integer salary;
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String gender;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
////////////////////////////////Service/////////////////////////////////
package com.service;
import java.util.List;
import com.model.Person;
public interface PersonService {
public void save(Person p);
public List<Person> list();
public void updatePerson(Integer id);
public Person getPersonById(int id);
public void removePerson(Integer id);
public void indexPersons() throws Exception;
public List<Person> searchForPerson(String searchText) throws Exception;
}
//////////////////////////////////////Service Implementation/////////////
package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dao.PersonDAO;
import com.model.Person;
#Service("PersonService")
public class PersonServiceImpl implements PersonService {
#Autowired
private PersonDAO pdao;
#Transactional
public void save(Person p) {
// TODO Auto-generated method stub
pdao.save(p);
}
public List<Person> list() {
// TODO Auto-generated method stub
return pdao.list();
}
public void updatePerson(Integer id) {
// TODO Auto-generated method stub
pdao.updatePerson(id);
}
public Person getPersonById(int id) {
// TODO Auto-generated method stub
return this.pdao.getPersonById(id);
}
public void removePerson(Integer id) {
// TODO Auto-generated method stub
pdao.removePerson(id);
}
public void indexPersons() throws Exception {
// TODO Auto-generated method stub
pdao.indexPersons();
}
public List<Person> searchForPerson(String searchText) throws Exception {
// TODO Auto-generated method stub
return null;
}
}
//////////////////////////////index.jsp/////////////////////
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://www.springframework.org/tags/form"
prefix="springForm"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<meta charset="utf-8">
<title>Welcome</title>
</head>
<body>
<h2>Hello World!</h2>
<h3>Add Person</h3>
<table border="1">
<tr>
<th>id</th>
<td>name<springForm:errors path='${p.name}' /></td>
<td>address<springForm:errors path='${p.address}' /></td>
<td>gender<springForm:errors path='${p.gender}' /></td>
<td>salary<springForm:errors path='${p.salary}' /></td></tr>
<c:forEach var="p" items='${personsList}' varStatus="status">
<tr>
<td>${p.id}</td>
<td>${p.name}</td>
<td>${p.address}</td>
<td>${p.gender}</td>
<td>${p.salary}</td>
<td>
Edit
Delete
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
///////////////////////////////////search.jsp//////////////////
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://www.springframework.org/tags/form"
prefix="springForm"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!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>Search Page</title>
</head>
<body>
<springForm:form action="/MainAssignment3/doSearch" method="POST" commandName="p">
<c:forEach var="p" items='${foundPersons}' varStatus="status">
<td>${p.name}</td>
<td>${p.address}</td>
<td>${p.gender}</td>
<td>${p.salary}</td>
</c:forEach>
</springForm:form>
</body>
</html>
//////////////////////////////AddPerson.jsp/////////////////////////////
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://www.springframework.org/tags/form"
prefix="springForm"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!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>Add Person</title>
</head>
<body>
<h1>Employee Registration Form</h1>
<springForm:form action="/MainAssignment3/save" method="POST"
commandName="person">
<table style="border: thin; border: ridge;">
<tr>
<td>Enter Name:</td>
<td bordercolor="#FF0000" ><springForm:input path="name"
placeholder="Enter Name" /></td>
<td><springForm:errors path="name" /></td>
</tr>
<tr>
<td>Enter address:</td>
<td><input type="text" name="address" placeholder="Enter Address" ></td>
<td><springForm:errors path="address" /></td>
</tr>
<tr>
<td>Enter gender:</td>
<td><springForm:input path="gender" id="gender" placeholder="Enter Gender" /></td>
<%-- <td><springForm:errors path="gender" /></td> --%>
</tr>
<tr>
<td>Enter salary:</td>
<td><input type="text" name="salary" placeholder="Enter Salary" ></td>
<td><springForm:errors path="salary" /></td>
<td style="padding-left: 110px;"></td>
</tr>
<tr>
<td><input type="submit"value="submit"></td>
</tr>
</table>
</springForm:form>
</body>
</html>
/////////////////////////////////////updatePerson.jsp/////////////////////
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://www.springframework.org/tags/form"
prefix="springForm"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!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>Update Person</title>
</head>
<body>
<springForm:form action="/MainAssignment3/update" method="POST" commandName="person">
<table style="border: thin; border: ridge;">
<tr>
<td><input type="hidden" name="id" value="${id}"></td>
</tr>
<tr>
<td>Enter Name:</td>
<td bordercolor="#FF0000" >
<springForm:input path="name" placeholder="Enter Name" value='${name}'/></td>
<%-- <td><springForm:errors path="name" /></td> --%>
</tr>
<tr>
<td>Enter address:</td>
<td><springForm:input path="address" id="address" placeholder="Enter Address" value='${address}'/></td>
<%-- <td><springForm:errors path='${p1.address}'/></td> --%>
</tr>
<tr>
<td>Enter gender:</td>
<td><springForm:input path="gender" id="gender" placeholder="Enter Gender" value='${gender}' /></td>
<%-- <td><springForm:errors path='${p1.gender}'/></td> --%>
</tr>
<tr>
<td>Enter salary:</td>
<td><springForm:input path="salary" id="salary" placeholder="Enter Salary" value='${salary}'/></td>
<%-- <td><springForm:errors path='${p1.salary}' /></td> --%>
<td style="padding-left: 110px;"></td>
</tr>
<tr>
<td><input type="submit"value="submit"></td>
</tr>
</table>
</springForm:form>
</body>
</html>
Please help . Below is my code to redirect the request with two attributes to JSP but both of the below two attributes returns the value of passWord .
1)user_Name
2)Pass_word
for example , ABC is my username and XYZ is my password which is get from the "FORM" but my second value i.e the value of the passWord variable is appears in both of the attribute.
printing inside the jsp page :
user_Name: XYS (Should be ABC instead of XYZ)
pass_Word: XYZ
servlet :
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class JndiConn extends HttpServlet implements Servlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String userName=request.getParameter("Username");
String passWord=request.getParameter("password");
String user_Name="";
request.setAttribute(user_Name,userName);
String pass_Word="";
request.setAttribute(pass_Word,passWord);
RequestDispatcher rd=request.getRequestDispatcher ("GetParameter.jsp");
System.out.println(userName);
System.out.println(passWord);
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
Connection connection = getConnection();
if (connection != null) {
String sql = "SELECT count(1) FROM scott.login_user where login_id ='"+userName+"' and password='"+passWord+"'";
String sql1 = "select SYSDATE from dual";
System.out.println(sql);
try{
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
int number=rs.getInt("count(1)");
System.out.println("Result value is "+number);
if(number==1)
{
System.out.println("THE LOGIN SUCCESS FOR::"+userName);
String sql2 = "INSERT INTO SCOTT.LOGIN_USER VALUES(3,'VINOTH','vinoth55','SCOTT',to_date('08/06/13','DD/MM/RR'),105)";
PreparedStatement statement1 = connection.prepareStatement(sql2);
ResultSet rs1 = statement1.executeQuery();
rd.forward(request, response);
}
else{
System.out.println("THE LOGIN FAILURE FOR "+userName);
rd.forward(request, response);
}
}
connection.close();
}catch(Exception e){
System.out.println(e);
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
private Connection getConnection() {
Connection connection = null;
try {
InitialContext context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("vinothprd");
connection = dataSource.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
Below is my JSP to print the user_Name and pass_Word :
JSP:
String user_Name="";
String userName=(String)request.getAttribute(user_Name);
String pass_Word="";
String passWord=(String)request.getAttribute(pass_Word);
System.out.println("user_Name: "+userName);
System.out.println("pass_Word: "+passWord);
Thanks for your help in advance...
In Servlet you are setting, attributes using empty value.
String user_Name="";
request.setAttribute(user_Name,userName);
String pass_Word="";
request.setAttribute(pass_Word,passWord);
First of all, this is wrong and I don't know why you are doing this.
In JSP, When you access request.getAttribute(user_Name); // which is empty "",
you will get the value of password as username was overridden.
Solution:
You should set attribute like
EDIT Servlet
String userName=request.getParameter("Username");
String passWord=request.getParameter("password");
String user_Name="userName";
request.setAttribute(user_Name, userName);
String pass_Word="passWord";
request.setAttribute(pass_Word, passWord);
then in JSP
String user_Name="userName"
String userName=(String) request.getAttribute(user_Name);
String pass_Word="passWord";
String passWord=(String)request.getAttribute(pass_Word);
See: http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#setAttribute